<?php

declare(strict_types=1);

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

$pdo = db();
$readOnlyPreview = function_exists('task_preview_mode') && task_preview_mode();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        verify_csrf();
        if ($readOnlyPreview) throw new RuntimeException('Return to the signed-in Superuser workspace before recording operational evidence.');
        $action = (string)($_POST['action'] ?? '');
        if ($action !== 'record_snapshot') throw new RuntimeException('Unknown operational-health action.');
        $snapshot = dental_operational_health_snapshot($pdo);
        $id = dental_operational_health_record_snapshot($pdo, $snapshot);
        audit_required('operational_health_snapshot_recorded', 'system', $id, [
            'overall'=>(string)$snapshot['overall'],
            'counts'=>(array)$snapshot['counts'],
            'fingerprint'=>(string)$snapshot['fingerprint'],
        ]);
        flash(($snapshot['overall'] ?? '') === 'blocked' ? 'error' : 'success',
            ($snapshot['overall'] ?? '') === 'blocked'
                ? 'Operational snapshot recorded with blocked checks. Correct the blocked items before updates, backups, or clinical use.'
                : 'Operational-health snapshot recorded.');
    } catch (Throwable $exception) {
        flash('error', $exception->getMessage());
    }
    header('Location: operational-health');
    exit;
}

$snapshot = dental_operational_health_snapshot($pdo);
$history = dental_operational_health_recent_snapshots($pdo, 20);
$tableReady = dental_operational_health_table_ready($pdo);
$statusLabel = ['pass'=>'Healthy','review'=>'Review required','blocked'=>'Blocked'][(string)$snapshot['overall']] ?? 'Review required';

render_header('Operational Health & Recovery');
?>
<section class="admin-hero card">
    <div>
        <span class="eyebrow">System & Recovery</span>
        <h2>Operational Health & Recovery</h2>
        <p>One non-blocking view of database, storage, sessions, protected files, backups, release alignment, and PHP requirements. Optional warnings never create a global staff redirect.</p>
        <div class="status-actions">
            <a class="btn ghost" href="backup-restore">Backup & Restore</a>
            <a class="btn ghost" href="production-monitoring">Production Monitor</a>
            <a class="btn ghost" href="system-setup?tab=updates">Updates & Database</a>
        </div>
    </div>
    <div class="admin-hero-icon"><?=dental_icon('shield')?></div>
</section>

<section class="stats mini-stats">
    <?php stat_card('Overall', $statusLabel, 'Generated ' . date('M j, Y g:i A', strtotime((string)$snapshot['generated_at']))); ?>
    <?php stat_card('Passed', (string)$snapshot['counts']['pass'], 'Operational checks clear'); ?>
    <?php stat_card('Review', (string)$snapshot['counts']['review'], 'Advisory, not a global blocker'); ?>
    <?php stat_card('Blocked', (string)$snapshot['counts']['blocked'], 'Core write/database failure'); ?>
</section>

<?php if (!$tableReady): ?>
<div class="alert warning"><strong>Snapshot history is not installed.</strong> Live checks are available, but recording evidence requires the v0.9.3.0 migration. <a href="system-setup?tab=updates">Open Updates & Database</a>.</div>
<?php endif; ?>

<section class="card">
    <div class="card-head"><div><h2>Live operational checks</h2><p>Blocked means the application cannot safely write a required resource. Review means optional or governance evidence needs attention.</p></div>
    <?php if ($tableReady): ?><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">Record current snapshot</button></form><?php endif; ?></div>
    <div class="table-wrap"><table><thead><tr><th>Area</th><th>Status</th><th>Result</th><th>Details</th><th>Action</th></tr></thead><tbody>
    <?php foreach ((array)$snapshot['checks'] as $check):
        $state=(string)($check['status'] ?? 'review');
        $class=$state==='pass'?'badge success':($state==='blocked'?'badge danger':'badge warning');
        $link=trim((string)($check['link'] ?? ''));
    ?>
        <tr>
            <td><strong><?=e((string)$check['label'])?></strong></td>
            <td><span class="<?=$class?>"><?=e(ucfirst($state))?></span></td>
            <td><?=e((string)$check['metric'])?></td>
            <td><?=e((string)$check['detail'])?></td>
            <td><?=$link!==''?'<a href="'.e($link).'">Open</a>':'—'?></td>
        </tr>
    <?php endforeach; ?></tbody></table></div>
    <p class="muted">Fingerprint: <code><?=e((string)$snapshot['fingerprint'])?></code></p>
</section>

<section class="card">
    <div class="card-head"><div><h2>Safe cleanup inventory</h2><p>Informational only. Nothing is deleted from this page.</p></div></div>
    <div class="table-wrap"><table><thead><tr><th>Candidate group</th><th>Files</th><th>Estimated size</th></tr></thead><tbody>
    <?php foreach ((array)$snapshot['cleanup_inventory'] as $row): ?>
        <tr><td><?=e((string)$row['label'])?></td><td><?=e((string)$row['count'])?></td><td><?=e(dental_storage_format_bytes((int)$row['bytes']))?></td></tr>
    <?php endforeach; ?></tbody></table></div>
    <div class="alert info"><strong>No automatic deletion.</strong> Review sessions, logs, installers, and backup retention before removing anything. Patient files and current backups are never included in this inventory.</div>
</section>

<section class="card">
    <div class="card-head"><div><h2>Recorded evidence</h2><p>Snapshots document system state without storing credentials, patient records, clinical notes, or raw logs.</p></div></div>
    <div class="table-wrap"><table><thead><tr><th>Recorded</th><th>Release</th><th>Status</th><th>Pass</th><th>Review</th><th>Blocked</th><th>Recorded by</th><th>Fingerprint</th></tr></thead><tbody>
    <?php foreach ($history as $row): ?>
        <tr>
            <td><?=e(date('M j, Y g:i A', strtotime((string)$row['created_at'])))?></td>
            <td><?=e((string)$row['installed_version'])?> / <?=e((string)$row['release_version'])?></td>
            <td><?=e(ucfirst((string)$row['overall_status']))?></td>
            <td><?=e((string)$row['pass_count'])?></td><td><?=e((string)$row['review_count'])?></td><td><?=e((string)$row['blocked_count'])?></td>
            <td><?=e((string)($row['creator_name'] ?? $row['creator_email'] ?? 'System'))?></td>
            <td><code><?=e(substr((string)$row['fingerprint_sha256'],0,18))?>…</code></td>
        </tr>
    <?php endforeach; if (!$history): ?><tr><td colspan="8" class="muted">No operational-health snapshot has been recorded.</td></tr><?php endif; ?>
    </tbody></table></div>
</section>
<?php render_footer();
