<?php
declare(strict_types=1);
require_once __DIR__.'/daily-not-logged-out-report-common.php';

function mnlo_options(mysqli $con,array $scope):array{
    $base=dnlo_options($con,$scope);
    return ['branches'=>$base['locations'],'subbranches'=>$base['subbranches'],'show_subbranch'=>$base['show_subbranch'],'company'=>$base['company'],'export'=>mnlo_export_enabled($con)];
}
function mnlo_export_enabled(mysqli $con):bool{
    if(!dal_table_exists($con,'jos_app_exporttoexcel_config'))return false;
    return(bool)dal_rows($con,"SELECT id FROM jos_app_exporttoexcel_config WHERE layout='Monthly Not Loggedout Report' AND status=1 LIMIT 1");
}
function mnlo_parse_date(string $raw):?string{
    $raw=trim($raw);$date=dal_date($raw);if($date!==null)return$date;
    if(preg_match('/^\d{2}-\d{2}-\d{4}$/',$raw)){$d=DateTimeImmutable::createFromFormat('!d-m-Y',$raw);if($d&&$d->format('d-m-Y')===$raw)return$d->format('Y-m-d');}
    return null;
}
function mnlo_filters(array $s):array{
    $default=date('Y-m-d',strtotime('-1 day'));$fs=array_key_exists('filter_fromdate',$s);$ts=array_key_exists('filter_todate',$s);$fr=mnlo_parse_date((string)($s['filter_fromdate']??''));$to=mnlo_parse_date((string)($s['filter_todate']??''));
    return['from'=>$fr??$default,'to'=>$to??$default,'from_valid'=>!$fs||$fr!==null,'to_valid'=>!$ts||$to!==null,'branch'=>dal_int($s['filter_branchlocation']??0),'subbranch'=>dal_int($s['filt_subbranch']??0)];
}
function mnlo_validate(array $f,array $o):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[]='To Date must be on or after From Date.';
    if(!dal_valid_option($o['branches'],$f['branch']))$e[]='Invalid or unauthorized branch location.';
    if(!dal_valid_option($o['subbranches'],$f['subbranch']))$e[]='Invalid or unauthorized sub branch location.';
    if(!$o['show_subbranch']&&$f['subbranch'])$e[]='Sub Branch Location is not enabled.';
    return array_values(array_unique($e));
}
function mnlo_report(mysqli $con,array $f,array $scope):array{
    $types='ss';$p=[$f['from'],$f['to']];$w=["COALESCE(a.in_time,'')<>''","COALESCE(a.out_time,'')=''",'e.status IN (0,1)','DATE(a.entrydate) BETWEEN ? AND ?'];
    if($f['branch']){$w[]='e.branch_location=?';$types.='i';$p[]=$f['branch'];}
    if($f['subbranch']){$w[]='e.subbranch=?';$types.='i';$p[]=$f['subbranch'];}
    if($scope['restricted']){if(!$scope['terminals'])$w[]='1=0';else{$marks=dnlo_in($scope['terminals'],$types,$p);$w[]="EXISTS (SELECT 1 FROM jos_app_employee_locationlog el WHERE el.app_empid=e.id AND el.orglocation IN ($marks))";}}
    else $w[]='EXISTS (SELECT 1 FROM jos_app_employee_locationlog el WHERE el.app_empid=e.id)';
    $sql="SELECT e.id,e.name,e.orderby,GROUP_CONCAT(DISTINCT DATE(a.entrydate) ORDER BY DATE(a.entrydate) SEPARATOR ',') missing_dates,COUNT(DISTINCT DATE(a.entrydate)) missing_count FROM jos_app_employee e INNER JOIN jos_app_attendance_log a ON a.empid=e.id WHERE ".implode(' AND ',$w).' GROUP BY e.id,e.name,e.orderby ORDER BY e.orderby=0,e.orderby,e.id';
    $rows=dal_rows($con,$sql,$types,$p);foreach($rows as&$r)$r['dates']=array_values(array_filter(explode(',',(string)$r['missing_dates'])));unset($r);return$rows;
}
function mnlo_render(array $rows):void{?><div class="overflow-x-auto"><table class="min-w-[760px] w-full text-sm"><thead class="bg-slate-900 text-white"><tr><?php foreach(['Sr No','Employee Name','Date','Not Logged Out Count']as$h):?><th class="border border-slate-700 px-3 py-3 text-center font-bold"><?=h($h)?></th><?php endforeach;?></tr></thead><tbody><?php foreach($rows as$i=>$r):?><tr><td class="border px-3 py-4 text-center font-semibold"><?=$i+1?></td><td class="border px-3 py-4 text-center font-semibold"><?=h((string)$r['name'])?></td><td class="border px-3 py-4 text-center"><?php foreach($r['dates']as$d):?><?=h(date('d',strtotime((string)$d)))?> /&nbsp;<?php endforeach;?></td><td class="border px-3 py-4 text-center font-bold"><?=(int)$r['missing_count']?></td></tr><?php endforeach;if(!$rows):?><tr><td colspan="4" class="px-6 py-12 text-center font-semibold text-slate-400">No not-logged-out records found for the selected date range.</td></tr><?php endif;?></tbody></table></div><?php }
