<?php

namespace App\Controllers;

use App\Core\Controller;
use App\Helpers\Auth;
use App\Models\EventAttendance;
use App\Models\Event;
use App\Models\AuditLog;

class AttendanceController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        Auth::requireLogin();
    }

    public function index()
    {
        $model = new EventAttendance();
        $userId = Auth::user()->role === 'admin' ? null : Auth::id();

        if ($userId) {
            $attendance = $model->getByUser($userId);
        } else {
            $attendance = $model->all();
        }

        $this->view('attendance/index', ['attendance' => $attendance ?? []]);
    }

    public function markAttendance($params)
    {
        if (Auth::user()->role !== 'admin') {
            $_SESSION['error'] = 'Unauthorized';
            $this->redirect('/attendance');
        }

        $eventId = $params['id'] ?? null;
        $userId = $_POST['user_id'] ?? null;
        $status = $_POST['status'] ?? 'attended';

        if ($eventId && $userId) {
            $stmt = $this->db->prepare("UPDATE event_attendance SET status = ?, attended_at = NOW() WHERE event_id = ? AND user_id = ?");
            $stmt->execute([$status, $eventId, $userId]);

            $audit = new AuditLog();
            $audit->log(Auth::id(), 'attendance.mark', 'event_attendance', $eventId, "Marked attendance for user {$userId}");
            $_SESSION['success'] = 'Attendance marked';
        }

        $this->redirect('/events/' . $eventId . '/attendees');
    }
}
