<?php
declare(strict_types=1);ini_set('display_errors','0');header('Cache-Control:private,no-store,no-cache,must-revalidate,max-age=0');
require_once __DIR__.'/../includes/auth.php';require_once __DIR__.'/../includes/aclhelper.php';require_login();require_acl('can_view','reports/monthly-attendance-log.php');require_once __DIR__.'/monthly-attendance-log-common.php';
if($_SERVER['REQUEST_METHOD']!=='POST'){http_response_code(405);exit('Method not allowed.');}if(!verify_csrf($_POST['_csrf']??null)){http_response_code(403);exit('Invalid security token.');}
$enabled=false;if(mal_table($con,'jos_app_exporttoexcel_config')){$x=mal_rows($con,'SELECT status FROM jos_app_exporttoexcel_config WHERE layout=? LIMIT 1','s',['Monthly Attendance Log']);$enabled=!empty($x[0]['status']);}if(!$enabled){http_response_code(404);exit('Export is not enabled.');}
$o=mal_options($con);$f=mal_filters($con,$_POST,$o);if(mal_validate($f,$o)){http_response_code(422);exit('Invalid report filters.');}$r=mal_report($con,$f,$o);
header('Content-Type:application/vnd.ms-excel;charset=UTF-8');header('Content-Disposition:attachment;filename="Monthly Attendance Log.xls"');echo"\xEF\xBB\xBF";$safe=static function($v){$v=(string)$v;if(preg_match('/^[=+\\-@]/',$v))$v="'".$v;return h($v);};
?><table border="1"><tr><th colspan="8"><?=$safe($r['company'])?><br>Monthly Attendance Log<br><?=$safe($r['employee']['name'].' · '.$r['period']['label'])?></th></tr><tr><th>Sr No</th><th>Date</th><th>Shift / Status</th><th>Logs</th><th>Gate Pass / Production Logs</th><th>Total Hrs</th><th>Extra / Loss Time</th><th>Late Mark</th></tr><?php foreach($r['rows'] as $i=>$x):?><tr><td><?=$i+1?></td><td><?=$safe(date('l d-m-Y',strtotime($x['date'])))?></td><td><?=$safe($x['status'])?></td><td><?php foreach($x['logs'] as $l)echo$safe(($l['location']??'').' '.implode(' - ',$l['pair'])).'<br>';?></td><td><?php foreach($x['gate'] as $l)echo$safe(($l['location']??'').' '.implode(' - ',$l['pair'])).'<br>';?></td><td><?=$safe(mal_hhmm($x['worked']))?></td><td><?=$safe('E +'.mal_hhmm($x['extra']).' / L -'.mal_hhmm($x['loss']))?></td><td><?=$safe($x['late']?mal_hhmm($x['late']).' L':'')?></td></tr><?php endforeach;?><tr><th colspan="8">Attendance Summary</th></tr><?php foreach($r['summary'] as $k=>$v):?><tr><th><?=$safe($k)?></th><td colspan="7"><?=$safe(strpos($k,'Minutes')!==false?mal_hhmm((int)$v):$v)?></td></tr><?php endforeach;?></table>
