<?php

declare(strict_types=1);

require DENTAL_ROOT . '/app/bootstrap.php';
require_login();
require_roles(['super_admin']);
require_once DENTAL_ROOT . '/app/navigation_integrity.php';
require DENTAL_ROOT . '/app/layout.php';

$pdo = db();

if (isset($_GET['export']) && (string)$_GET['export'] === 'csv') {
    $snapshot = dental_navigation_integrity_snapshot();
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="dentalcare-route-role-visibility-' . date('Ymd-His') . '.csv"');
    $out = fopen('php://output', 'wb');
    fputcsv($out, ['Route','Slug','File','Classification','Visibility','Authorized roles','Workspace roles','Permission','Action','Aliases','Status','Issues']);
    foreach ((array)$snapshot['rows'] as $row) {
        fputcsv($out, [
            $row['route'],$row['slug'],$row['relative_file'],$row['classification'],$row['visibility'],
            implode('|',(array)$row['access_roles']),implode('|',(array)$row['navigation_roles']),$row['permission'],$row['action'],
            implode('|',(array)$row['aliases']),!empty($row['ready'])?'Ready':'Blocked',implode(' ',(array)$row['issues']),
        ]);
    }
    fclose($out);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        verify_csrf();
        $action = (string)($_POST['action'] ?? '');
        if ($action === 'record_snapshot') {
            $snapshot = dental_navigation_integrity_snapshot();
            setting_set('system','last_navigation_integrity_check_at',date(DATE_ATOM));
            setting_set('system','last_navigation_integrity_fingerprint',(string)$snapshot['fingerprint']);
            setting_set('system','last_navigation_integrity_blocked',(string)($snapshot['counts']['blocked'] ?? 0));
            audit_required('navigation_integrity_snapshot_recorded','system',null,[
                'fingerprint'=>(string)$snapshot['fingerprint'],
                'counts'=>(array)$snapshot['counts'],
            ]);
            flash(!empty($snapshot['ready'])?'success':'error', !empty($snapshot['ready'])
                ? 'Route, role, slug, and file integrity passed for the current release.'
                : (string)$snapshot['counts']['blocked'] . ' route integrity issue(s) require correction.');
            header('Location: navigation-diagnostics');
            exit;
        }
        if ($action === 'reset_workspace') {
            $result = dental_navigation_reset_current_workspace();
            audit_required('navigation_workspace_recovered','user',(int)(current_user()['id'] ?? 0),['cleared'=>(array)$result['cleared']]);
            flash('success','Temporary navigation and workflow context was cleared. No clinic record was changed.');
            header('Location: navigation-diagnostics?navigation_guard_reset=1');
            exit;
        }
        throw new RuntimeException('Unsupported navigation diagnostic action.');
    } catch (Throwable $exception) {
        flash('error',$exception->getMessage());
    }
}

$snapshot = dental_navigation_integrity_snapshot();
$session = dental_navigation_session_snapshot();
$counts = (array)$snapshot['counts'];
$show = (string)($_GET['show'] ?? 'all');
$rows = array_values(array_filter((array)$snapshot['rows'], static function(array $row) use ($show): bool {
    if ($show === 'blocked') return empty($row['ready']);
    if ($show === 'direct') return ($row['visibility'] ?? '') === 'Direct / linked';
    if ($show === 'internal') return ($row['classification'] ?? '') === 'internal';
    return true;
}));

render_header('Navigation & Role Integrity');
?>
<section class="role-welcome card">
    <div><span class="eyebrow">v0.9.1.3 reliability control</span><h2>Navigation & Role Integrity</h2><p>One authoritative inventory for routed PHP pages, clean URLs, Task View authorization, workspace visibility, aliases, and missing files.</p><div class="status-actions"><form method="post"><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="action" value="record_snapshot"><button class="btn primary" type="submit">Run and record integrity check</button></form><a class="btn ghost" href="navigation-diagnostics?export=csv">Export CSV</a><a class="btn ghost" href="navigation-recovery">Workspace recovery</a></div></div>
    <span class="badge <?=!empty($snapshot['ready'])?'success':'warning'?>"><?=!empty($snapshot['ready'])?'READY':'REVIEW'?></span>
</section>
<section class="stats-grid">
    <?php stat_card('Configured routes',(int)($counts['routes']??0),'All clean and legacy routed endpoints'); ?>
    <?php stat_card('Ready',(int)($counts['ready']??0),'File, slug, and authorization aligned'); ?>
    <?php stat_card('Blocked',(int)($counts['blocked']??0),'Requires correction before release'); ?>
    <?php stat_card('Workspace links',(int)($counts['workspace_navigation']??0),'Visible in at least one Task View'); ?>
    <?php stat_card('Direct / linked',(int)($counts['direct_linked']??0),'Contextual pages and actions'); ?>
</section>
<section class="card">
    <div class="card-head"><div><h2>Current session isolation</h2><p>Temporary state can be reset without changing any clinic record.</p></div><span class="badge"><?=e(ucwords(str_replace('_',' ',(string)$session['active_role'])))?></span></div>
    <p><strong>Primary role:</strong> <?=e(ucwords(str_replace('_',' ',(string)$session['actual_role'])))?> · <strong>Temporary context keys:</strong> <?=count((array)$session['context'])?></p>
    <form method="post"><input type="hidden" name="csrf" value="<?=e(csrf_token())?>"><input type="hidden" name="action" value="reset_workspace"><button class="btn ghost" type="submit">Clear temporary workspace context</button></form>
</section>
<section class="card">
    <div class="card-head"><div><h2>Route inventory</h2><p>Aliases pointing to the same PHP target are shown for review and are not automatically treated as defects.</p></div><div class="status-actions"><a class="btn ghost" href="navigation-diagnostics?show=all">All</a><a class="btn ghost" href="navigation-diagnostics?show=blocked">Blocked</a><a class="btn ghost" href="navigation-diagnostics?show=direct">Direct / linked</a><a class="btn ghost" href="navigation-diagnostics?show=internal">Internal</a></div></div>
    <div class="table-wrap"><table><thead><tr><th>Route</th><th>PHP target</th><th>Visibility</th><th>Authorized Task Views</th><th>Workspace links</th><th>Permission/action</th><th>Status</th></tr></thead><tbody>
    <?php foreach ($rows as $row): ?>
        <tr>
            <td><strong><?=e((string)$row['route'])?></strong><br><small>/<?=e((string)$row['slug'])?></small><?php if($row['aliases']):?><br><small>Aliases: <?=e(implode(', ',(array)$row['aliases']))?></small><?php endif;?></td>
            <td><code><?=e((string)$row['relative_file'])?></code></td>
            <td><?=e((string)$row['visibility'])?><br><small><?=e((string)$row['classification'])?></small></td>
            <td><?=e($row['access_roles']?implode(', ',array_map(static fn(string $r):string=>ucwords(str_replace('_',' ',$r)),(array)$row['access_roles'])):'—')?></td>
            <td><?=e($row['navigation_roles']?implode(', ',array_map(static fn(string $r):string=>ucwords(str_replace('_',' ',$r)),(array)$row['navigation_roles'])):'Contextual only')?></td>
            <td><?=e(trim((string)$row['permission'].' '.(string)$row['action'])?:'Role guard')?></td>
            <td><span class="badge <?=!empty($row['ready'])?'success':'warning'?>"><?=!empty($row['ready'])?'Ready':'Blocked'?></span><?php if($row['issues']):?><br><small><?=e(implode(' ',(array)$row['issues']))?></small><?php endif;?></td>
        </tr>
    <?php endforeach; ?>
    </tbody></table></div>
</section>
<?php render_footer();
