<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Attendance;
use App\Models\AuditLog;
use App\Models\Department;
use App\Models\Employee;
use App\Models\LeaveRequest;
use Carbon\Carbon;
use Carbon\CarbonPeriod;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class LeaveRequestController extends Controller
{
    public function index(Request $request)
    {
        $query = LeaveRequest::with(['employee.department', 'employee.position', 'approver']);

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        if ($request->filled('type')) {
            $query->where('type', $request->type);
        }

        if ($request->filled('department_id')) {
            $query->whereHas('employee', function ($q) use ($request) {
                $q->where('department_id', $request->department_id);
            });
        }

        $leaveRequests = $query->latest()->paginate(12)->withQueryString();

        $totalPending = LeaveRequest::where('status', 'pending')->count();
        $totalApproved = LeaveRequest::where('status', 'approved')->count();
        $totalRejected = LeaveRequest::where('status', 'rejected')->count();

        $departments = Department::all();

        return view('admin.leave_requests.index', compact(
            'leaveRequests',
            'totalPending',
            'totalApproved',
            'totalRejected',
            'departments'
        ));
    }

    public function approve(Request $request, LeaveRequest $leaveRequest)
    {
        DB::transaction(function () use ($leaveRequest) {
            $leaveRequest->update([
                'status' => 'approved',
                'approved_by' => Auth::id(),
                'approved_at' => now(),
            ]);

            // Deduct leave balance if type is 'leave' (cuti)
            if ($leaveRequest->type === 'leave') {
                $employee = $leaveRequest->employee;
                if ($employee) {
                    $employee->decrement('leave_balance', $leaveRequest->total_days);
                }
            }

            // Automatically generate/update attendance records for the leave period
            $period = CarbonPeriod::create($leaveRequest->start_date, $leaveRequest->end_date);
            $statusMap = [
                'permit' => 'permit',
                'sick' => 'sick',
                'leave' => 'leave',
            ];
            $attStatus = $statusMap[$leaveRequest->type] ?? 'permit';

            foreach ($period as $date) {
                Attendance::updateOrCreate(
                    [
                        'employee_id' => $leaveRequest->employee_id,
                        'attendance_date' => $date->toDateString(),
                    ],
                    [
                        'status' => $attStatus,
                        'notes' => 'Pengajuan ' . $leaveRequest->type_label . ' disetujui: ' . $leaveRequest->reason,
                    ]
                );
            }

            AuditLog::log('Approve Izin/Cuti', "Menyetujui {$leaveRequest->type_label} karyawan {$leaveRequest->employee?->name}");
        });

        return back()->with('success', 'Pengajuan izin/cuti berhasil disetujui dan status presensi telah diperbarui.');
    }

    public function reject(Request $request, LeaveRequest $leaveRequest)
    {
        $validated = $request->validate([
            'rejection_note' => ['required', 'string'],
        ]);

        $leaveRequest->update([
            'status' => 'rejected',
            'approved_by' => Auth::id(),
            'approved_at' => now(),
            'rejection_note' => $validated['rejection_note'],
        ]);

        AuditLog::log('Reject Izin/Cuti', "Menolak {$leaveRequest->type_label} karyawan {$leaveRequest->employee?->name}");

        return back()->with('success', 'Pengajuan izin/cuti telah ditolak.');
    }
}
