<?php
declare(strict_types=1);

namespace App\Controllers;

require_once BASE_PATH . '/app/helpers/permissions.php';

require_once BASE_PATH . '/app/helpers/conference_scope.php';

use App\Core\Controller;
use App\Core\Database;

final class AdminAttendanceController extends Controller
{
    private function cid($db): int {
        $cid=function_exists('default_conference_id')?(int)default_conference_id():0;
        if($cid>0) return $cid;
        return (int)($db->query("SELECT id FROM conferences WHERE (is_active=1 OR is_active IS NULL) ORDER BY id DESC LIMIT 1")->fetchColumn() ?: 0);
    }

    public function index(): void
    {
        require_admin_area();
        $db=Database::getInstance();
        $cid=$this->cid($db);
        $session_id=(int)($_GET['session_id']??0);

        $sessions=[];
        $st=$db->prepare("SELECT id,title_en,title_ar,session_date,start_time FROM conference_sessions WHERE conference_id=:c ORDER BY id DESC");
        $st->execute([':c'=>$cid]);
        $sessions=$st->fetchAll()?:[];

        $rows=[];
        if($session_id>0){
            $q=$db->prepare("
              SELECT a.*, u.email,u.first_name,u.last_name
              FROM attendance_logs a
              JOIN users u ON u.id=a.user_id
              WHERE a.session_id=:s
              ORDER BY a.checked_in_at DESC
            ");
            $q->execute([':s'=>$session_id]);
            $rows=$q->fetchAll()?:[];
        }

        $this->view('admin/attendance/index',['sessions'=>$sessions,'rows'=>$rows,'session_id'=>$session_id]);
    }
}
