<?php
declare(strict_types=1);
require_once __DIR__.'/daily-attendance-log-common.php';

function gpa_scope(mysqli $con):array{$u=current_user()?:[];if((int)($u['role_id']??0)===1)return['terminals'=>[],'restricted'=>false];$c=dal_columns($con,'jos_admin_users');if(!dal_has($c,'terminal_access'))return['terminals'=>[],'restricted'=>true];$r=dal_rows($con,'SELECT terminal_access FROM jos_admin_users WHERE id=? AND status=1 LIMIT 1','i',[(int)($u['id']??0)]);$ids=array_values(array_unique(array_filter(array_map('intval',explode(',',(string)($r[0]['terminal_access']??''))))));return['terminals'=>$ids,'restricted'=>true];}
function gpa_filters(array $s):array{$fs=array_key_exists('filter_fromdate',$s);$ts=array_key_exists('filter_todate',$s);$fr=trim((string)($s['filter_fromdate']??''));$tr=trim((string)($s['filter_todate']??''));$f=dal_date($fr);$t=dal_date($tr);$st=filter_var($s['filt_status']??0,FILTER_VALIDATE_INT);return['from'=>$f??date('Y-m-d'),'to'=>$t??date('Y-m-d'),'from_valid'=>!$fs||$f!==null,'to_valid'=>!$ts||$t!==null,'employee'=>dal_int($s['filter_emp']??0),'employee_name'=>trim((string)($s['filter_namevalue']??'')),'status'=>in_array($st,[0,1,2],true)?(int)$st:-1];}
function gpa_employee_where(array $scope,string &$types,array &$params,string $alias='e'):array{$w=[];if($scope['restricted']){if(!$scope['terminals'])$w[]='1=0';else{$m=implode(',',array_fill(0,count($scope['terminals']),'?'));$w[]="EXISTS (SELECT 1 FROM jos_app_employee_locationlog gpa_el WHERE gpa_el.app_empid=$alias.id AND gpa_el.orglocation IN ($m))";$types.=str_repeat('i',count($scope['terminals']));array_push($params,...$scope['terminals']);}}return$w;}
function gpa_employee(mysqli $con,int $id,array $scope):?array{if($id<1)return null;$types='i';$p=[$id];$w=array_merge(['e.id=?'],gpa_employee_where($scope,$types,$p));$r=dal_rows($con,'SELECT e.id,e.name,e.emp_code FROM jos_app_employee e WHERE '.implode(' AND ',$w).' LIMIT 1',$types,$p);return$r[0]??null;}
function gpa_validate(mysqli $con,array $f,array $scope):array{$e=[];if(!$f['from_valid'])$e[]='Enter a valid From Date.';if(!$f['to_valid'])$e[]='Enter a valid To Date.';if($f['from_valid']&&$f['to_valid']&&strtotime($f['from'])>strtotime($f['to']))$e[]='From Date must be on or before To Date.';if($f['status']<0)$e[]='Invalid request status.';if($f['employee']>0){$x=gpa_employee($con,$f['employee'],$scope);if(!$x)$e[]='Invalid or unauthorized employee.';elseif($f['employee_name']!==''&&strcasecmp($f['employee_name'],(string)$x['name'])!==0)$e[]='Employee Name does not match the selected employee.';}elseif($f['employee_name']!=='')$e[]='Select an employee from the suggestions.';return$e;}
function gpa_status_label(int $s):string{if($s===0)return'Pending for Approval';if($s===1)return'Approved';if($s===2)return'Rejected';return'Unknown';}
function gpa_report(mysqli $con,array $f,array $scope):array{$types='ssi';$p=[$f['from'],$f['to'],$f['status']];$w=['DATE(g.gatepassdate) BETWEEN ? AND ?','g.status=?'];if($f['employee']>0){$w[]='g.empid=?';$types.='i';$p[]=$f['employee'];}$w=array_merge($w,gpa_employee_where($scope,$types,$p));$rows=dal_rows($con,'SELECT g.*,e.name employee_name,e.emp_code,o.name gatepass_type,s.shift_type,s.shortname FROM jos_app_gatepass_request_log g INNER JOIN jos_app_employee e ON e.id=g.empid LEFT JOIN jos_app_orglocation o ON o.id=g.orglocation LEFT JOIN jos_app_empshift s ON s.id=g.shift WHERE '.implode(' AND ',$w).' ORDER BY g.gatepassdate DESC,g.id DESC',$types,$p);if(!$rows)return[];$ids=array_map('intval',array_column($rows,'id'));$m=implode(',',array_fill(0,count($ids),'?'));$h=dal_rows($con,"SELECT * FROM jos_app_gatepass_request_status_log WHERE gateid IN ($m) ORDER BY gateid,entrydate,id",str_repeat('i',count($ids)),$ids);$hb=[];foreach($h as$x)$hb[(int)$x['gateid']][]=$x;$emp=array_values(array_unique(array_map('intval',array_column($rows,'empid'))));$em=implode(',',array_fill(0,count($emp),'?'));$pt=str_repeat('i',count($emp)).'ss';$pp=array_merge($emp,[$f['from'],$f['to']]);$pr=dal_rows($con,"SELECT empid,DATE(entrydate) logdate,in_time,out_time FROM jos_app_attendance_log WHERE empid IN ($em) AND DATE(entrydate) BETWEEN ? AND ? ORDER BY empid,entrydate,id",$pt,$pp);$pb=[];foreach($pr as$x){$k=(int)$x['empid'].'|'.$x['logdate'];if(trim((string)$x['in_time'])!=='')$pb[$k][]=(string)$x['in_time'];if(trim((string)$x['out_time'])!=='')$pb[$k][]=(string)$x['out_time'];}foreach($rows as&$r){$r['history']=$hb[(int)$r['id']]??[];$r['punches']=$pb[(int)$r['empid'].'|'.substr((string)$r['gatepassdate'],0,10)]??[];}unset($r);return$rows;}
function gpa_history_label(array $r):string{$s=(int)($r['status']??0);return$s===0?'Pending':($s===1?'Approved by Supervisor':'Approved by HR');}
function gpa_hhmm($m):string{$m=max(0,(int)$m);return sprintf('%02d:%02d',intdiv($m,60),$m%60);}
function gpa_render(array $rows):void{?><div class="divide-y divide-slate-200"><?php foreach($rows as$i=>$r):?><article class="p-5"><div class="grid gap-5 md:grid-cols-2 xl:grid-cols-6"><div><div class="text-xs font-bold uppercase text-slate-400">Sr No / Gatepass Date</div><div class="mt-1 font-bold"><?=$i+1?> · <?=h(date('d-m-Y',strtotime((string)$r['gatepassdate'])))?></div><?php if(!(int)($r['machinelog']??0)):?><div class="mt-1 text-sm text-slate-500"><?=h((string)($r['gatepass_type']??''))?></div><?php endif;?></div><div><div class="text-xs font-bold uppercase text-slate-400">Employee Name</div><div class="mt-1 font-bold"><?=h((string)$r['employee_name'])?></div><?php if(!empty($r['emp_code'])):?><div class="text-sm text-slate-500"><?=h((string)$r['emp_code'])?></div><?php endif;?><?php if(!(int)($r['machinelog']??0)):?><div class="mt-1 text-sm text-slate-500"><?=h((string)($r['shift_type']?:$r['shortname']))?></div><?php endif;?></div><div class="xl:col-span-2"><div class="text-xs font-bold uppercase text-slate-400"><?=(int)($r['machinelog']??0)?'Logs':'Time / Total Hours'?></div><?php if((int)($r['machinelog']??0)):?><div class="mt-1 flex flex-wrap gap-2"><?php foreach($r['punches']as$j=>$p):?><span class="rounded bg-slate-100 px-2 py-1 text-sm font-semibold"><?=h(($j%2===0?'In - ':'Out - ').dal_display_time((string)$p))?></span><?php endforeach;if(!$r['punches']):?><span class="text-sm text-slate-400">No attendance logs</span><?php endif;?></div><?php else:?><div class="mt-1 font-semibold"><?=h((string)$r['in_time'])?> – <?=h((string)$r['out_time'])?></div><div class="text-sm text-slate-500"><?=h(gpa_hhmm($r['total_hours']??0))?></div><?php endif;?></div><div><div class="text-xs font-bold uppercase text-slate-400">Status History</div><div class="mt-1 space-y-1 text-sm"><?php foreach($r['history']as$history):?><div><?=h(date('d M Y',strtotime((string)$history['entrydate'])))?> — <b><?=h(gpa_history_label($history))?></b></div><?php endforeach;if(!$r['history']):?><div class="font-semibold"><?=h(gpa_status_label((int)$r['status']))?></div><?php endif;?></div></div><div class="no-print"><div class="text-xs font-bold uppercase text-slate-400">Action</div><a target="_blank" href="/reports/attendance/gatepass-pending-for-approval-print.php?id=<?=(int)$r['id']?>" class="mt-2 inline-flex rounded-lg border border-slate-200 px-3 py-2 text-sm font-bold text-slate-600"><i class="fa-solid fa-print mr-2"></i>Print</a></div></div><div class="mt-4 rounded-xl bg-slate-50 px-4 py-3 text-sm"><b>Reason:</b> <?=h((string)($r['reason']??''))?></div></article><?php endforeach;if(!$rows):?><div class="p-12 text-center font-semibold text-slate-400">No gatepass requests match the selected filters.</div><?php endif;?></div><?php }
