<?php

namespace App\Http\Controllers;

use App\Models\Employee;
use App\Models\Holiday;
use App\Models\LeaveRequest;
use Carbon\Carbon;
use Illuminate\Http\Request;

class ScheduleController extends Controller
{
    public function index(Request $request)
    {
        $month = Carbon::createFromFormat('Y-m', $request->query('month', now()->format('Y-m')))->startOfMonth();
        $employees = Employee::where('status', 'Aktif')->orderBy('role')->orderBy('name')->get();
        $nurses = $employees->where('role', '!=', 'Pimpinan')->values();
        $holidays = Holiday::whereBetween('date', [$month->copy()->startOfMonth(), $month->copy()->endOfMonth()])->get()->keyBy(fn ($item) => $item->date->format('Y-m-d'));
        $leaves = LeaveRequest::with('employee')->where('status', '!=', 'Ditolak')->whereDate('end_date', '>=', $month->copy()->startOfMonth())->whereDate('start_date', '<=', $month->copy()->endOfMonth())->orderBy('start_date')->get();

        $calendarStart = $month->copy()->startOfMonth()->startOfWeek(Carbon::MONDAY);
        $calendarDays = collect(range(0, 41))->map(function (int $offset) use ($calendarStart, $month, $holidays, $leaves) {
            $date = $calendarStart->copy()->addDays($offset);
            $key = $date->format('Y-m-d');
            $leaveCount = $leaves->filter(fn ($leave) => $date->betweenIncluded($leave->start_date, $leave->end_date))->count();

            return [
                'date' => $date,
                'current_month' => $date->month === $month->month,
                'holiday' => $holidays->get($key),
                'leave_count' => $leaveCount,
            ];
        });

        return view('schedule', compact('month', 'employees', 'nurses', 'holidays', 'leaves', 'calendarDays'));
    }

    public function storeLeave(Request $request)
    {
        $data = $request->validate([
            'employee_id' => ['required', 'exists:employees,id'],
            'type' => ['required', 'in:Cuti,Izin,Sakit,Libur Pengganti'],
            'start_date' => ['required', 'date'],
            'end_date' => ['required', 'date', 'after_or_equal:start_date'],
            'notes' => ['nullable', 'string', 'max:1000'],
        ]);

        LeaveRequest::create($data + ['status' => 'Menunggu']);

        return back()->with('success', 'Pengajuan berhasil dikirim.');
    }
}
