<?php

namespace Portal\Mileage\Http\Controllers;

use Portal\Mileage\Model\Users;
use Portal\Mileage\Model\Project;
use Portal\Mileage\Model\JenisKenderaan;
use Portal\Mileage\Model\Claim;
use Portal\Mileage\Model\ProjectTeam;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Carbon\Carbon;

use Illuminate\Support\Facades\Auth;

class ProjectDirectorController extends Controller
{
    public function index()
    {
        $user = auth()->user();

        // Get project IDs where this user is the Project Director
        $directedProjectIds = ProjectTeam::where('pt_staff_id', $user->employeeCode)
            ->where('role_id', 7) // 7 = Project Director
            ->pluck('fk_project_id')
            ->toArray();

        // Get claims for those projects, only after PM verification
        $claims = Claim::with(['user', 'project'])
            ->whereIn('project_id', $directedProjectIds)
            ->whereIn('status', ['Disahkan', 'Ditolak']) // Only show claims verified by Project Manager
            ->orderBy('created_at', 'desc')
            ->get();

        return view('mileage::projectDirector.index', compact('claims'));
    }

    public function show($id)
    {
       // load claim
        $claim = Claim::with(['project', 'jenisKenderaan', 'user'])->findOrFail($id);

        // Recompute penalty for display based on actual submission date (created_at)
        // so show page always displays correct reason even if saved earlier incorrectly.
        $claimDate = Carbon::parse($claim->claim_date);
        $submissionDate = $claim->submission_date ?? $claim->created_at ?? Carbon::now();
        $daysDiff = $claimDate->diffInDays($submissionDate);

        $calculatedAmount = $claim->calculated_amount ?? 0;

        if ($daysDiff <= 30) {
            $displayPenalty = 0;
            $displayReason = 'Tiada penalti (≤ 1 bulan)';
        } elseif ($daysDiff <= 90) {
            $displayPenalty = $calculatedAmount * 0.10;
            $displayReason = 'Lewat hantar >1 ≤3 bulan (10%)';
        } elseif ($daysDiff <= 180) {
            $displayPenalty = $calculatedAmount * 0.30;
            $displayReason = 'Lewat hantar >3 ≤6 bulan (30%)';
        } else {
            $displayPenalty = 0;
            $displayReason = 'Tertakluk kepada BOD';
        }

        // Attach computed display-only properties (won't persist to DB)
        $claim->display_penalty_amount = $displayPenalty;
        $claim->display_penalty_reason = $displayReason;
        $totalClaim = ($calculatedAmount + ($claim->toll_amount ?? 0) + ($claim->others_amount ?? 0)) - $displayPenalty;
        $claim->display_total_claim_amount = $totalClaim;

        return view('mileage::projectDirector.show', compact('claim'));
    }


    public function approve($id)
    {
        $user = auth()->user();

        $claim = Claim::findOrFail($id);
        $claim->status = 'Disahkan';

        $allowedProjectIds = ProjectTeam::where('pt_staff_id', $user->employeeCode)
            ->where('role_id', 7)
            ->pluck('fk_project_id')
            ->toArray();

        if (!in_array($claim->project_id, $allowedProjectIds)) {
            return back()->with('error', 'Anda tidak dibenarkan meluluskan tuntutan ini.');
        }

        $claim->status = 'Disahkan';
        $claim->save();

        return back()->with('success', 'Claim approved successfully.');
    }

    public function reject($id)
    {
        $claim = Claim::findOrFail($id);
        $user = auth()->user();

        $allowedProjectIds = ProjectTeam::where('pt_staff_id', $user->employeeCode)
            ->where('role_id', 7)
            ->pluck('fk_project_id')
            ->toArray();

        if (!in_array($claim->project_id, $allowedProjectIds)) {
            return back()->with('error', 'Anda tidak dibenarkan menolak tuntutan ini.');
        }

        $claim->status = 'Ditolak';
        $claim->save();

        return back()->with('error', 'Claim rejected.');
    }
}
