<?php
declare(strict_types=1);
ini_set('display_errors', '0');
require_once __DIR__ . '/../includes/console_shell.php';
require_login();

$pageLink='reset-data/synchronization-status.php';
$acl=require_acl('can_view',$pageLink);
$errors=[];

function syn_stmt(mysqli $con,string $sql):mysqli_stmt{
    $stmt=$con->prepare($sql);
    if(!$stmt)throw new RuntimeException('Unable to prepare synchronization query.');
    return $stmt;
}
function syn_col_exists(mysqli $con,string $table,string $column):bool{
    $stmt=syn_stmt($con,'SELECT COUNT(*) total FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=?');
    $stmt->bind_param('ss',$table,$column);$stmt->execute();$found=(int)($stmt->get_result()->fetch_assoc()['total']??0)>0;$stmt->close();return $found;
}
function syn_accessible_ids(mysqli $con):?array{
    $user=current_user()?:[];
    if((int)($user['role_id']??0)===1)return null;
    if(!syn_col_exists($con,'jos_admin_users','terminal_access'))return [];
    $uid=(int)($user['id']??0);$stmt=syn_stmt($con,'SELECT terminal_access FROM jos_admin_users WHERE id=? AND status=1 LIMIT 1');
    $stmt->bind_param('i',$uid);$stmt->execute();$access=trim((string)($stmt->get_result()->fetch_assoc()['terminal_access']??''));$stmt->close();
    if($access==='0'||strtolower($access)==='all')return null;
    preg_match_all('/\d+/',$access,$matches);return array_values(array_unique(array_map('intval',$matches[0]??[])));
}
function syn_locations(mysqli $con,?array $allowed):array{
    if($allowed===[])return [];$sql='SELECT id,name FROM jos_app_orglocation';$types='';$params=[];
    if(is_array($allowed)){$sql.=' WHERE id IN ('.implode(',',array_fill(0,count($allowed),'?')).')';$types=str_repeat('i',count($allowed));$params=$allowed;}
    $stmt=syn_stmt($con,$sql.' ORDER BY name ASC,id ASC');if($types)$stmt->bind_param($types,...$params);$stmt->execute();$rows=[];$result=$stmt->get_result();while($row=$result->fetch_assoc())$rows[]=$row;$stmt->close();return $rows;
}
function syn_location(mysqli $con,int $id,?array $allowed):?array{
    if($id<1||$allowed===[]||(is_array($allowed)&&!in_array($id,$allowed,true)))return null;
    $stmt=syn_stmt($con,'SELECT id,name FROM jos_app_orglocation WHERE id=? LIMIT 1');$stmt->bind_param('i',$id);$stmt->execute();$row=$stmt->get_result()->fetch_assoc()?:null;$stmt->close();return $row;
}

$allowed=syn_accessible_ids($con);$locations=syn_locations($con,$allowed);
$locationId=max(0,(int)($_GET['location_id']??$_GET['orgid']??0));
$syncType=(string)($_GET['sync_type']??(((string)($_GET['no']??''))==='1'?'employee':'face'));
if(!in_array($syncType,['employee','face'],true)){$syncType='employee';$errors[]='Invalid synchronization type.';}
$employeeStatus=(string)($_GET['employee_status']??$_GET['active']??'');
if(!in_array($employeeStatus,['','0','1'],true)){$employeeStatus='';$errors[]='Invalid employee status filter.';}
$location=$locationId?syn_location($con,$locationId,$allowed):null;
if($locationId&&!$location){$errors[]='Select a valid authorized location.';$locationId=0;}

$page=max(1,(int)($_GET['page']??1));$perPage=25;$totalRows=0;$rows=[];
if($location){
    $whereStatus=$employeeStatus!==''?' AND e.status=?':'';
    if($syncType==='employee'){
        $from=' FROM jos_app_employee_locationlog l INNER JOIN jos_app_employee e ON e.id=l.app_empid WHERE l.orglocation=? AND l.status=0'.$whereStatus;
        $select='SELECT l.id,e.name employee_name'.$from.' ORDER BY l.id ASC LIMIT ? OFFSET ?';
    }else{
        $from=' FROM jos_app_employeeface p INNER JOIN jos_app_employeeface_locationlog l ON p.id=l.empfaceid INNER JOIN jos_app_employee e ON e.id=p.empid WHERE l.orglocation=? AND l.status=0'.$whereStatus;
        $select='SELECT l.id,e.name employee_name'.$from.' ORDER BY l.id ASC LIMIT ? OFFSET ?';
    }
    $stmt=syn_stmt($con,'SELECT COUNT(*) total'.$from);
    if($employeeStatus!==''){$status=(int)$employeeStatus;$stmt->bind_param('ii',$locationId,$status);}else{$stmt->bind_param('i',$locationId);}
    $stmt->execute();$totalRows=(int)($stmt->get_result()->fetch_assoc()['total']??0);$stmt->close();
    $totalPages=max(1,(int)ceil($totalRows/$perPage));$page=min($page,$totalPages);$offset=($page-1)*$perPage;
    $stmt=syn_stmt($con,$select);
    if($employeeStatus!==''){$status=(int)$employeeStatus;$stmt->bind_param('iiii',$locationId,$status,$perPage,$offset);}else{$stmt->bind_param('iii',$locationId,$perPage,$offset);}
    $stmt->execute();$result=$stmt->get_result();while($row=$result->fetch_assoc())$rows[]=$row;$stmt->close();
}else{$totalPages=1;$offset=0;}

$filterQuery=['location_id'=>$locationId,'sync_type'=>$syncType,'employee_status'=>$employeeStatus];
console_header('Synchronization Status',$pageLink);
?>
<div class="mb-6"><div class="mb-2 flex items-center gap-2 text-xs font-semibold text-slate-500"><a href="/dashboard.php">Dashboard</a><i class="fa-solid fa-chevron-right text-[9px]"></i><span>D. Masters</span><i class="fa-solid fa-chevron-right text-[9px]"></i><span>Reset Data</span><i class="fa-solid fa-chevron-right text-[9px]"></i><span class="text-brand-600">Synchronization Status</span></div><h1 class="text-2xl font-bold text-slate-900">Synchronization Status</h1><p class="mt-1 text-sm text-slate-500">View employees or employee faces that are pending synchronization for a terminal location.</p></div>
<?php if($errors):?><div class="mb-5 rounded-xl border border-red-100 bg-red-50 px-5 py-4 text-sm font-semibold text-red-700"><i class="fa-solid fa-circle-exclamation mr-2"></i><?=h(implode(' ',$errors))?></div><?php endif;?>
<section class="mb-5 overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm"><div class="border-b border-slate-100 px-5 py-4"><h2 class="text-lg font-bold text-slate-800">Filters</h2><p class="mt-1 text-sm font-medium text-slate-400">Status is read from stored location synchronization records. Refreshing this page does not start synchronization.</p></div><form method="get" class="grid gap-4 p-5 md:grid-cols-3 xl:grid-cols-[1.4fr_1fr_1fr_auto]"><label class="text-sm font-bold text-slate-700">Location<select name="location_id" required class="mt-2 w-full rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm font-semibold text-slate-700 outline-none focus:border-brand-500 focus:ring-4 focus:ring-brand-100"><option value="">Select Location</option><?php foreach($locations as $item):?><option value="<?=(int)$item['id']?>" <?=$locationId===(int)$item['id']?'selected':''?>><?=h($item['name'])?></option><?php endforeach;?></select></label><label class="text-sm font-bold text-slate-700">Synchronization Type<select name="sync_type" class="mt-2 w-full rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm font-semibold text-slate-700"><option value="employee" <?=$syncType==='employee'?'selected':''?>>Employee</option><option value="face" <?=$syncType==='face'?'selected':''?>>Employee Face</option></select></label><label class="text-sm font-bold text-slate-700">Employee Status<select name="employee_status" class="mt-2 w-full rounded-xl border border-slate-200 bg-white px-4 py-3 text-sm font-semibold text-slate-700"><option value="">All</option><option value="1" <?=$employeeStatus==='1'?'selected':''?>>Active</option><option value="0" <?=$employeeStatus==='0'?'selected':''?>>Inactive</option></select></label><div class="flex items-end gap-2"><button class="rounded-xl bg-brand-600 px-5 py-3 text-sm font-bold text-white hover:bg-brand-700"><i class="fa-solid fa-magnifying-glass mr-2"></i>Filter</button><a href="/<?=$pageLink?>" class="rounded-xl border border-slate-200 px-5 py-3 text-sm font-bold text-slate-600 hover:bg-slate-50">Reset</a></div></form></section>
<section class="overflow-hidden rounded-2xl border border-slate-100 bg-white shadow-sm"><div class="flex flex-col gap-3 border-b border-slate-100 px-5 py-4 sm:flex-row sm:items-center sm:justify-between"><div><h2 class="text-lg font-bold text-slate-800"><?= $location?'Pending Employee List - '.h($location['name']):'Pending Employee List' ?></h2><p class="mt-1 text-sm font-medium text-slate-400"><?=h($syncType==='employee'?'Employee synchronization':'Employee face synchronization')?><?= $location?' · '.h((string)$totalRows).' pending':'' ?></p></div><?php if($location):?><a href="?<?=h(http_build_query($filterQuery))?>" class="inline-flex items-center justify-center rounded-xl border border-slate-200 px-4 py-2.5 text-sm font-bold text-slate-600 hover:bg-slate-50"><i class="fa-solid fa-rotate mr-2"></i>Refresh</a><?php endif;?></div>
<div class="overflow-x-auto"><table class="w-full min-w-[640px] text-left text-sm"><thead class="bg-slate-50 text-[10px] font-extrabold uppercase tracking-wider text-slate-600"><tr><th class="w-24 px-5 py-4">Sr No</th><th class="px-5 py-4">Employee Name</th><th class="w-36 px-5 py-4">Status</th></tr></thead><tbody class="divide-y divide-slate-100">
<?php if(!$location):?><tr><td colspan="3" class="px-5 py-16 text-center font-semibold text-slate-400">Select a location to view pending synchronization records.</td></tr><?php elseif(!$rows):?><tr><td colspan="3" class="px-5 py-16 text-center font-semibold text-slate-400">No pending employees found.</td></tr><?php endif;?>
<?php foreach($rows as $index=>$row):?><tr class="hover:bg-slate-50/70"><td class="px-5 py-4 font-semibold text-slate-500"><?=$offset+$index+1?></td><td class="px-5 py-4 font-bold text-slate-800"><?=h($row['employee_name']?:'Unnamed Employee')?></td><td class="px-5 py-4"><span class="rounded-full bg-amber-50 px-3 py-1 text-xs font-bold text-amber-700">Pending</span></td></tr><?php endforeach;?>
</tbody></table></div>
<?php if($location&&$totalPages>1):?><div class="flex items-center justify-between border-t border-slate-100 px-5 py-4 text-sm font-semibold text-slate-500"><span>Page <?=$page?> of <?=$totalPages?></span><div class="flex gap-2"><?php if($page>1):?><a class="rounded-lg border border-slate-200 px-3 py-2" href="?<?=h(http_build_query($filterQuery+['page'=>$page-1]))?>">Previous</a><?php endif;?><?php if($page<$totalPages):?><a class="rounded-lg border border-slate-200 px-3 py-2" href="?<?=h(http_build_query($filterQuery+['page'=>$page+1]))?>">Next</a><?php endif;?></div></div><?php endif;?>
</section>
<?php console_footer();
