<?php

namespace App\Http\Controllers\Admin\Finance\Payroll;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Models\Attendance;
use App\Models\Employee;

class AttendanceController extends Controller
{
    public function store(Request $request)
    {
        $request->validate([
            'employee_id' => 'required|exists:employees,id',
            'date' => 'required|date',
            'check_in' => 'nullable|date_format:H:i',
            'check_out' => 'nullable|date_format:H:i|after_or_equal:check_in',
            'overtime_hours' => 'nullable|numeric|min:0',
            'status' => 'required|in:Present,Absent,Leave',
        ]);

        Attendance::create($request->all());

        return redirect()->route('admin.finance.payroll.attendance')->with('success', 'Attendance logged successfully.');
    }

    public function edit(Attendance $attendance)
    {
        $employees = Employee::all();
        return view('admin.finance.payroll.edit-attendance', compact('attendance', 'employees'));
    }

    public function update(Request $request, Attendance $attendance)
    {
        $request->validate([
            'employee_id' => 'required|exists:employees,id',
            'date' => 'required|date',
            'check_in' => 'nullable|date_format:H:i',
            'check_out' => 'nullable|date_format:H:i|after_or_equal:check_in',
            'overtime_hours' => 'nullable|numeric|min:0',
            'status' => 'required|in:Present,Absent,Leave',
        ]);

        $attendance->update($request->all());

        return redirect()->route('admin.finance.payroll.attendance')->with('success', 'Attendance updated successfully.');
    }

    public function destroy(Attendance $attendance)
    {
        $attendance->delete();

        return redirect()->route('admin.finance.payroll.attendance')->with('success', 'Attendance deleted successfully.');
    }
}
