<?php

namespace App\Http\Controllers;

use App\Models\Project;
use App\Models\ProjectPhase;
use App\Models\ProjectApproval;
use Illuminate\Http\Request;

class ProjectPhaseController extends Controller
{
    public function listPhases($projectId)
    {
        $project = Project::findOrFail($projectId);
        return response()->json([
            'project' => $project,
            'phases' => $project->phases()->get(),
            'progress' => $this->calculateProgress($project),
        ]);
    }

    public function getPhase($projectId, $phaseId)
    {
        $phase = ProjectPhase::where('project_id', $projectId)
            ->findOrFail($phaseId);
        
        return response()->json([
            'phase' => $phase,
            'approvals' => $phase->approvals()->get(),
            'documents' => $phase->project->documents()
                ->where('phase_number', $phase->phase_number)
                ->get(),
        ]);
    }

    public function updatePhaseProgress($projectId, $phaseId, Request $request)
    {
        $phase = ProjectPhase::where('project_id', $projectId)
            ->findOrFail($phaseId);

        $validated = $request->validate([
            'progress_percentage' => 'integer|min:0|max:100',
            'status' => 'string|in:pending,in_progress,completed,on_hold',
        ]);

        $phase->update($validated);

        ProjectAuditLog::log(
            $phase->project,
            'phase_progress_updated',
            "Phase {$phase->name} progress updated to {$validated['progress_percentage']}%",
            auth()->user(),
            'phase',
            $phase->id
        );

        return response()->json(['success' => true, 'phase' => $phase]);
    }

    public function startPhase($projectId, $phaseId, Request $request)
    {
        $phase = ProjectPhase::where('project_id', $projectId)
            ->findOrFail($phaseId);

        $phase->update([
            'status' => 'in_progress',
            'actual_start_date' => now(),
        ]);

        ProjectAuditLog::log(
            $phase->project,
            'phase_started',
            "Phase {$phase->name} has been started",
            auth()->user(),
            'phase',
            $phase->id
        );

        return response()->json(['success' => true, 'phase' => $phase]);
    }

    public function completePhase($projectId, $phaseId, Request $request)
    {
        $phase = ProjectPhase::where('project_id', $projectId)
            ->findOrFail($phaseId);

        $validated = $request->validate([
            'completion_notes' => 'nullable|string',
        ]);

        // Check if all required approvals are met
        $requiredApprovals = $phase->required_approvals ?? [];
        $pendingApprovals = ProjectApproval::where('approval_type', 'phase_completion')
            ->where('approval_number', $phase->id)
            ->where('status', 'pending')
            ->count();

        if ($pendingApprovals > 0 && !empty($requiredApprovals)) {
            return response()->json([
                'success' => false,
                'message' => 'All required approvals must be completed first',
            ], 422);
        }

        $phase->markComplete($validated['completion_notes'] ?? null);

        ProjectAuditLog::log(
            $phase->project,
            'phase_completed',
            "Phase {$phase->name} has been marked as completed",
            auth()->user(),
            'phase',
            $phase->id
        );

        return response()->json(['success' => true, 'phase' => $phase]);
    }

    public function requestApproval($projectId, $phaseId, Request $request)
    {
        $phase = ProjectPhase::where('project_id', $projectId)
            ->findOrFail($phaseId);

        $validated = $request->validate([
            'required_role' => 'required|string',
            'notes' => 'nullable|string',
        ]);

        $approval = ProjectApproval::create([
            'project_id' => $projectId,
            'approval_type' => 'phase_completion',
            'approval_number' => $phase->id,
            'required_role' => $validated['required_role'],
            'status' => 'pending',
            'requested_by' => auth()->id(),
            'requested_at' => now(),
        ]);

        ProjectAuditLog::log(
            $phase->project,
            'approval_requested',
            "Approval requested from {$validated['required_role']} for phase {$phase->name}",
            auth()->user(),
            'approval',
            $approval->id
        );

        return response()->json(['success' => true, 'approval' => $approval]);
    }

    private function calculateProgress(Project $project)
    {
        $phases = $project->phases()->get();
        if ($phases->isEmpty()) {
            return 0;
        }

        $totalProgress = $phases->sum('progress_percentage');
        return round($totalProgress / $phases->count());
    }
}
