<?php
declare(strict_types=1);
ini_set('display_errors','0');
header('Cache-Control: private, no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
require_once __DIR__.'/../../includes/console_shell.php';
require_login();
$pageLink='reports/attendance/daily-attendance-log.php';
$acl=require_acl('can_view',$pageLink);
require_once __DIR__.'/daily-attendance-log-common.php';
date_default_timezone_set('Asia/Kolkata');
$submitted=$_SERVER['REQUEST_METHOD']==='POST';
$options=[];$errors=[];$report=null;
try{$options=dal_load_options($con);$filters=dal_filters($submitted?$_POST:[]);if($submitted){$errors=dal_validate($filters,$options);if(!$errors)$report=dal_report($con,$filters);}}catch(Throwable $e){$filters=dal_filters([]);$errors[]='Unable to generate the Daily Attendance Log.';}
$settings=dal_table_exists($con,'jos_app_usersetting')?dal_rows($con,'SELECT store_name,subbranch,catonof FROM jos_app_usersetting LIMIT 1'):[];
$setting=$settings[0]??[];$company=(string)($setting['store_name']??APP_NAME);
$showSub=!empty($setting['subbranch']);$showCategory=!empty($setting['catonof']);
$exportEnabled=false;
if(dal_table_exists($con,'jos_app_exporttoexcel_config')){$x=dal_rows($con,'SELECT status FROM jos_app_exporttoexcel_config WHERE layout=? LIMIT 1','s',['Daily Attendance Log']);$exportEnabled=!empty($x[0]['status']);}
$input='mt-1 w-full rounded-xl border border-slate-200 bg-white px-3 py-2.5 text-sm outline-none focus:border-brand-500 focus:ring-2 focus:ring-brand-100';
$selected=static fn(int $a,int $b):string=>$a===$b?'selected':'';
$additionalOpen=(int)$filters['shift']>0||(int)$filters['department']>0||(int)$filters['terminal']>0||(int)$filters['branch']>0||(int)$filters['subbranch']>0||(int)$filters['category']>0;
console_header('Daily Attendance Log','reports');
?>
<div class="mb-6"><div class="mb-2 flex items-center gap-2 text-xs font-semibold text-slate-500"><span>Reports</span><i class="fa-solid fa-chevron-right text-[9px]"></i><span>Attendance Report</span><i class="fa-solid fa-chevron-right text-[9px]"></i><span class="text-brand-600">Daily Attendance Log</span></div><h1 class="text-2xl font-bold text-slate-900">Daily Attendance Log</h1><p class="mt-1 text-sm text-slate-500">Select the filters and view the daily attendance report below.</p></div>
<?php foreach($errors as $error): ?><div class="mb-4 rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm font-semibold text-red-700"><?=h($error)?></div><?php endforeach; ?>
<section class="mb-6 overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-sm">
<div class="border-b border-slate-100 px-5 py-4"><h2 class="text-lg font-bold text-slate-800">Report Filters</h2></div>
<form method="post" id="report-form" class="p-5">
<div class="grid gap-4 md:grid-cols-2 xl:grid-cols-4">
<label class="text-sm font-bold text-slate-700">Date<input required type="date" name="filter_date" value="<?=h($filters['date'])?>" class="<?=$input?>"></label>
<label class="text-sm font-bold text-slate-700">Select Payroll Location<select name="filter_payrolllocation" class="<?=$input?>"><option value="0">-All-</option><?php foreach($options['payrolls']??[] as $o):?><option value="<?=(int)$o['id']?>" <?=$selected($filters['payroll'],(int)$o['id'])?>><?=h($o['name'])?></option><?php endforeach;?></select></label>
</div>
<div class="mt-4 flex flex-wrap items-center justify-between gap-3">
<button type="button" id="daily-additional-toggle" aria-expanded="<?=$additionalOpen?'true':'false'?>" aria-controls="daily-additional-filters" class="rounded-lg border border-slate-200 bg-white px-4 py-2.5 text-sm font-bold text-slate-700 hover:border-brand-300 hover:bg-brand-50 hover:text-brand-700"><i class="fa-solid fa-sliders mr-2"></i><span><?=$additionalOpen?'Hide Additional Filters':'Use Additional Filters'?></span><i class="fa-solid fa-chevron-down ml-2 text-xs <?=$additionalOpen?'rotate-180':''?>"></i></button>
<div class="flex flex-wrap items-end gap-2">
<button type="submit" class="rounded-xl bg-brand-600 px-6 py-3 text-sm font-bold text-white hover:bg-brand-700"><i class="fa-solid fa-magnifying-glass mr-2"></i>Go</button>
<?php if($report!==null):?><button id="daily-print-button" type="button" onclick="window.print()" class="rounded-xl bg-red-500 px-6 py-3 text-sm font-bold text-white hover:bg-red-600"><i class="fa-solid fa-print mr-2"></i>Print</button><?php endif;?>
<?php if($report!==null&&$exportEnabled):?><button id="daily-export-button" type="submit" formaction="/reports/attendance/daily-attendance-log-export.php" formtarget="_blank" class="rounded-xl bg-emerald-600 px-6 py-3 text-sm font-bold text-white hover:bg-emerald-700"><i class="fa-solid fa-file-excel mr-2"></i>Export to XLS</button><?php endif;?>
</div>
</div>
<div id="daily-additional-filters" class="mt-4 <?=$additionalOpen?'':'hidden'?> border-t border-slate-100 pt-4"><div class="grid gap-4 md:grid-cols-2 xl:grid-cols-6">
<label class="text-sm font-bold text-slate-700">Select Shift<select name="filter_shift" class="<?=$input?>"><option value="0">-All-</option><?php foreach($options['shifts']??[] as $o):?><option value="<?=(int)$o['id']?>" <?=$selected($filters['shift'],(int)$o['id'])?>><?=h($o['name'])?></option><?php endforeach;?></select></label>
<label class="text-sm font-bold text-slate-700">Select Department<select name="filter_dept" class="<?=$input?>"><option value="0">-All-</option><?php foreach($options['departments']??[] as $o):?><option value="<?=(int)$o['id']?>" <?=$selected($filters['department'],(int)$o['id'])?>><?=h($o['name'])?></option><?php endforeach;?></select></label>
<label class="text-sm font-bold text-slate-700">Select Terminal Location<select name="filter_orglocation" class="<?=$input?>"><option value="0">-All-</option><?php foreach($options['locations']??[] as $o):?><option value="<?=(int)$o['id']?>" <?=$selected($filters['terminal'],(int)$o['id'])?>><?=h($o['name'])?></option><?php endforeach;?></select></label>
<label class="text-sm font-bold text-slate-700">Branch Location<select name="filter_branchlocation" class="<?=$input?>"><option value="0">Select Location</option><?php foreach($options['locations']??[] as $o):?><option value="<?=(int)$o['id']?>" <?=$selected($filters['branch'],(int)$o['id'])?>><?=h($o['name'])?></option><?php endforeach;?></select></label>
<?php if($showSub):?><label class="text-sm font-bold text-slate-700">Sub Branch Location<select name="filt_subbranch" class="<?=$input?>"><option value="0">-Select Location-</option><?php foreach($options['subbranches']??[] as $o):?><option value="<?=(int)$o['id']?>" <?=$selected($filters['subbranch'],(int)$o['id'])?>><?=h($o['name'])?></option><?php endforeach;?></select></label><?php endif;?>
<?php if($showCategory):?><label class="text-sm font-bold text-slate-700">Category<select name="filt_cat" class="<?=$input?>"><option value="0">Select category</option><?php foreach($options['categories']??[] as $o):?><option value="<?=(int)$o['id']?>" <?=$selected($filters['category'],(int)$o['id'])?>><?=h($o['name'])?></option><?php endforeach;?></select></label><?php endif;?>
</div></div>
</form></section>
<?php if($report!==null):?><div id="report-output" class="space-y-6">
<section class="rounded-2xl border border-slate-200 bg-white shadow-sm"><div class="border-b border-slate-100 p-5 text-center"><div class="font-extrabold text-slate-900"><?=h($company)?></div><h2 class="text-lg font-bold">Daily Attendance Log</h2><div class="text-sm font-semibold text-slate-500">Date: <?=h(date('d-m-Y',strtotime($filters['date'])))?></div></div><div class="overflow-x-auto"><table class="min-w-[1100px] w-full text-sm"><thead class="bg-slate-900 text-white"><tr><th class="px-3 py-3 text-center">Sr No</th><th class="px-3 py-3 text-center">Name</th><th colspan="6" class="px-3 py-3 text-center">Log Details</th></tr></thead><tbody class="divide-y divide-slate-100"><?php foreach($report['detail'] as $i=>$row):$shift=$row['shift'];?><tr class="align-top"><td class="px-3 py-4 text-center font-bold"><?=($i+1)?></td><td class="px-3 py-4 text-center"><b><?=h($row['employee']['name'])?></b><br><span class="text-xs text-slate-500"><?=h($row['employee']['branch_name']??'')?></span></td><td class="px-3 py-4 text-center"><b><?=h(($shift['shift_in']??'').' - '.($shift['shift_out']??''))?></b><br>Working Hrs - <?=h(dal_hhmm($row['worked']))?><br><span class="font-bold <?=$row['not_logout']?'text-red-600':'text-emerald-700'?>"><?=h($row['status'])?></span></td><td class="px-3 py-4 text-center"><b class="underline">Logs</b><br><br><?php foreach($row['logs'] as $log):?><b><?=h($log['location']??'')?></b><br><?=h(implode(' - ',$log['pair']))?><br><br><?php endforeach;?></td><td class="px-3 py-4 text-center"><b>Gate Pass Logs</b><br><?php foreach($row['gate_logs'] as $log):?><b><?=h($log['location']??'')?></b><br><?=h(implode(' - ',$log['pair']))?><br><?php endforeach;?><b class="text-red-600"><?=h(dal_hhmm($row['gate_minutes']))?></b></td><td class="px-3 py-4 text-center font-bold"><span class="underline">Total Hrs</span><br><br><?=h(dal_hhmm($row['worked']))?></td><td class="px-3 py-4 text-center"><b class="underline">Extra / Loss Time</b><br>—</td><td class="px-3 py-4 text-center"><b class="underline">Late Mark</b><br>—</td></tr><?php endforeach;?><?php if(!$report['detail']):?><tr><td colspan="8" class="px-6 py-12 text-center font-semibold text-slate-400">No attendance logs match the selected filters.</td></tr><?php endif;?></tbody></table></div></section>
<section class="rounded-2xl border border-slate-200 bg-white shadow-sm"><div class="p-5 text-center"><div class="font-extrabold"><?=h($company)?></div><h2 class="text-lg font-bold">Daily Attendance Log</h2><div class="text-sm font-semibold text-slate-500">Date: <?=h(date('d-m-Y',strtotime($filters['date'])))?></div></div><div class="overflow-x-auto"><table class="w-full text-sm"><thead class="bg-slate-900 text-white"><tr><th class="px-4 py-3">Sr No</th><th class="px-4 py-3">Name</th></tr></thead><tbody class="divide-y divide-slate-100"><?php foreach($report['absent'] as $i=>$row):?><tr><td class="px-4 py-3 text-center font-bold"><?=($i+1)?></td><td class="px-4 py-3 text-center"><b><?=h($row['employee']['name'])?></b><br><span class="text-xs text-slate-500"><?=h($row['employee']['branch_name']??'')?></span><br><b class="text-red-600"><?=h($row['status'])?></b></td></tr><?php endforeach;?><?php if(!$report['absent']):?><tr><td colspan="2" class="px-6 py-10 text-center font-semibold text-slate-400">No absent or non-login employees.</td></tr><?php endif;?></tbody></table></div></section>
<section class="grid gap-3 sm:grid-cols-2 lg:grid-cols-5"><?php foreach([['Log In','login','blue'],['Absent','absent','red'],['Weekly Off','weeklyoff','amber'],['Holiday','holiday','violet'],['Total','total','slate']] as [$label,$key,$color]):?><div class="rounded-2xl border border-slate-200 bg-white p-5 text-center shadow-sm"><div class="text-xs font-extrabold uppercase tracking-wide text-slate-500"><?=h($label)?></div><div class="mt-2 text-3xl font-black text-<?=$color?>-600"><?=(int)$report['summary'][$key]?></div></div><?php endforeach;?></section></div><?php endif;?>
<script>
document.addEventListener('DOMContentLoaded',function(){
  var form=document.getElementById('report-form');
  var report=document.getElementById('report-output');
  var printButton=document.getElementById('daily-print-button');
  var exportButton=document.getElementById('daily-export-button');
  var additionalToggle=document.getElementById('daily-additional-toggle');
  var additionalFilters=document.getElementById('daily-additional-filters');
  if(additionalToggle&&additionalFilters){
    additionalToggle.addEventListener('click',function(){
      var opening=additionalFilters.classList.contains('hidden');
      additionalFilters.classList.toggle('hidden');
      additionalToggle.setAttribute('aria-expanded',opening?'true':'false');
      additionalToggle.querySelector('span').textContent=opening?'Hide Additional Filters':'Use Additional Filters';
      additionalToggle.querySelector('.fa-chevron-down').classList.toggle('rotate-180',opening);
    });
  }
  if(!form||!report)return;
  form.querySelectorAll('input,select').forEach(function(field){
    field.addEventListener('change',function(){
      report.classList.add('hidden');
      if(printButton)printButton.classList.add('hidden');
      if(exportButton)exportButton.classList.add('hidden');
    });
  });
});
</script>
<style>@media print{aside,header,nav,#report-form,.mb-6,.no-print{display:none!important}main{padding:0!important}body{background:white!important}#report-output{display:block!important}.rounded-2xl{border-radius:0!important;box-shadow:none!important}table{font-size:10px!important}}</style>
<?php console_footer(); ?>
