<?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/hardening_foundation.php';

$pdo = db();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        verify_csrf();
        if ((string)($_POST['action'] ?? '') !== 'run_hardening_validation') {
            throw new RuntimeException('Unsupported hardening action.');
        }
        $result = dental_hardening_record($pdo);
        audit_required('hardening_validation_run', 'system', null, [
            'version' => (string)$result['version'],
            'ready' => !empty($result['ready']),
            'blocked' => (int)($result['counts']['blocked'] ?? 0),
            'review' => (int)($result['counts']['review'] ?? 0),
            'fingerprint' => (string)$result['fingerprint'],
        ]);
        flash(!empty($result['ready']) ? 'success' : 'error', !empty($result['ready'])
            ? 'Hardening foundation checks passed. Review items remain advisory until the external CI pipeline runs.'
            : (int)($result['counts']['blocked'] ?? 0) . ' hardening foundation check(s) are blocked.');
        header('Location: hardening_center.php');
        exit;
    } catch (Throwable $exception) {
        $reference = strtoupper(substr(hash('sha256', microtime(true) . '|' . random_bytes(12)), 0, 12));
        if (function_exists('dental_runtime_write_log')) dental_runtime_write_log('Hardening validation failed [' . $reference . ']: ' . $exception->getMessage());
        flash('error', 'Hardening validation could not complete. Reference: ' . $reference . '. ' . $exception->getMessage());
        header('Location: hardening_center.php');
        exit;
    }
}

$current = dental_hardening_run($pdo);
$latest = null;
try {
    if (schema_table_exists(table('system_hardening_runs'))) {
        $latest = $pdo->query('SELECT * FROM `' . table('system_hardening_runs') . '` ORDER BY id DESC LIMIT 1')->fetch() ?: null;
    }
} catch (Throwable) {
    $latest = null;
}

render_header('Hardening Center', 'super');
?>
<section class="page-hero compact">
    <div>
        <span class="eyebrow">DentalCare <?= e(app_release_version()) ?></span>
        <h1>Hardening Center</h1>
        <p>Automated engineering checks for migration integrity, test infrastructure, static-analysis configuration, release safety, and source-policy risks.</p>
    </div>
    <form method="post">
        <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
        <input type="hidden" name="action" value="run_hardening_validation">
        <button class="btn primary" type="submit">Run hardening validation</button>
    </form>
</section>

<div class="stat-grid">
    <?php stat_card('Foundation status', !empty($current['ready']) ? 'PASS' : 'BLOCKED', (int)$current['counts']['blocked'] . ' blocked'); ?>
    <?php stat_card('Automated tests', (string)$current['scan']['test_file_count'], 'PHP test files'); ?>
    <?php stat_card('Strict types', (string)$current['scan']['strict_types_percent'] . '%', (int)$current['scan']['strict_types_files'] . ' of ' . (int)$current['scan']['php_files'] . ' PHP files'); ?>
    <?php stat_card('Review findings', (string)$current['counts']['review'], 'Advisory; not hidden'); ?>
</div>

<?php if ($latest): ?>
<section class="card">
    <h2>Last recorded run</h2>
    <p><strong><?= e(strtoupper((string)$latest['status'])) ?></strong> · <?= e((string)$latest['created_at']) ?> · Fingerprint <?= e(substr((string)$latest['fingerprint_sha256'], 0, 16)) ?>…</p>
</section>
<?php endif; ?>

<section class="card">
    <h2>Current checks</h2>
    <div class="table-wrap">
        <table>
            <thead><tr><th>Check</th><th>Status</th><th>Evidence</th></tr></thead>
            <tbody>
            <?php foreach ((array)$current['checks'] as $check):
                $status = strtolower((string)($check['status'] ?? 'review'));
            ?>
                <tr>
                    <td><strong><?= e((string)$check['label']) ?></strong></td>
                    <td><span class="badge <?= $status === 'pass' ? 'success' : ($status === 'blocked' ? 'danger' : 'warning') ?>"><?= e(strtoupper($status)) ?></span></td>
                    <td><?= e((string)$check['detail']) ?></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</section>

<div class="grid-2">
<section class="card">
    <h2>Engineering foundation</h2>
    <dl class="detail-list">
        <div><dt>PHP source files scanned</dt><dd><?= e((string)$current['scan']['php_files']) ?></dd></div>
        <div><dt>Automated PHP test files</dt><dd><?= e((string)$current['scan']['test_file_count']) ?></dd></div>
        <div><dt>Prohibited executable calls</dt><dd><?= e((string)count((array)$current['scan']['prohibited_calls'])) ?></dd></div>
        <div><dt>Direct request-to-SQL patterns</dt><dd><?= e((string)count((array)$current['scan']['direct_sql_input_patterns'])) ?></dd></div>
        <div><dt>Files over 4,000 lines</dt><dd><?= e((string)count((array)$current['scan']['large_files'])) ?></dd></div>
    </dl>
</section>
<section class="card">
    <h2>Assurance boundary</h2>
    <p>This page proves that the hardening files and internal policies are present and performs safe source/database checks. It does not pretend that PHPUnit, PHPStan, Semgrep, browser tests, or penetration tests ran on the production server.</p>
    <p>The included CI workflow runs those external checks when the canonical source is placed in a Git repository.</p>
</section>
</div>

<?php if (!empty($current['scan']['direct_sql_input_patterns']) || !empty($current['scan']['large_files'])): ?>
<section class="card">
    <h2>Review queue</h2>
    <?php if (!empty($current['scan']['direct_sql_input_patterns'])): ?>
        <h3>Potential raw SQL input patterns</h3>
        <ul><?php foreach (array_slice((array)$current['scan']['direct_sql_input_patterns'], 0, 20) as $item): ?><li><code><?= e((string)$item) ?></code></li><?php endforeach; ?></ul>
    <?php endif; ?>
    <?php if (!empty($current['scan']['large_files'])): ?>
        <h3>Large refactoring candidates</h3>
        <ul><?php foreach ((array)$current['scan']['large_files'] as $item): ?><li><code><?= e((string)$item) ?></code></li><?php endforeach; ?></ul>
    <?php endif; ?>
</section>
<?php endif; ?>
<?php render_footer(); ?>
