<?php
declare(strict_types=1);
function attendance_now(): DateTimeImmutable {return new DateTimeImmutable('now',new DateTimeZone('Africa/Lusaka'));}
function record_student_login(array $user): void {
 if(($user['role']??'')!=='student')return;
 $day=attendance_now()->format('Y-m-d');if(($_SESSION['attendance_day']??'')===$day)return;
 try{$q=db()->prepare('INSERT IGNORE INTO student_login_days(user_id,attendance_date,first_seen_at) VALUES(?,?,UTC_TIMESTAMP())');$q->execute([(int)$user['id'],$day]);$_SESSION['attendance_day']=$day;}catch(Throwable $e){error_log('Login attendance unavailable; apply attendance migration.');}
}
function attendance_days(string $month,string $start,string $enrolled,array $logins,DateTimeImmutable $now): array {
 if(!preg_match('/^\d{4}-(0[1-9]|1[0-2])$/',$month))throw new InvalidArgumentException('Choose a valid month.');
 $first=new DateTimeImmutable($month.'-01',new DateTimeZone('Africa/Lusaka'));$today=$now->format('Y-m-d');$rows=[];
 for($i=0;$i<(int)$first->format('t');$i++){$date=$first->modify('+'.$i.' days')->format('Y-m-d');$seen=$logins[$date]??null;
  $status=$date<$start||$date<$enrolled?'not_tracked':($date>$today?'upcoming':($seen?'present':($date===$today?'pending':'absent')));
  $rows[]=['date'=>$date,'weekday'=>$first->modify('+'.$i.' days')->format('l'),'status'=>$status,'first_seen_at'=>$seen];
 }return $rows;
}
function attendance_scope(array $user): array {
 if(in_array($user['role'],['staff','admin'],true))return ['1=1',[]];
 if($user['role']==='student')return ['s.user_id=?',[$user['id']]];
 if($user['role']==='hod')return ['EXISTS(SELECT 1 FROM hod_assignments h WHERE h.user_id=? AND h.department_id=s.department_id AND h.campus_id=s.campus_id)',[$user['id']]];
 throw new InvalidArgumentException('Attendance is unavailable for this account.');
}
function attendance_receipt(array $student,string $month,string $start,DateTimeImmutable $now): array {
 $closed=$month<$now->format('Y-m');$uid=(int)$student['user_id'];
 if($closed){$q=db()->prepare('SELECT receipt_json FROM student_login_receipts WHERE user_id=? AND receipt_month=?');$q->execute([$uid,$month]);$old=$q->fetchColumn();if($old)return json_decode($old,true,512,JSON_THROW_ON_ERROR);}
 $q=db()->prepare('SELECT attendance_date,first_seen_at FROM student_login_days WHERE user_id=? AND attendance_date>=? AND attendance_date<? ORDER BY attendance_date');$first=new DateTimeImmutable($month.'-01',new DateTimeZone('Africa/Lusaka'));$q->execute([$uid,$month.'-01',$first->modify('+1 month')->format('Y-m-d')]);$logins=[];foreach($q->fetchAll() as $r)$logins[$r['attendance_date']]=$r['first_seen_at'];
 $enrolled=(new DateTimeImmutable($student['created_at'],new DateTimeZone('UTC')))->setTimezone(new DateTimeZone('Africa/Lusaka'))->format('Y-m-d');
 $days=attendance_days($month,$start,$enrolled,$logins,$now);$counts=array_count_values(array_column($days,'status'));
 $receipt=['number'=>'RVU-LOGIN-'.str_replace('-','',$month).'-'.$uid,'month'=>$month,'student'=>$student,'days'=>$days,'present'=>$counts['present']??0,'absent'=>$counts['absent']??0,'closed'=>$closed,'closed_at'=>$closed?$first->modify('+1 month')->format('Y-m-d H:i:s'):null,'timezone'=>'Africa/Lusaka','tracking_started'=>$start,'institution'=>function_exists('platform_settings')?platform_settings()['institution']:'Rockview University'];
 if($closed){$q=db()->prepare('INSERT IGNORE INTO student_login_receipts(user_id,receipt_month,closed_at,receipt_json) VALUES(?,?,?,?)');$q->execute([$uid,$month,$receipt['closed_at'],json_encode($receipt,JSON_THROW_ON_ERROR)]);$q=db()->prepare('SELECT receipt_json FROM student_login_receipts WHERE user_id=? AND receipt_month=?');$q->execute([$uid,$month]);return json_decode($q->fetchColumn(),true,512,JSON_THROW_ON_ERROR);}
 return $receipt;
}
