<?php

namespace Portal\Mileage\Http\Controllers;

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

class ProjectManagerController extends Controller
{
    /**
     * Display the project manager dashboard (monthly view only).
     */
    public function index(Request $request)
    {
        $manager = Auth::user();
        $month = $request->input('month', Carbon::now()->format('Y-m'));

        try {
            // validate the format (YYYY-MM)
            if (!preg_match('/^\d{4}-\d{2}$/', $month)) {
                $month = now()->format('Y-m');
            }
            $parsedMonth = Carbon::createFromFormat('Y-m', $month);
        } catch (\Exception $e) {
            $month = now()->format('Y-m');
            $parsedMonth = Carbon::createFromFormat('Y-m', $month);
        }


        // Get project IDs assigned to this Project Manager
        $projectIds = \Portal\Mileage\Model\ProjectTeam::where('pt_staff_id', $manager->employeeCode)
            ->where('role_id', 1) //  "Project Manager" role
            ->pluck('fk_project_id');

        // Get projects under the PM
        $projects = \Portal\Mileage\Model\Project::whereIn('id', $projectIds)->get();

        // Get all claims for those projects in the selected month
        $claims = \Portal\Mileage\Model\Claim::with(['user', 'project'])
            ->whereIn('project_id', $projectIds)
            ->whereMonth('claim_date', $parsedMonth->month)
            ->whereYear('claim_date', $parsedMonth->year)
            ->get();

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


    /**
     * Show all claims for one staff for the selected month.
     */
    public function show($projectId, $userId, Request $request)
    {
        $month = $request->input('month', Carbon::now()->format('Y-m'));

        try {
            if (!preg_match('/^\d{4}-\d{2}$/', $month)) {
                $month = now()->format('Y-m');
            }
            $parsedMonth = Carbon::createFromFormat('Y-m', $month);
        } catch (\Exception $e) {
            $month = now()->format('Y-m');
            $parsedMonth = Carbon::createFromFormat('Y-m', $month);
        }


        $project = \Portal\Mileage\Model\Project::findOrFail($projectId);
        $user = \Portal\Mileage\Model\Users::findOrFail($userId);

        $claims = \Portal\Mileage\Model\Claim::with(['project'])
            ->where('project_id', $projectId)
            ->where('user_id', $userId)
            ->whereMonth('claim_date', $parsedMonth->month)
            ->whereYear('claim_date', $parsedMonth->year)
            ->orderBy('claim_date', 'asc')
            ->get();

        return view('mileage::projectManager.show', compact('project', 'user', 'claims', 'month'));
    }

    /**
     * Approve all pending claims for a specific project in the selected month.
     */
    public function approveMonth(Request $request)
    {
        $manager = Auth::user();
        $monthLabel = $request->input('month');
        $projectId = $request->input('project_id');

        // require project_id
        if (!$projectId) {
            return back()->with('error', 'Sila pilih projek untuk disokong.');
        }

        // validate month format (expects YYYY-MM)
        try {
            if (!preg_match('/^\d{4}-\d{2}$/', $monthLabel)) {
                throw new \Exception('Invalid month format');
            }
            $parsedMonth = Carbon::createFromFormat('Y-m', $monthLabel);
        } catch (\Exception $e) {
            return back()->with('error', 'Format bulan tidak sah. Sila pilih semula bulan dalam format YYYY-MM.');
        }

        // ensure manager oversees this project
        $allowedProjectIds = ProjectTeam::where('pt_staff_id', $manager->employeeCode)
            ->where('role_id', 1) // project manager role
            ->pluck('fk_project_id')
            ->toArray();

        if (!in_array($projectId, $allowedProjectIds)) {
            return back()->with('error', 'Anda tidak dibenarkan melakukan tindakan ini untuk projek terpilih.');
        }

        // update only claims for this project and month with status 'Diproses'
        $approvedCount = Claim::where('project_id', $projectId)
            ->whereMonth('claim_date', $parsedMonth->month)
            ->whereYear('claim_date', $parsedMonth->year)
            ->where('status', 'Diproses')
            ->update([
                'status' => 'Disokong',
                'approved_by' => $manager->id,
                'updated_at' => now(),
            ]);

        if ($approvedCount > 0) {
            return back()->with('success', $approvedCount . ' tuntutan telah disokong untuk projek ini bagi bulan ' . $monthLabel . '.');
        }

        return back()->with('warning', 'Tiada tuntutan "Diproses" untuk disokong bagi projek ini pada bulan ' . $monthLabel . '.');
    }

    /**
     * Reject all pending claims for a specific project in the selected month.
     */
    public function rejectMonth(Request $request)
    {
        $manager = Auth::user();
        $monthLabel = $request->input('month');
        $projectId = $request->input('project_id');

        if (!$projectId) {
            return back()->with('error', 'Sila pilih projek untuk ditolak.');
        }

        // validate month format (expects YYYY-MM)
        try {
            if (!preg_match('/^\d{4}-\d{2}$/', $monthLabel)) {
                throw new \Exception('Invalid month format');
            }
            $parsedMonth = Carbon::createFromFormat('Y-m', $monthLabel);
        } catch (\Exception $e) {
            return back()->with('error', 'Format bulan tidak sah. Sila pilih semula bulan dalam format YYYY-MM.');
        }

        // ensure manager oversees this project
        $allowedProjectIds = ProjectTeam::where('pt_staff_id', $manager->employeeCode)
            ->where('role_id', 1)
            ->pluck('fk_project_id')
            ->toArray();

        if (!in_array($projectId, $allowedProjectIds)) {
            return back()->with('error', 'Anda tidak dibenarkan melakukan tindakan ini untuk projek terpilih.');
        }

        // update only claims for this project and month with status 'Diproses'
        $rejectedCount = Claim::where('project_id', $projectId)
            ->whereMonth('claim_date', $parsedMonth->month)
            ->whereYear('claim_date', $parsedMonth->year)
            ->where('status', 'Diproses')
            ->update([
                'status' => 'Ditolak',
                'rejected_by' => $manager->id,
                'updated_at' => now(),
            ]);

        if ($rejectedCount > 0) {
            return back()->with('success', $rejectedCount . ' tuntutan telah ditolak untuk projek ini bagi bulan ' . $monthLabel . '.');
        }

        return back()->with('warning', 'Tiada tuntutan "Diproses" untuk ditolak bagi projek ini pada bulan ' . $monthLabel . '.');
    }
}
