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

$pageLink = 'reset-data/reset-terminal-key.php';
$acl = require_acl('can_view', $pageLink);
$canReset = !empty($acl['can_delete']);
$errors = [];
$flash = $_SESSION['flash_reset_terminal_key'] ?? null;
unset($_SESSION['flash_reset_terminal_key']);

function rtk_stmt(mysqli $con, string $sql): mysqli_stmt {
    $stmt = $con->prepare($sql);
    if (!$stmt) throw new RuntimeException('Unable to prepare terminal-key operation.');
    return $stmt;
}
function rtk_col_exists(mysqli $con, string $table, string $column): bool {
    $stmt=rtk_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 rtk_accessible_ids(mysqli $con): ?array {
    $user=current_user()?:[];
    if((int)($user['role_id']??0)===1)return null;
    if(!rtk_col_exists($con,'jos_admin_users','terminal_access'))return [];
    $uid=(int)($user['id']??0);$stmt=rtk_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 rtk_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=rtk_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 rtk_location(mysqli $con, int $id, ?array $allowed): ?array {
    if($id<1||$allowed===[]||(is_array($allowed)&&!in_array($id,$allowed,true)))return null;
    $stmt=rtk_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 rtk_license_counts(mysqli $con, int $locationId): array {
    $stmt=rtk_stmt($con,"SELECT COUNT(*) total,SUM(CASE WHEN status<>0 THEN 1 ELSE 0 END) active FROM jos_app_license_key WHERE orglocation=?");
    $stmt->bind_param('i',$locationId);$stmt->execute();$row=$stmt->get_result()->fetch_assoc()?:[];$stmt->close();
    return ['total'=>(int)($row['total']??0),'active'=>(int)($row['active']??0)];
}
function rtk_reset(mysqli $con, int $locationId): int {
    $con->begin_transaction();
    try{
        $stmt=rtk_stmt($con,"UPDATE jos_app_license_key SET status='0' WHERE orglocation=? AND status<>0");
        $stmt->bind_param('i',$locationId);$stmt->execute();$affected=$stmt->affected_rows;$stmt->close();
        if($affected<1)throw new RuntimeException('No active terminal key was available to reset.');
        $con->commit();return $affected;
    }catch(Throwable $e){$con->rollback();throw $e;}
}

$allowed=rtk_accessible_ids($con);$locations=rtk_locations($con,$allowed);
$selectedId=max(0,(int)($_POST['location_id']??0));$selected=null;$counts=['total'=>0,'active'=>0];$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 terminal keys.';
    else{
        $selected=rtk_location($con,$selectedId,$allowed);
        if(!$selected)$errors[]='Select a valid authorized location.';
        else{
            $counts=rtk_license_counts($con,$selectedId);
            if($counts['total']<1)$errors[]='The selected location has no registered terminal key.';
            elseif($counts['active']<1)$errors[]='The terminal key for this location is already reset.';
            elseif($action==='prepare')$confirmStep=true;
            elseif($action==='reset'){
                if(($_POST['confirm_reset']??'')!=='1'){$errors[]='Confirm that you want to reset the terminal key.';$confirmStep=true;}
                else try{$affected=rtk_reset($con,$selectedId);audit_log('reset.terminal_key','jos_app_orglocation',(string)$selectedId,'location='.$selected['name'].'; records='.$affected);$_SESSION['flash_reset_terminal_key']='Terminal key status was reset successfully for '.$selected['name'].'. Reactivation is required before the key can be used again.';redirect('/'.$pageLink);}catch(Throwable $e){$errors[]='The terminal key could not be reset. No database changes were committed.';$confirmStep=true;}
            }else$errors[]='Invalid reset request.';
        }
    }
}

console_header('Reset Terminal Key',$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 Terminal Key</span></div><h1 class="text-2xl font-bold text-slate-900">Reset Terminal Key</h1><p class="mt-1 text-sm text-slate-500">Deactivate the registered terminal key 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">Terminal reactivation will be required</h2><p class="mt-1 text-sm font-medium leading-6 text-amber-800">This action deactivates the existing license record for the selected location. It does not delete or display the key, but the terminal cannot use it again until an administrator reactivates the license.</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 Terminal Key</h2><p class="mt-1 text-sm text-slate-500">Selected Location: <strong class="text-slate-800"><?=h($selected['name'])?></strong></p><p class="mt-1 text-xs font-semibold text-slate-400">Affected license records: <?=h((string)$counts['active'])?></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 the terminal key for <?=h($selected['name'])?> will be deactivated and require reactivation.</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-key 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">Reset Terminal Key</h2><p class="mt-1 text-sm font-medium text-slate-400">Select the terminal location whose license-key status 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();
