<?php

class AttendanceController extends Controller
{
    public function index(): void
    {
        Auth::requirePermission('attendance', 'view');

        $date = $this->input('date', date('Y-m-d'));
        $attendanceModel = new Attendance();

        $this->view('attendance.index', [
            'pageTitle' => 'Attendance',
            'date'      => $date,
            'staff'     => $attendanceModel->forDate($date),
            'summary'   => $attendanceModel->todaySummary(),
            'csrf'      => $this->csrfField(),
        ]);
    }

    public function store(): void
    {
        Auth::requirePermission('attendance', 'add');
        $this->verifyCsrf();

        $date = $this->input('date', date('Y-m-d'));
        $statuses = $this->input('status', []);
        $checkIns = $this->input('check_in', []);
        $checkOuts = $this->input('check_out', []);

        $attendanceModel = new Attendance();
        if (is_array($statuses)) {
            foreach ($statuses as $userId => $status) {
                if (!in_array($status, ['PRESENT', 'ABSENT', 'HALF_DAY', 'LEAVE'], true)) {
                    continue;
                }
                $attendanceModel->mark(
                    (int) $userId,
                    $date,
                    $status,
                    $checkIns[$userId] ?? null,
                    $checkOuts[$userId] ?? null
                );
            }
        }

        AuditLogger::log(Auth::id(), 'ATTENDANCE_MARK', 'attendance', "Marked attendance for {$date}");
        $this->redirect('attendance?date=' . $date);
    }
}
