<?php
declare(strict_types=1);
require_once __DIR__.'/../../authentication/api/connect.php';require_once __DIR__.'/../lib/login_attendance.php';
$user=require_auth();if(($_SERVER['REQUEST_METHOD']??'GET')!=='GET')reply(405,['message'=>'Use GET.']);
try{
 $now=attendance_now();$month=(string)($_GET['month']??$now->format('Y-m'));if(!preg_match('/^\d{4}-(0[1-9]|1[0-2])$/',$month)||$month>$now->format('Y-m'))reply(422,['message'=>'Choose the current month or an earlier month.']);
 $start=db()->query('SELECT started_on FROM login_attendance_settings WHERE id=1')->fetchColumn();if(!$start)reply(503,['message'=>'Apply the login attendance database migration first.']);
 if($month<substr($start,0,7))reply(422,['message'=>'Attendance tracking started in '.substr($start,0,7).'.']);
 [$where,$args]=attendance_scope($user);$selected=(int)($_GET['student']??0);if($selected){$where.=' AND s.user_id=?';$args[]=$selected;}
 $sql="SELECT s.user_id,s.student_number,s.created_at,COALESCE(NULLIF(u.full_name,''),u.username) full_name,d.department_name,c.campus_name FROM students s JOIN users u ON u.id=s.user_id JOIN departments d ON d.id=s.department_id JOIN campuses c ON c.id=s.campus_id WHERE ".$where.' ORDER BY u.full_name';
 if(!$selected&&$user['role']!=='student')$sql.=' LIMIT 31 OFFSET '.(max(0,(int)($_GET['page']??0))*30);
 $q=db()->prepare($sql);$q->execute($args);$students=$q->fetchAll();if($selected&&!$students)reply(404,['message'=>'Student receipt not found in your access scope.']);
 $more=count($students)>30;if($more)$students=array_slice($students,0,30);$receipts=[];foreach($students as $s){$r=attendance_receipt($s,$month,$start,$now);if(!$selected&&$user['role']!=='student')unset($r['days']);$receipts[]=$r;}
 reply(200,['receipts'=>$receipts,'month'=>$month,'tracking_started'=>$start,'more'=>$more,'student_view'=>$user['role']==='student']);
}catch(InvalidArgumentException $e){reply(422,['message'=>$e->getMessage()]);}catch(Throwable $e){error_log('Login attendance: '.$e->getMessage());reply(503,['message'=>'Attendance is unavailable. Check the attendance migration and database connection.']);}
