<?php

namespace Portal\Mileage\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use Portal\Mileage\Model\Users;
use Portal\Mileage\Model\Claim;

class HODController extends Controller
{
    public function index()
    {
        $hod = Auth::user();

        // check if HOD has staff info
        if (!$hod || !$hod->staffInfo) {
            return back()->with('error', 'Maklumat jabatan HOD tidak dijumpai.');
        }

        $departmentId = $hod->staffInfo->fk_lkp_department;

        // get all staff IDs under the same department
        $staffIds = Users::whereHas('staffInfo', function ($query) use ($departmentId) {
            $query->where('fk_lkp_department', $departmentId);
        })->pluck('id');

        // fetch claims under the HOD’s department
        $claims = Claim::with(['user', 'project'])
            ->whereIn('user_id', $staffIds)
            ->whereNull('project_id')
            ->where(function ($q) use ($hod) {
                $q->whereIn('status', ['Diproses', 'Disokong']) // pending for review
                ->orWhere(function ($sub) use ($hod) {
                    // Only show rejected claims that were rejected by THIS HOD
                    $sub->where('status', 'Ditolak')
                        ->where('rejected_by', $hod->id);
                });
            })
            ->orderBy('claim_date', 'desc')
            ->get();

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

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

        // Deduct first 40 km
        $totalMileage = $claim->total_mileage ?? 0;
        $claim->claimable_mileage = max(0, $totalMileage - 40);

        // Penalty logic
        $claimDate = Carbon::parse($claim->claim_date);
        $submissionDate = $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';
        }

        $claim->display_penalty_amount = $displayPenalty;
        $claim->display_penalty_reason = $displayReason;
        $claim->display_total_claim_amount =
            ($calculatedAmount + ($claim->toll_amount ?? 0) + ($claim->others_amount ?? 0)) - $displayPenalty;

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

    public function verify($id)
    {
        $hod = Auth::user();
        $claim = Claim::with('user.staffInfo')->findOrFail($id);

        // Check if claim is from HOD’s department
        $hodDept = $hod->staffInfo->fk_lkp_department ?? null;
        $claimDept = $claim->user->staffInfo->fk_lkp_department ?? null;

        if ($hodDept !== $claimDept) {
            return back()->with('error', 'Anda tidak dibenarkan menyokong tuntutan ini.');
        }

        $claim->status = 'Disokong';
        $claim->approved_by = $hod->id;
        $claim->save();

        return back()->with('success', 'Tuntutan berjaya disokong.');
    }

    public function reject($id)
    {
        $hod = Auth::user();
        $claim = Claim::with('user.staffInfo')->findOrFail($id);

        $hodDept = $hod->staffInfo->fk_lkp_department ?? null;
        $claimDept = $claim->user->staffInfo->fk_lkp_department ?? null;

        if ($hodDept !== $claimDept) {
            return back()->with('error', 'Anda tidak dibenarkan menolak tuntutan ini.');
        }

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

        return back()->with('error', 'Tuntutan telah ditolak.');
    }
}
