<?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 Illuminate\Routing\Controller;
use Illuminate\Http\Request;
use Carbon\Carbon;

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

        // Get project IDs managed by this PM
        $managedProjectIds = ProjectTeam::where('pt_staff_id', $user->employeeCode)
            ->where('role_id', 1) // assuming 2 = PM
            ->pluck('fk_project_id')
            ->toArray();

        // Get claims only for those projects
        $claims = Claim::with(['user', 'project'])
            ->whereIn('project_id', $managedProjectIds)
            ->get();

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

    public function show($id)
    {
        // load claim
        $claim = Claim::with(['project', 'jenisKenderaan'])->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->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;
        $claim->display_total_claim_amount = ($calculatedAmount - $displayPenalty);

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