<?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 BODController extends Controller
{
    public function index()
    {
        $bod = Auth::user();

        // Get all claims with no project, approved by HOD or previously verified
        $claims = Claim::with(['user', 'project'])
            ->whereNull('project_id')
            ->where(function ($query) use ($bod) {
                $query->whereIn('status', ['Disokong', 'Disahkan'])
                    ->orWhere(function ($sub) use ($bod) {
                        // Only show claims rejected by this specific BOD
                        $sub->where('status', 'Ditolak')
                            ->where('rejected_by', $bod->id);
                    });
            })
            ->orderBy('claim_date', 'desc')
            ->get();

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

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

        // Calculate claimable mileage
        $claim->claimable_mileage = max(0, $claim->total_mileage - 40);

        // Calculate penalties
        $claimDate = Carbon::parse($claim->claim_date);
        $submissionDate = $claim->created_at ?? Carbon::now();
        $daysDiff = $claimDate->diffInDays($submissionDate);

        $claimableMileage = max(0, ($claim->total_mileage ?? 0) - 40);
        if ($claim->jenis_kenderaan_id == 1) {
            $rate = ($claimableMileage <= 500) ? 0.55 : 0.50;
        } else {
            $rate = 0.30;
        }
        $calculatedAmount = round($claimableMileage * $rate, 2);

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

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

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

    public function approve($id)
    {
        $bod = Auth::user();
        $claim = Claim::findOrFail($id);

        if ($claim->status !== 'Disokong') {
            return back()->with('error', 'Tuntutan ini belum disokong oleh HOD.');
        }

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

        return back()->with('success', 'Tuntutan berjaya disahkan oleh BOD.');
    }

    public function reject($id)
    {
        $bod = Auth::user();
        $claim = Claim::findOrFail($id);

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

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