<?php

declare(strict_types=1);

require DENTAL_ROOT . '/app/bootstrap.php';
if (!current_user()) { header('Location: login.php'); exit; }
require_roles(['super_admin']);
require_once DENTAL_ROOT . '/app/Services/DemoAccountService.php';
require DENTAL_ROOT . '/app/layout.php';

$pdo = db();
$lastResult = $_SESSION['demo_account_seed_result'] ?? null;
$lastPatientResult = $_SESSION['demo_patient_seed_result'] ?? null;
$lastFullDemoResult = $_SESSION['demo_full_clinic_seed_result'] ?? null;
unset($_SESSION['demo_account_seed_result'], $_SESSION['demo_patient_seed_result'], $_SESSION['demo_full_clinic_seed_result']);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    $action = (string)($_POST['action'] ?? '');
    try {
        if ($action === 'create_demo_accounts') {
            $resetPasswords = isset($_POST['reset_passwords']);
            $createDentistProfile = isset($_POST['create_dentist_profile']);
            $result = DemoAccountService::createOrRefresh($pdo, $resetPasswords, $createDentistProfile);
            $_SESSION['demo_account_seed_result'] = $result;
            flash('success', 'Demo accounts are ready. Created ' . (int)$result['created'] . ', updated ' . (int)$result['updated'] . ', skipped ' . (int)$result['skipped'] . '.');
            header('Location: demo_accounts.php'); exit;
        }
        if ($action === 'create_demo_patients') {
            $createWorkflowEntries = isset($_POST['create_workflow_entries']);
            $result = DemoAccountService::createOrRefreshPatients($pdo, $createWorkflowEntries);
            $_SESSION['demo_patient_seed_result'] = $result;
            flash('success', 'Demo patients are ready. Created ' . (int)$result['created'] . ', updated ' . (int)$result['updated'] . ', skipped ' . (int)$result['skipped'] . '.');
            header('Location: demo_accounts.php'); exit;
        }
        if ($action === 'create_full_demo_clinic') {
            $result = DemoAccountService::createFullDemoClinic($pdo);
            $_SESSION['demo_full_clinic_seed_result'] = $result;
            flash('success', 'Full demo clinic dataset is ready. Demo accounts, patients, clinic setup, services, chairs, inventory, sterilization, and clinical samples were refreshed.');
            header('Location: demo_accounts.php'); exit;
        }
        if ($action === 'enable_orientation_mode') {
            DemoAccountService::setOrientationMode($pdo, true);
            flash('success', 'Orientation mode is active. Real automatic email delivery is paused while clients train using demo records.');
            header('Location: demo_accounts.php'); exit;
        }
        if ($action === 'disable_orientation_mode') {
            DemoAccountService::setOrientationMode($pdo, false);
            flash('success', 'Orientation mode is disabled. Email queue behavior was restored to its previous setting when available.');
            header('Location: demo_accounts.php'); exit;
        }
        if ($action === 'deactivate_demo_accounts') {
            $count = DemoAccountService::deactivate($pdo);
            flash('success', $count . ' demo account(s) were deactivated.');
            header('Location: demo_accounts.php'); exit;
        }
        if ($action === 'reactivate_demo_accounts') {
            $count = DemoAccountService::reactivate($pdo);
            flash('success', $count . ' demo account(s) were reactivated.');
            header('Location: demo_accounts.php'); exit;
        }
        throw new RuntimeException('Unknown demo account action.');
    } catch (Throwable $exception) {
        flash('error', $exception->getMessage());
        header('Location: demo_accounts.php'); exit;
    }
}

$readiness = DemoAccountService::readiness($pdo);
$counts = DemoAccountService::counts($pdo);
$accounts = DemoAccountService::existingAccounts($pdo);
$templates = DemoAccountService::accountTemplates();
$patientTemplates = DemoAccountService::patientTemplates();
$patients = DemoAccountService::existingPatients($pdo);
$patientCreatedAt = (string) setting_get('system','demo_patients_created_at','');
$createdAt = (string) setting_get('system','demo_accounts_created_at','');
$fullDemoCreatedAt = (string) setting_get('system','full_demo_clinic_dataset_created_at','');
$orientationMode = DemoAccountService::orientationModeEnabled();

render_header('Demo Data & Orientation');
?>
<section class="admin-hero card">
    <div>
        <span class="eyebrow">Superuser settings</span>
        <h2>Demo data and orientation mode for client walkthroughs</h2>
        <p>Create fictional clinic data for sales demos, orientation, and role walkthroughs. Demo users and patients are marked with <code>is_demo=1</code>; other demo records are tracked in the demo registry and can be removed later through Data Import & Reset.</p>
        <div class="status-actions">
            <a class="btn ghost" href="data_tools.php?tab=reset">Open Demo Data Reset</a>
            <a class="btn ghost" href="setup_wizard.php">Open Setup Wizard</a>
        </div>
    </div>
    <div class="admin-hero-icon"><?= dental_icon('shield') ?></div>
</section>

<section class="stats setup-stats">
    <?php stat_card('Demo accounts', (string)$counts['total'], $counts['active'] . ' active · ' . $counts['inactive'] . ' inactive'); ?>
    <?php stat_card('Templates', (string)$counts['templates'], 'Role-based logins'); ?>
    <?php stat_card('Demo dentist profiles', (string)$counts['dentist_profiles'], 'Doctor flow readiness'); ?>
    <?php stat_card('Demo patients', (string)$counts['patients'], $counts['appointments'] . ' appointments · ' . $counts['invoices'] . ' invoices'); ?>
    <?php stat_card('Demo services', (string)($counts['services'] ?? 0), (string)($counts['inventory_items'] ?? 0) . ' inventory items · ' . (string)($counts['sterilization_records'] ?? 0) . ' sterilization records'); ?>
    <?php stat_card('Orientation mode', $orientationMode ? 'ON' : 'OFF', $orientationMode ? 'Real automatic email delivery paused' : 'Normal operation'); ?>
    <?php stat_card('Full demo data', $fullDemoCreatedAt !== '' ? date('M j, Y', strtotime($fullDemoCreatedAt)) : 'Not yet', $fullDemoCreatedAt !== '' ? date('g:i A', strtotime($fullDemoCreatedAt)) : 'Create full demo dataset'); ?>
</section>

<section class="card table-wrap">
    <div class="card-head"><div><h2>Readiness checks</h2><p>The account seeder needs the role and demo-marker schema before it can safely create logins.</p></div><span class="version-pill <?= !empty($readiness['ready']) ? '' : 'warn' ?>"><?= !empty($readiness['ready']) ? 'Ready' : 'Needs update' ?></span></div>
    <table><thead><tr><th>Check</th><th>Status</th><th>Detail</th></tr></thead><tbody>
    <?php foreach($readiness['checks'] as $check): ?>
        <tr><td><?= e($check['label']) ?></td><td><strong class="<?= !empty($check['ready']) ? 'ok' : 'warn' ?>"><?= !empty($check['ready']) ? 'Ready' : 'Needs review' ?></strong></td><td><?= e((string)$check['detail']) ?></td></tr>
    <?php endforeach; ?>
    </tbody></table>
</section>


<section class="card">
    <div class="card-head"><div><h2>Full demo clinic dataset</h2><p>Use this for sales demos and client orientation on a blank/demo copy. It creates or refreshes fictional clinic profile details, services, chairs, demo accounts, demo patients, appointment/queue/treatment/billing samples, inventory stock, sterilization records, prescriptions, recalls, and follow-up samples.</p></div><span class="badge">Recommended for demo</span></div>
    <form method="post" class="form-grid">
        <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
        <input type="hidden" name="action" value="create_full_demo_clinic">
        <div class="wide alert info"><strong>Fictional data only:</strong> This intentionally uses .local emails, sample patients, sample prices, and sample clinic records so clients can see what populated screens look like. Do not use these as real clinic records.</div>
        <div class="wide actions"><button class="btn primary" type="submit" <?= empty($readiness['ready']) ? 'disabled' : '' ?>>Create / Refresh Full Demo Clinic Dataset</button></div>
    </form>
</section>

<section class="card">
    <div class="card-head"><div><h2>Orientation mode</h2><p>Use this while training clients or staff with demo records. It adds a visible banner and pauses real automatic email delivery while the mode is active.</p></div><span class="version-pill <?= $orientationMode ? '' : 'warn' ?>"><?= $orientationMode ? 'Active' : 'Off' ?></span></div>
    <div class="alert <?= $orientationMode ? 'success' : 'warning' ?>"><strong><?= $orientationMode ? 'Orientation mode is active.' : 'Orientation mode is off.' ?></strong> <?= $orientationMode ? 'Real automatic email queue processing is paused. Use demo accounts and fictional patients for the walkthrough.' : 'Normal operation is available. Enable only on demo/training copies or before guided orientation using fictional records.' ?></div>
    <form method="post" class="inline-actions">
        <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
        <?php if ($orientationMode): ?>
            <input type="hidden" name="action" value="disable_orientation_mode"><button class="btn ghost" type="submit">Disable Orientation Mode</button>
        <?php else: ?>
            <input type="hidden" name="action" value="enable_orientation_mode"><button class="btn primary" type="submit">Enable Orientation Mode</button>
        <?php endif; ?>
        <a class="btn ghost" href="data_tools.php?tab=reset">Reset demo data later</a>
    </form>
</section>

<section class="card">
    <div class="card-head"><div><h2>Create or refresh demo accounts</h2><p>These accounts are for training and sales walkthroughs only. They should not be used for real clinic operations.</p></div></div>
    <form method="post" class="form-grid">
        <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
        <input type="hidden" name="action" value="create_demo_accounts">
        <label class="check-card wide"><input type="checkbox" name="reset_passwords" checked><span><strong>Generate new one-time passwords for demo accounts</strong><small>Each password is generated securely, shown only in the result below, and never stored in source code or audit logs. Uncheck this to retain passwords for existing demo accounts.</small></span></label>
        <label class="check-card wide"><input type="checkbox" name="create_dentist_profile" checked><span><strong>Create/refresh demo Dentist Profile and schedule</strong><small>Required so the Doctor workspace can be tested immediately.</small></span></label>
        <div class="wide alert warning"><strong>Important:</strong> This does not create a demo Superuser. Use your real Superuser account only for licensing, update, backup, and owner-level controls.</div>
        <div class="wide actions"><button class="btn primary" type="submit" <?= empty($readiness['ready']) ? 'disabled' : '' ?>>Create / Refresh Demo Accounts</button></div>
    </form>
</section>

<section class="card">
    <div class="card-head"><div><h2>Create or refresh demo patients</h2><p>Add fictional patient records and optional workflow entries so screens do not look empty during orientation.</p></div><span class="badge">Fictional data</span></div>
    <form method="post" class="form-grid">
        <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
        <input type="hidden" name="action" value="create_demo_patients">
        <label class="check-card wide"><input type="checkbox" name="create_workflow_entries" checked><span><strong>Create sample workflow entries</strong><small>Adds sample appointment, queue, public request, completed treatment, invoice, and payment records linked to the demo patients.</small></span></label>
        <div class="wide alert warning"><strong>Training use only:</strong> These records use fictional names, fictional contact details, and demo-only notes. Remove them before live clinic operation if the client will start with a clean database.</div>
        <div class="wide actions"><button class="btn primary" type="submit" <?= empty($readiness['ready']) ? 'disabled' : '' ?>>Create / Refresh Demo Patients</button></div>
    </form>
</section>

<?php if (is_array($lastFullDemoResult)): ?>
<section class="card table-wrap">
    <div class="card-head"><div><h2>Full demo clinic seed result</h2><p>Client-orientation dataset has been refreshed.</p></div><span class="badge">Fresh result</span></div>
    <?php if (!empty($lastFullDemoResult['warnings'])): ?><div class="alert warning"><strong>Warnings:</strong><ul><?php foreach((array)$lastFullDemoResult['warnings'] as $warning): ?><li><?= e((string)$warning) ?></li><?php endforeach; ?></ul></div><?php endif; ?>
    <table><thead><tr><th>Area</th><th>Result</th></tr></thead><tbody>
        <tr><td>Accounts</td><td><?= e((string)((int)($lastFullDemoResult['accounts']['created'] ?? 0) + (int)($lastFullDemoResult['accounts']['updated'] ?? 0))) ?> refreshed</td></tr>
        <tr><td>Patients</td><td><?= e((string)((int)($lastFullDemoResult['patients']['created'] ?? 0) + (int)($lastFullDemoResult['patients']['updated'] ?? 0))) ?> refreshed</td></tr>
        <tr><td>Clinic profile / hours / chairs</td><td><?= (int)$lastFullDemoResult['clinic_profile'] ?> profile · <?= (int)$lastFullDemoResult['hours'] ?> hour rules · <?= (int)$lastFullDemoResult['chairs'] ?> chair/resources</td></tr>
        <tr><td>Services and operations</td><td><?= (int)$lastFullDemoResult['services'] ?> services · <?= (int)$lastFullDemoResult['inventory_items'] ?> inventory items · <?= (int)$lastFullDemoResult['sterilization_records'] ?> sterilization records</td></tr>
        <tr><td>Clinical samples</td><td><?= (int)$lastFullDemoResult['clinical_samples'] ?> prescription/follow-up/recall/communication records</td></tr>
    </tbody></table>
    <?php $fullDemoAccounts = (array)($lastFullDemoResult['accounts']['accounts'] ?? []); ?>
    <?php if ($fullDemoAccounts): ?>
        <div class="alert info"><strong>One-time credentials:</strong> Save these now. They are not written to source files or audit logs and will not be shown again after leaving this page.</div>
        <table><thead><tr><th>Role</th><th>Name</th><th>Email</th><th>One-time password</th><th>Status</th></tr></thead><tbody>
        <?php foreach($fullDemoAccounts as $account): ?>
            <?php $password = (string)($account['password'] ?? ''); ?>
            <tr><td><?= e(ucwords(str_replace('_',' ',(string)($account['role'] ?? '')))) ?></td><td><?= e((string)($account['name'] ?? '')) ?></td><td><code><?= e((string)($account['email'] ?? '')) ?></code></td><td><?= $password !== '' ? '<code>' . e($password) . '</code>' : '<span class="muted">Existing password retained</span>' ?></td><td><?= e((string)($account['message'] ?? '')) ?></td></tr>
        <?php endforeach; ?>
        </tbody></table>
    <?php endif; ?>
</section>
<?php endif; ?>

<?php if (is_array($lastPatientResult)): ?>
<section class="card table-wrap">
    <div class="card-head"><div><h2>Demo patient seed result</h2><p>These fictional entries are ready for client walkthroughs.</p></div><span class="badge">Fresh result</span></div>
    <?php if (!empty($lastPatientResult['warnings'])): ?><div class="alert warning"><strong>Warnings:</strong><ul><?php foreach((array)$lastPatientResult['warnings'] as $warning): ?><li><?= e((string)$warning) ?></li><?php endforeach; ?></ul></div><?php endif; ?>
    <table><thead><tr><th>Patient No.</th><th>Name</th><th>Status</th></tr></thead><tbody>
    <?php foreach((array)$lastPatientResult['patients'] as $patient): ?>
        <tr><td><code><?= e((string)$patient['patient_no']) ?></code></td><td><?= e((string)$patient['name']) ?></td><td><?= e((string)$patient['message']) ?></td></tr>
    <?php endforeach; ?>
    </tbody></table>
    <p class="muted">Workflow entries created/refreshed: <?= (int)($lastPatientResult['appointments'] ?? 0) ?> appointment(s), <?= (int)($lastPatientResult['requests'] ?? 0) ?> request(s), <?= (int)($lastPatientResult['encounters'] ?? 0) ?> encounter(s), <?= (int)($lastPatientResult['invoices'] ?? 0) ?> invoice(s), <?= (int)($lastPatientResult['payments'] ?? 0) ?> payment(s).</p>
</section>
<?php endif; ?>

<?php if (is_array($lastResult)): ?>
<section class="card table-wrap">
    <div class="card-head"><div><h2>One-time demo login credentials</h2><p>Save generated passwords now. They are not stored in source code or audit logs and will not be shown again after leaving this page.</p></div><span class="badge">Fresh result</span></div>
    <?php if (!empty($lastResult['warnings'])): ?><div class="alert warning"><strong>Warnings:</strong><ul><?php foreach((array)$lastResult['warnings'] as $warning): ?><li><?= e((string)$warning) ?></li><?php endforeach; ?></ul></div><?php endif; ?>
    <table><thead><tr><th>Role</th><th>Name</th><th>Email</th><th>One-time password</th><th>Status</th></tr></thead><tbody>
    <?php foreach((array)$lastResult['accounts'] as $account): ?>
        <?php $password = (string)($account['password'] ?? ''); ?>
        <tr><td><?= e(ucwords(str_replace('_',' ',(string)$account['role']))) ?></td><td><?= e((string)$account['name']) ?></td><td><code><?= e((string)$account['email']) ?></code></td><td><?= $password !== '' ? '<code>' . e($password) . '</code>' : '<span class="muted">Existing password retained</span>' ?></td><td><?= e((string)$account['message']) ?></td></tr>
    <?php endforeach; ?>
    </tbody></table>
</section>
<?php endif; ?>

<section class="card table-wrap">
    <div class="card-head"><div><h2>Included demo role accounts</h2><p>These are the default fictional accounts that will be created or refreshed.</p></div></div>
    <table><thead><tr><th>Role</th><th>Employee No.</th><th>Name</th><th>Email</th><th>Use in demo</th></tr></thead><tbody>
    <?php foreach($templates as $template): ?>
        <tr><td><strong><?= e(ucwords(str_replace('_',' ',(string)$template['role']))) ?></strong></td><td><code><?= e((string)$template['employee_no']) ?></code></td><td><?= e((string)$template['name']) ?></td><td><code><?= e((string)$template['email']) ?></code></td><td><?= e((string)$template['description']) ?></td></tr>
    <?php endforeach; ?>
    </tbody></table>
</section>

<section class="card table-wrap">
    <div class="card-head"><div><h2>Included demo patient records</h2><p>These fictional patients show what populated patient, appointment, billing, and clinical screens will look like.</p></div></div>
    <table><thead><tr><th>Patient No.</th><th>Name</th><th>Dental safety alert</th><th>Demo use</th></tr></thead><tbody>
    <?php foreach($patientTemplates as $patientTemplate): ?>
        <tr><td><code><?= e((string)$patientTemplate['patient_no']) ?></code></td><td><?= e((string)$patientTemplate['first_name'] . ' ' . (string)$patientTemplate['last_name']) ?></td><td><?= e((string)$patientTemplate['medical_alerts']) ?></td><td><?= e((string)$patientTemplate['scenario']) ?></td></tr>
    <?php endforeach; ?>
    </tbody></table>
</section>

<section class="card table-wrap">
    <div class="card-head"><div><h2>Existing demo patients</h2><p>Patients shown here are tagged as demo or use the official demo patient-number pattern.</p></div></div>
    <table><thead><tr><th>Patient No.</th><th>Name</th><th>Birth date</th><th>Contact</th><th>Status</th><th>Created</th></tr></thead><tbody>
    <?php foreach($patients as $patient): ?>
        <tr><td><code><?= e((string)$patient['patient_no']) ?></code></td><td><?= e(trim((string)$patient['first_name'] . ' ' . (string)($patient['middle_name'] ?? '') . ' ' . (string)$patient['last_name'])) ?></td><td><?= e((string)$patient['birth_date']) ?></td><td><?= e((string)($patient['mobile'] ?: $patient['email'])) ?></td><td><span class="badge"><?= e((string)$patient['status']) ?></span></td><td><?= e(date('M j, Y', strtotime((string)$patient['created_at']))) ?></td></tr>
    <?php endforeach; ?>
    <?php if (!$patients): ?><tr><td colspan="6" class="muted">No demo patients yet.</td></tr><?php endif; ?>
    </tbody></table>
</section>

<section class="card table-wrap">
    <div class="card-head"><div><h2>Existing demo accounts</h2><p>Accounts shown here are tagged as demo or use the official demo email/employee-number pattern.</p></div></div>
    <table><thead><tr><th>Role</th><th>Name</th><th>Email</th><th>Employee No.</th><th>Status</th><th>Created</th></tr></thead><tbody>
    <?php foreach($accounts as $account): ?>
        <tr><td><?= e((string)($account['role_name'] ?? $account['role_code'])) ?></td><td><?= e((string)$account['name']) ?></td><td><code><?= e((string)$account['email']) ?></code></td><td><?= e((string)$account['employee_no']) ?></td><td><span class="badge"><?= e((string)$account['status']) ?></span></td><td><?= e(date('M j, Y', strtotime((string)$account['created_at']))) ?></td></tr>
    <?php endforeach; ?>
    <?php if (!$accounts): ?><tr><td colspan="6" class="muted">No demo accounts yet.</td></tr><?php endif; ?>
    </tbody></table>
</section>

<div class="setup-grid">
<section class="card">
    <h2>Pause demo logins</h2>
    <p>Deactivate all demo accounts without deleting their records. Use this after training, before live operation, or when a client stops testing.</p>
    <form method="post"><input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>"><input type="hidden" name="action" value="deactivate_demo_accounts"><button class="btn warning" type="submit">Deactivate Demo Accounts</button></form>
</section>
<section class="card">
    <h2>Reactivate demo logins</h2>
    <p>Re-enable demo accounts for another walkthrough. Use the create/refresh button if you also need to reset passwords.</p>
    <form method="post"><input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>"><input type="hidden" name="action" value="reactivate_demo_accounts"><button class="btn ghost" type="submit">Reactivate Demo Accounts</button></form>
</section>
</div>

<section class="card">
    <h2>Recommended demo walkthrough order</h2>
    <ol class="workflow-list">
        <li>Create/refresh <strong>Demo Accounts</strong> and <strong>Demo Patients</strong> from this page.</li>
        <li>Log in as <strong>Demo Receptionist</strong> and create or confirm an appointment using a demo patient.</li>
        <li>Move the patient to waiting/called/seated and assign a chair.</li>
        <li>Log in as <strong>Dr. Demo Santos</strong> and open the Doctor workspace.</li>
        <li>Add a treatment note/procedure and send the charge to billing.</li>
        <li>Log in as <strong>Demo Cashier</strong>, collect payment, add the digital reference if needed, and print the receipt.</li>
        <li>Log in as <strong>Demo Administrator</strong> to review reports, services, staff, and setup readiness.</li>
    </ol>
</section>
<?php render_footer();
