<?php

declare(strict_types=1);

require DENTAL_ROOT . '/app/bootstrap.php';
require_login();
require_once DENTAL_ROOT . '/app/navigation_integrity.php';
require DENTAL_ROOT . '/app/layout.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        verify_csrf();
        if ((string)($_POST['action'] ?? '') !== 'reset_workspace') throw new RuntimeException('Unsupported recovery action.');
        $result = dental_navigation_reset_current_workspace();
        if (function_exists('audit')) audit('navigation_workspace_recovered', 'user', (int)(current_user()['id'] ?? 0), ['cleared'=>(array)$result['cleared']]);
        flash('success', 'Temporary navigation, patient, Task View, and update-status context was cleared. No clinic record was changed.');
        header('Location: dashboard.php?navigation_guard_reset=1');
        exit;
    } catch (Throwable $exception) {
        flash('error', $exception->getMessage());
    }
}

$session = dental_navigation_session_snapshot();
render_header('Workspace Recovery');
?>
<section class="card">
    <div class="card-head"><div><span class="eyebrow">Safe session repair</span><h2>Workspace Recovery</h2><p>Use this only when navigation, Task View, patient context, or a completed update appears stuck. It clears temporary session state only.</p></div></div>
    <div class="stats-grid">
        <?php stat_card('Signed-in role', ucwords(str_replace('_',' ',(string)$session['actual_role'])), 'Primary account role'); ?>
        <?php stat_card('Active Task View', ucwords(str_replace('_',' ',(string)$session['active_role'])), 'Current working role'); ?>
        <?php stat_card('Temporary context', count((array)$session['context']), 'Session keys currently present'); ?>
    </div>
    <div class="notice warning"><strong>This does not delete data.</strong> Patient records, appointments, encounters, treatments, payments, prescriptions, documents, and audit history remain unchanged.</div>
    <form method="post" class="status-actions">
        <input type="hidden" name="csrf" value="<?=e(csrf_token())?>">
        <input type="hidden" name="action" value="reset_workspace">
        <button class="btn primary" type="submit">Reset temporary workspace state</button>
        <a class="btn ghost" href="dashboard.php?navigation_guard_reset=1">Return to dashboard</a>
        <?php if (function_exists('actual_role') && actual_role()==='super_admin'): ?><a class="btn ghost" href="role-switch?return_primary=1&navigation_guard_reset=1">Return to Superuser workspace</a><?php endif; ?>
        <a class="btn ghost" href="logout.php">Sign out</a>
    </form>
</section>
<section class="card">
    <div class="card-head"><div><h2>Current temporary context</h2><p>These are session references, not clinical records.</p></div></div>
    <?php if (!$session['context']): ?><p class="muted">No temporary workflow context is currently stored.</p><?php else: ?>
        <div class="table-wrap"><table><thead><tr><th>Session key</th><th>Current value summary</th></tr></thead><tbody>
        <?php foreach ((array)$session['context'] as $key=>$value): ?><tr><td><code><?=e((string)$key)?></code></td><td><?=e(mb_substr(is_scalar($value)?(string)$value:(json_encode($value,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE)?:'[structured value]'),0,300))?></td></tr><?php endforeach; ?>
        </tbody></table></div>
    <?php endif; ?>
</section>
<?php render_footer();
