<?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;
use Maatwebsite\Excel\Facades\Excel;
use Portal\Mileage\Exports\ClaimsExport; 
use DB;

class HRController extends Controller
{
    public function index(Request $request)
    {
        $month = $request->input('month', Carbon::now()->format('Y-m'));
        $parsedMonth = Carbon::parse($month);

        // Group claims by staff for the selected month
        $claims = Claim::with('user')
            ->whereMonth('claim_date', $parsedMonth->month)
            ->whereYear('claim_date', $parsedMonth->year)
            ->get()
            ->groupBy('user_id');

        $users = $claims->map(function ($claimsForUser) {
            $user = $claimsForUser->first()->user;
            return [
                'id' => $user->id,
                'name' => $user->name ?? '-',
                'total_claims' => $claimsForUser->count(),
                'total_amount' => $claimsForUser->sum('total_claim_amount'),
            ];
        });

        return view('mileage::hr.index', compact('users', 'month'));
    }

    /**
     * Show individual claim details
     */
    public function show($userId, Request $request)
    {
        $month = $request->input('month', Carbon::now()->format('Y-m'));
        $parsedMonth = Carbon::parse($month);

        $user = Users::findOrFail($userId);

        $claims = Claim::where('user_id', $userId)
            ->whereMonth('claim_date', $parsedMonth->month)
            ->whereYear('claim_date', $parsedMonth->year)
            ->orderBy('claim_date', 'asc')
            ->get();

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

    /**
     * Show a single claim (HR detailed view)
     */
    public function viewEach($id)
    {
        $claim = Claim::with(['user', 'project', 'jenisKenderaan'])->findOrFail($id);
        return view('mileage::HR.view', compact('claim'));
    }


    /**
     * Reject claim (HR decision)
     */
    public function reject($id)
    {
        $hr = Auth::user();
        $claim = Claim::findOrFail($id);

        $claim->status = 'Ditolak';
        $claim->rejected_by = $hr->id; // record who rejected it
        $claim->save();

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

    /**
     * Export all claims to Excel
     */
    public function export(Request $request)
    {
        $userId = $request->input('user_id');
        $month  = $request->input('month');

        // parse month safely
        $parsedMonth = $month ? Carbon::parse($month) : null;

        // fetch user
        $user = $userId ? Users::find($userId) : null;

        // query claims by filter
        $claims = Claim::with(['user', 'project'])
            ->when($userId, fn($q) => $q->where('user_id', $userId))
            ->when($parsedMonth, fn($q) => 
                $q->whereMonth('claim_date', $parsedMonth->month)
                  ->whereYear('claim_date', $parsedMonth->year)
            )
            ->orderBy('claim_date', 'asc')
            ->get();

        // if no data found, return with warning
        if ($claims->isEmpty()) {
            return back()->with('error', 'Tiada tuntutan dijumpai untuk penapis yang dipilih.');
        }

        // build filename dynamically
        $staffName = $user ? str_replace(' ', '_', strtoupper($user->name)) : 'SEMUA_STAF';
        $monthName = $parsedMonth ? $parsedMonth->format('m-Y') : Carbon::now()->format('m-Y');
        $fileName  = "Tuntutan_{$staffName}_{$monthName}.xlsx";

        // generate Excel using filtered data
        return Excel::download(new ClaimsExport($user, $claims), $fileName);

    }
}

