<?php

declare(strict_types=1);

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

$pdo = db();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        verify_csrf();
        $action = (string)($_POST['action'] ?? '');
        if ($action === 'save_clinic_quick_profile') {
            setting_set('clinic', 'name', trim((string)($_POST['clinic_name'] ?? '')));
            setting_set('clinic', 'public_email', trim((string)($_POST['public_email'] ?? '')));
            setting_set('clinic', 'phone', trim((string)($_POST['phone'] ?? '')));
            setting_set('clinic', 'address', trim((string)($_POST['address'] ?? '')));
            audit('clinic_setup_wizard_quick_profile_saved','settings',null,[]);
            flash('success', 'Clinic quick profile saved. Continue the remaining setup steps below.');
        } elseif ($action === 'mark_setup_reviewed') {
            setting_set('system', 'first_time_setup_reviewed_at', date('Y-m-d H:i:s'));
            setting_set('system', 'first_time_setup_reviewed_by', (string)(current_user()['id'] ?? 0));
            audit('clinic_setup_wizard_reviewed','system',null,[]);
            flash('success', 'Setup review was recorded. Use Go-Live Checklist for final client/demo readiness.');
        }
    } catch (Throwable $exception) {
        flash('error', $exception->getMessage());
    }
    header('Location: setup_wizard.php');
    exit;
}

$snapshot = dental_setup_readiness_snapshot($pdo);
$steps = (array)($snapshot['steps'] ?? []);
$clinic = (array)($snapshot['clinic'] ?? []);
$missing = dental_setup_missing_titles($snapshot);
$priorityMissing = function_exists('dental_setup_priority_missing_steps') ? dental_setup_priority_missing_steps($snapshot, 5) : array_slice(array_filter($steps, static fn(array $step): bool => empty($step['ready'])), 0, 5);
$groups = function_exists('dental_setup_grouped_steps') ? dental_setup_grouped_steps($snapshot) : [];

render_header('First-Time Clinic Setup');
?>
<style>
.setup-wizard-compact .setup-summary-strip{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:12px;margin:14px 0}.setup-wizard-compact .setup-summary-tile{border:1px solid var(--border,#dfe7ef);border-radius:16px;padding:14px;background:var(--surface,#fff)}.setup-wizard-compact .setup-summary-tile strong{display:block;font-size:1.35rem}.setup-wizard-compact .setup-attention-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px}.setup-wizard-compact .setup-action-card{border:1px solid var(--border,#dfe7ef);border-radius:16px;padding:14px;background:var(--surface,#fff);display:flex;flex-direction:column;gap:8px;min-height:160px}.setup-wizard-compact .setup-action-card .btn{margin-top:auto}.setup-wizard-compact .setup-group-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(310px,1fr));gap:14px}.setup-wizard-compact .setup-group-card{display:flex;flex-direction:column;gap:10px}.setup-wizard-compact .setup-group-head{display:flex;align-items:flex-start;justify-content:space-between;gap:12px}.setup-wizard-compact .setup-group-progress{font-weight:700;white-space:nowrap}.setup-wizard-compact .setup-compact-list{display:grid;gap:8px}.setup-wizard-compact .setup-compact-row{display:grid;grid-template-columns:auto minmax(0,1fr) auto;align-items:center;gap:10px;border:1px solid var(--border,#dfe7ef);border-radius:14px;padding:10px 12px;background:rgba(255,255,255,.72)}.setup-wizard-compact .setup-compact-row strong{display:block}.setup-wizard-compact .setup-compact-row small{display:block;color:var(--muted,#64748b);line-height:1.35}.setup-wizard-compact .setup-status-dot{width:12px;height:12px;border-radius:99px;background:#ef4444}.setup-wizard-compact .setup-compact-row.ready .setup-status-dot{background:#22c55e}.setup-wizard-compact .setup-compact-row.warn .setup-status-dot{background:#f59e0b}.setup-wizard-compact details.setup-step-details{grid-column:1/-1;margin-top:4px}.setup-wizard-compact details.setup-step-details summary{cursor:pointer;color:var(--muted,#64748b);font-size:.9rem}.setup-wizard-compact .setup-facts{margin:8px 0 0 20px;color:var(--muted,#64748b)}.setup-wizard-compact .setup-muted-note{color:var(--muted,#64748b);margin:4px 0 0}.setup-wizard-compact .setup-quick-profile textarea{min-height:88px}@media(max-width:720px){.setup-wizard-compact .setup-compact-row{grid-template-columns:auto 1fr}.setup-wizard-compact .setup-compact-row .btn{grid-column:1/-1;width:100%}.setup-wizard-compact .setup-group-head{display:block}.setup-wizard-compact .setup-group-progress{display:inline-block;margin-top:8px}}
</style>
<div class="setup-wizard-compact">
<section class="role-welcome card setup-wizard-hero">
    <div>
        <span class="eyebrow">Client readiness</span>
        <h2>First-Time Clinic Setup Wizard</h2>
        <p>This page is now grouped into short setup phases instead of one long checklist. Fix the items under <strong>Needs attention</strong>, then use the grouped sections for details.</p>
        <div class="status-actions">
            <?php if(actual_role()==='super_admin'):?>
            <a class="btn primary" href="go_live_checklist.php">Open Go-Live Checklist</a>
            <a class="btn ghost" href="system_smoke_test.php">Run QA Smoke Test</a>
            <?php else:?><a class="btn primary" href="administration.php">Return to Operations Control</a><?php endif;?>
        </div>
    </div>
    <div class="setup-progress-ring"><strong><?= e((string)$snapshot['percent']) ?>%</strong><span><?= e((string)$snapshot['complete']) ?> / <?= e((string)$snapshot['total']) ?> complete</span></div>
</section>

<section class="setup-summary-strip">
    <div class="setup-summary-tile"><span class="eyebrow">Status</span><strong><?= $missing ? 'Needs work' : 'Baseline ready' ?></strong><small><?= e((string)count($missing)) ?> item<?= count($missing) === 1 ? '' : 's' ?> remaining</small></div>
    <div class="setup-summary-tile"><span class="eyebrow">Setup progress</span><strong><?= e((string)$snapshot['percent']) ?>%</strong><small><?= e((string)$snapshot['complete']) ?> of <?= e((string)$snapshot['total']) ?> checks passed</small></div>
    <div class="setup-summary-tile"><span class="eyebrow">Next action</span><strong><?= $priorityMissing ? 'Fix top items' : 'Manual test' ?></strong><small><?= $priorityMissing ? 'Use the cards below first' : 'Proceed to role-flow testing' ?></small></div>
</section>

<?php if ($missing): ?>
<div class="alert warning"><strong>Setup still needs work.</strong> Showing the most important items first. Full detail is grouped below.</div>
<section class="card">
    <div class="card-head"><div><h2>Needs attention</h2><p>These are the first items to complete. This replaces the previous long comma-separated checklist.</p></div></div>
    <div class="setup-attention-grid">
    <?php foreach ($priorityMissing as $step): $warn = !empty($step['warn']); ?>
        <article class="setup-action-card">
            <span class="badge <?= $warn ? 'warning' : 'danger' ?>"><?= $warn ? 'Review' : 'Needed' ?></span>
            <h3><?= e((string)($step['title'] ?? 'Setup item')) ?></h3>
            <p><?= e((string)($step['description'] ?? 'Complete this setup item before go-live.')) ?></p>
            <a class="btn ghost compact" href="<?= e((string)($step['href'] ?? '#')) ?>"><?= e((string)($step['action'] ?? 'Open')) ?></a>
        </article>
    <?php endforeach; ?>
    </div>
    <?php if (count($missing) > count($priorityMissing)): ?><p class="setup-muted-note">There are <?= e((string)(count($missing) - count($priorityMissing))) ?> more item<?= (count($missing) - count($priorityMissing)) === 1 ? '' : 's' ?> under the grouped setup sections.</p><?php endif; ?>
</section>
<?php else: ?>
<div class="alert success"><strong>Setup baseline complete.</strong> Continue with QA Smoke Test and manual role-flow testing before real go-live.</div>
<?php endif; ?>

<section class="card setup-quick-profile">
    <div class="card-head"><div><h2>Quick clinic profile</h2><p>These values help the landing page, public booking, email/SMS templates, and client documentation match the installed clinic.</p></div><a class="btn ghost compact" href="settings.php">Full Website Settings</a></div>
    <form method="post" class="form-grid">
        <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
        <input type="hidden" name="action" value="save_clinic_quick_profile">
        <label>Clinic name<input name="clinic_name" value="<?= e((string)($clinic['name'] ?? '')) ?>" placeholder="Example Dental Clinic"></label>
        <label>Public email<input type="email" name="public_email" value="<?= e((string)($clinic['public_email'] ?? $clinic['email'] ?? '')) ?>" placeholder="info@exampleclinic.com"></label>
        <label>Phone / mobile<input name="phone" value="<?= e((string)($clinic['phone'] ?? '')) ?>" placeholder="0917 000 0000"></label>
        <label class="wide">Clinic address<textarea name="address" placeholder="Clinic branch address"><?= e((string)($clinic['address'] ?? '')) ?></textarea></label>
        <div class="wide"><button class="btn primary" type="submit">Save quick profile</button></div>
    </form>
</section>

<section class="setup-group-grid">
<?php foreach ($groups as $group): ?>
    <article class="card setup-group-card">
        <div class="setup-group-head">
            <div><span class="eyebrow"><?= e((string)($group['label'] ?? 'Setup group')) ?></span><h2><?= e((string)($group['title'] ?? 'Setup')) ?></h2><p><?= e((string)($group['description'] ?? 'Review related setup items.')) ?></p></div>
            <span class="badge <?= !empty($group['ready']) ? 'success' : (!empty($group['warn']) ? 'warning' : 'danger') ?> setup-group-progress"><?= e((string)($group['complete'] ?? 0)) ?> / <?= e((string)($group['total'] ?? 0)) ?></span>
        </div>
        <div class="setup-compact-list collapsed-ready">
        <?php foreach ((array)($group['steps'] ?? []) as $step): $ready = !empty($step['ready']); $warn = !$ready && !empty($step['warn']); ?>
            <div class="setup-compact-row <?= $ready ? 'ready' : ($warn ? 'warn' : 'missing') ?>">
                <span class="setup-status-dot" aria-hidden="true"></span>
                <div>
                    <strong><?= e((string)($step['title'] ?? 'Setup item')) ?></strong>
                    <small><?= e($ready ? 'Ready' : ($warn ? 'Review before go-live' : 'Required before go-live')) ?></small>
                </div>
                <a class="btn ghost compact" href="<?= e((string)($step['href'] ?? '#')) ?>"><?= e((string)($step['action'] ?? 'Open')) ?></a>
                <?php if (!empty($step['facts'])): ?>
                <details class="setup-step-details"><summary>Show details</summary><ul class="setup-facts"><?php foreach ((array)$step['facts'] as $fact): ?><li><?= e((string)$fact) ?></li><?php endforeach; ?></ul></details>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>
        </div>
        <details class="compact-details"><summary>Show completed checks / all phase details</summary><div class="compact-details-body"><p class="muted">Completed checks are hidden from the main view to keep this page short. Expand this section when auditing every setup requirement.</p></div></details>
    </article>
<?php endforeach; ?>
</section>

<section class="card setup-finish-card">
    <div class="card-head"><div><h2>Finish setup review</h2><p>Record that the Superuser/Admin reviewed the first-time setup sequence. This is an operational marker only; final go-live still requires the Go-Live Checklist and manual test flow.</p></div></div>
    <form method="post" class="inline-form">
        <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
        <input type="hidden" name="action" value="mark_setup_reviewed">
        <button class="btn primary" type="submit">Mark setup reviewed</button>
        <?php if(actual_role()==='super_admin'):?><a class="btn ghost" href="go_live_checklist.php">Continue to Go-Live Checklist</a><?php else:?><a class="btn ghost" href="administration.php">Return to Operations Control</a><?php endif;?>
    </form>
</section>
</div>
<?php render_footer();
