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

$pageLink = 'reset-data/reset-web-console.php';
$errors = [];
$flash = $_SESSION['flash_reset_web_console'] ?? null;
unset($_SESSION['flash_reset_web_console']);

function rwc_stmt(mysqli $con, string $sql): mysqli_stmt {
    $stmt = $con->prepare($sql);
    if (!$stmt) throw new RuntimeException('Unable to prepare maintenance operation.');
    return $stmt;
}
function rwc_col_exists(mysqli $con, string $table, string $column): bool {
    $stmt = rwc_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 rwc_accessible_ids(mysqli $con): ?array {
    $user=current_user()?:[]; if((int)($user['role_id']??0)===1)return null;
    if(!rwc_col_exists($con,'jos_admin_users','terminal_access'))return [];
    $uid=(int)($user['id']??0); $stmt=rwc_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,$m); return array_values(array_unique(array_map('intval',$m[0]??[])));
}
function rwc_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=rwc_stmt($con,$sql.' ORDER BY name');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 rwc_location(mysqli $con,int $id,?array $allowed):?array {
    if($id<1||$allowed===[]||(is_array($allowed)&&!in_array($id,$allowed,true)))return null;
    $stmt=rwc_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;
}
function rwc_reset(mysqli $con,int $location):array {
    // These are the exact twelve updates performed by the old Joomla uninstallapp view.
    $operations=[
        ['jos_app_jobtype',"UPDATE `jos_app_jobtype` SET update_status='0'",false],
        ['jos_app_jobtype_locationlog',"UPDATE `jos_app_jobtype_locationlog` SET status='0' WHERE orglocation=?",true],
        ['jos_app_empshift',"UPDATE `jos_app_empshift` SET update_status='0'",false],
        ['jos_app_empshift_locationlog',"UPDATE `jos_app_empshift_locationlog` SET status='0' WHERE orglocation=?",true],
        ['jos_app_designation',"UPDATE `jos_app_designation` SET update_status='0'",false],
        ['jos_app_designation_locationlog',"UPDATE `jos_app_designation_locationlog` SET status='0' WHERE orglocation=?",true],
        ['jos_app_employee',"UPDATE `jos_app_employee` SET update_status='0'",false],
        ['jos_app_employee_locationlog',"UPDATE `jos_app_employee_locationlog` SET status='0' WHERE orglocation=?",true],
        ['jos_app_employeeface',"UPDATE jos_app_employeeface A JOIN jos_app_employee B ON A.empid=B.id SET A.update_status='0'",false],
        ['jos_app_employeeface_locationlog',"UPDATE `jos_app_employeeface_locationlog` SET status='0' WHERE orglocation=?",true],
        ['jos_app_empshiftgroup',"UPDATE `jos_app_empshiftgroup` SET update_status='0'",false],
        ['jos_app_empshiftgroup_locationlog',"UPDATE `jos_app_empshiftgroup_locationlog` SET status='0' WHERE orglocation=?",true],
    ];
    $affected=[];$con->begin_transaction();
    try{
        foreach($operations as [$table,$sql,$scoped]){$stmt=rwc_stmt($con,$sql);if($scoped)$stmt->bind_param('i',$location);$stmt->execute();$affected[$table]=$stmt->affected_rows;$stmt->close();}
        $con->commit();return $affected;
    }catch(Throwable $e){$con->rollback();throw $e;}
}

$acl=require_acl('can_view',$pageLink);
$canReset=!empty($acl['can_delete']);
$allowed=rwc_accessible_ids($con);$locations=rwc_locations($con,$allowed);
$selectedId=max(0,(int)($_POST['location_id']??0));$selected=null;$confirmStep=false;

if($_SERVER['REQUEST_METHOD']==='POST'){
    $action=(string)($_POST['action']??'');
    if(!verify_csrf($_POST['_csrf']??null))$errors[]='Security token expired. Please refresh and try again.';
    elseif(!$canReset)$errors[]='You do not have permission to reset web-console data.';
    else{
        $selected=rwc_location($con,$selectedId,$allowed);
        if(!$selected)$errors[]='Select a valid authorized location.';
        elseif($action==='prepare')$confirmStep=true;
        elseif($action==='reset'){
            if(($_POST['confirm_reset']??'')!=='1'){$errors[]='Confirm that you understand this reset is irreversible.';$confirmStep=true;}
            else try{$affected=rwc_reset($con,$selectedId);audit_log('reset.web_console','jos_app_orglocation',(string)$selectedId,'location='.$selected['name'].'; affected='.json_encode($affected));$_SESSION['flash_reset_web_console']='Web Console synchronization flags were reset successfully for '.$selected['name'].'.';redirect('/'.$pageLink);}catch(Throwable $e){$errors[]='The reset could not be completed. No database changes were committed.';$confirmStep=true;}
        }else$errors[]='Invalid reset request.';
    }
}

console_header('Reset Web Console',$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">Reset Web Console</span></div><h1 class="text-2xl font-bold text-slate-900">Reset Web Console</h1><p class="mt-1 text-sm text-slate-500">Reset web-console synchronization flags for a selected terminal location.</p></div>
<?php if($flash):?><div class="mb-5 rounded-xl border border-emerald-100 bg-emerald-50 px-5 py-4 text-sm font-semibold text-emerald-700"><i class="fa-solid fa-circle-check mr-2"></i><?=h($flash)?></div><?php endif;?>
<?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;?>
<div class="mb-5 rounded-2xl border border-amber-200 bg-amber-50 p-5"><div class="flex gap-3"><i class="fa-solid fa-triangle-exclamation mt-0.5 text-amber-600"></i><div><h2 class="font-bold text-amber-900">High-risk maintenance action</h2><p class="mt-1 text-sm font-medium leading-6 text-amber-800">This irreversible operation resets synchronization flags across job types, shifts, designations, employees, employee faces, and shift groups, plus location-log flags for the selected terminal location. It does not delete records or reset terminal keys.</p></div></div></div>
<?php if($confirmStep&&$selected):?>
<section class="rounded-2xl border border-red-200 bg-white shadow-sm"><div class="border-b border-red-100 px-5 py-4"><h2 class="text-lg font-bold text-red-700">Confirm Reset Web Console</h2><p class="mt-1 text-sm text-slate-500">Selected Location: <strong class="text-slate-800"><?=h($selected['name'])?></strong></p></div><form method="post" class="p-5"><input type="hidden" name="_csrf" value="<?=h(csrf_token())?>"><input type="hidden" name="action" value="reset"><input type="hidden" name="location_id" value="<?=$selectedId?>"><label class="flex items-start gap-3 rounded-xl border border-red-100 bg-red-50 p-4 text-sm font-semibold text-red-800"><input type="checkbox" name="confirm_reset" value="1" required class="mt-1">I understand that this reset is irreversible and will reset synchronization flags for <?=h($selected['name'])?>.</label><div class="mt-5 flex gap-3"><button type="submit" class="rounded-xl bg-red-600 px-6 py-3 text-sm font-bold text-white hover:bg-red-700" onclick="this.disabled=true;this.form.submit();"><i class="fa-solid fa-arrows-rotate mr-2"></i>Confirm Reset</button><a href="/<?=$pageLink?>" class="rounded-xl border border-slate-200 px-6 py-3 text-sm font-bold text-slate-600">Cancel</a></div></form></section>
<?php else:?>
<section class="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">Location (Reset Web Console)</h2><p class="mt-1 text-sm font-medium text-slate-400">Choose the terminal location whose location-log synchronization flags must be reset.</p></div><form method="post" class="p-5"><input type="hidden" name="_csrf" value="<?=h(csrf_token())?>"><input type="hidden" name="action" value="prepare"><label class="block max-w-xl text-sm font-bold text-slate-700">Select 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 $location):?><option value="<?=(int)$location['id']?>" <?=$selectedId===(int)$location['id']?'selected':''?>><?=h($location['name'])?></option><?php endforeach;?></select></label><?php if(!$locations):?><p class="mt-3 text-sm font-semibold text-amber-700">No authorized terminal locations are available.</p><?php endif;?><button type="submit" <?=(!$canReset||!$locations)?'disabled':''?> class="mt-5 rounded-xl bg-red-600 px-7 py-3 text-sm font-bold text-white hover:bg-red-700 disabled:cursor-not-allowed disabled:opacity-50"><i class="fa-solid fa-arrow-right mr-2"></i>Go</button></form></section>
<?php endif;?>
<?php console_footer();
