<?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/setup_readiness.php';
require_once DENTAL_ROOT . '/app/release_candidate.php';

$pdo = db();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        verify_csrf();
        if ((string)($_POST['action'] ?? '') === 'mark_manual_flow_reviewed') {
            $record = dental_release_candidate_record_manual_flow(
                (string)($_POST['confirmation'] ?? ''),
                trim((string)($_POST['flow_scope'] ?? '')),
                (string)($_POST['flow_note'] ?? '')
            );
            audit_required('manual_role_flow_reviewed', 'system', null, [
                'version' => (string)($record['version'] ?? ''),
                'scope' => (string)($record['scope'] ?? ''),
                'evidence_id' => (string)($record['evidence_id'] ?? ''),
            ]);
            flash('success', 'The current-release clinic workflow confirmation was recorded.');
            header('Location: go_live_checklist.php#version-bound-flow');
            exit;
        }
    } catch (Throwable $exception) {
        flash('error', $exception->getMessage());
    }
}

$setup = dental_setup_readiness_snapshot($pdo);
$release = dental_release_candidate_snapshot($pdo);
$approved = dental_release_candidate_is_approved($pdo);
$gates = (array)($release['gates'] ?? []);
$readyCount = count(array_filter($gates, static fn(array $gate): bool => !empty($gate['ready'])));
$totalCount = count($gates);
$percent = $totalCount > 0 ? (int)round(($readyCount / $totalCount) * 100) : 0;
$manualEvidence = dental_release_candidate_manual_flow_evidence();
$manualFlowReady = false;
foreach ($gates as $gate) { if ((string)($gate['key'] ?? '') === 'manual_flow') { $manualFlowReady = !empty($gate['ready']); break; } }
$canBuildInstallers = !function_exists('dental_distribution_feature_allowed') || dental_distribution_feature_allowed('package_builder');

render_header('Production Readiness');
?>
<section class="role-welcome card setup-wizard-hero">
    <div>
        <span class="eyebrow">DentalCare <?= e(app_release_version()) ?></span>
        <h2>Production Readiness</h2>
        <p>DentalCare performs the technical validation automatically. You only confirm the three items that require the clinic’s real hosting environment: email delivery, one complete clinic workflow, and one verified restore drill.</p>
        <div class="status-actions">
            <a class="btn primary" href="production_monitoring.php#automated-validation">Run Production Validation</a>
            <a class="btn ghost" href="email_settings.php">Test Clinic Email</a>
            <a class="btn ghost" href="backup_restore.php">Backup &amp; Restore</a>
        </div>
    </div>
    <div class="setup-progress-ring"><strong><?= e((string)$percent) ?>%</strong><span><?= e((string)$readyCount) ?> / <?= e((string)$totalCount) ?> gates</span></div>
</section>

<section class="card" id="release-candidate">
    <div class="card-head">
        <div>
            <span class="eyebrow">Automatic release decision</span>
            <h2><?= $approved ? 'Production package unlocked' : 'Production package remains protected' ?></h2>
            <p><?= $approved
                ? 'Automated technical validation and all three live-environment confirmations are current for this exact release.'
                : 'No typed approval or nine-role paperwork is required. Resolve only the failed technical checks and the three live confirmations shown below.' ?></p>
        </div>
        <span class="badge <?= $approved ? 'success' : 'warning' ?>"><?= $approved ? 'READY' : 'PROTECTED' ?></span>
    </div>
    <?php if ($canBuildInstallers): ?><div class="status-actions"><a class="btn <?= $approved ? 'primary' : 'ghost' ?>" href="installer_builder.php">Open Installer Builder</a></div><?php endif; ?>
</section>

<section class="card checklist-section">
    <div class="card-head"><div><h2>Current release gates</h2><p>Technical gates are evaluated by the application. Live gates require evidence from this hosting environment.</p></div></div>
    <div class="go-live-list compact-scroll-list">
        <?php foreach ($gates as $gate): ?>
            <a class="go-live-row <?= !empty($gate['ready']) ? 'ready' : 'missing' ?>" href="<?= e((string)($gate['href'] ?? '#')) ?>">
                <span class="go-live-check"><?= !empty($gate['ready']) ? '✓' : '!' ?></span>
                <span><strong><?= e((string)($gate['title'] ?? 'Production gate')) ?></strong><small><?= e((string)($gate['detail'] ?? '')) ?></small></span>
                <em><?= e(!empty($gate['ready']) ? 'Ready' : ((string)($gate['actionLabel'] ?? 'Complete'))) ?></em>
            </a>
        <?php endforeach; ?>
    </div>
</section>

<section class="card checklist-section" id="version-bound-flow">
    <div class="card-head">
        <div><span class="eyebrow">Live confirmation 2 of 3</span><h2>Confirm one real clinic workflow</h2><p>Technical role and permission checks are automatic. Confirm only that one browser workflow worked on this installed server.</p></div>
        <span class="badge <?= $manualFlowReady ? 'success' : 'warning' ?>"><?= $manualFlowReady ? 'CURRENT' : 'REQUIRED' ?></span>
    </div>
    <?php if (!empty($manualEvidence['tested_at'])): ?><p class="muted">Last evidence: <?= e((string)$manualEvidence['tested_at']) ?> · <?= e(str_replace('_', ' ', (string)($manualEvidence['scope'] ?? 'clinic'))) ?></p><?php endif; ?>
    <form method="post" class="form-grid checklist-confirm-form">
        <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
        <input type="hidden" name="action" value="mark_manual_flow_reviewed">
        <label>Flow tested<select name="flow_scope" required><option value="appointment">Scheduled appointment</option><option value="walk_in">Walk-in visit</option><option value="both">Both scheduled and walk-in</option></select></label>
        <label>Confirmation<input name="confirmation" placeholder="FLOW TESTED <?= e(app_release_version()) ?>" required></label>
        <label class="wide">Evidence note<textarea name="flow_note" rows="3" minlength="20" placeholder="State the chair/treatment result, invoice/payment result, receipt, and checkout status." required></textarea></label>
        <div class="wide"><button class="btn primary" type="submit">Record clinic workflow confirmation</button></div>
    </form>
</section>

<section class="card checklist-section">
    <div class="card-head"><div><h2>Clinic configuration</h2><p>These setup items remain operational requirements, but they do not replace automated technical validation.</p></div><span class="badge"><?= e((string)($setup['percent'] ?? 0)) ?>%</span></div>
    <div class="go-live-list compact-scroll-list">
        <?php foreach ((array)($setup['steps'] ?? []) as $step): ?>
            <a class="go-live-row <?= !empty($step['ready']) ? 'ready' : 'missing' ?>" href="<?= e((string)($step['href'] ?? '#')) ?>">
                <span class="go-live-check"><?= !empty($step['ready']) ? '✓' : '!' ?></span>
                <span><strong><?= e((string)($step['title'] ?? 'Setup item')) ?></strong><small><?= e((string)($step['description'] ?? '')) ?></small></span>
                <em><?= !empty($step['ready']) ? 'Ready' : 'Configure' ?></em>
            </a>
        <?php endforeach; ?>
    </div>
</section>
<?php render_footer();
