<?php

declare(strict_types=1);

/**
 * DentalCare 0.6.0 major stabilization helpers.
 * The helpers are deliberately UI/workflow focused and idempotent; they do not
 * create patient data or bypass role permissions.
 */

if (!function_exists('dentalcare_major_flow_roles')) {
    function dentalcare_major_flow_roles(): array
    {
        return [
            'receptionist' => [
                'title' => 'Reception / Intake lane',
                'goal' => 'One consistent intake model for booked patients, online requests, and walk-ins.',
                'steps' => ['Book appointment', 'Approve online request', 'Check in walk-in', 'Queue patient', 'Seat / hand off'],
            ],
            'dentist' => [
                'title' => 'Dentist chairside lane',
                'goal' => 'A guided clinical progression from start treatment to cashier/no-payment discharge.',
                'steps' => ['Start treatment', 'Assistant or none', 'Review vitals/alerts', 'Chart / diagnose', 'Record procedure outcome', 'Prescription decision', 'Complete visit'],
            ],
            'dental_assistant' => [
                'title' => 'Dental Assistant lane',
                'goal' => 'Direct support tasks during the assigned active encounter only.',
                'steps' => ['Prepare patient/chair', 'Record vitals', 'Upload X-ray/media', 'Document materials/support', 'Submit entries for Dentist verification', 'Chair turnover'],
            ],
            'cashier' => [
                'title' => 'Cashier POS lane',
                'goal' => 'A locked transaction terminal that follows the clinical handoff and itemized receipt.',
                'steps' => ['Open cashier window', 'Call patient', 'Review authorized charges', 'Record payment/reference', 'Print/send receipt', 'Complete or cancel transaction'],
            ],
            'clinic_admin' => [
                'title' => 'Admin / Owner lane',
                'goal' => 'Safe setup controls with no visible dead links or raw technical confusion for clients.',
                'steps' => ['Clinic profile', 'Roles/permissions', 'Schedules/chairs/services', 'Email provider setup', 'Data import/reset policy', 'Go-live QA'],
            ],
            'super_admin' => [
                'title' => 'Superuser stabilization lane',
                'goal' => 'Apply updates, validate readiness, and keep client-facing settings understandable.',
                'steps' => ['Apply updates', 'Run smoke tests', 'Review permission matrix', 'Verify email delivery', 'Confirm numbering/reset', 'Pilot sign-off'],
            ],
            'admin' => [
                'title' => 'Admin / Owner lane',
                'goal' => 'Safe setup controls with no visible dead links or raw technical confusion for clients.',
                'steps' => ['Clinic profile', 'Roles/permissions', 'Schedules/chairs/services', 'Email provider setup', 'Data import/reset policy', 'Go-live QA'],
            ],
            'front_desk' => [
                'title' => 'Reception / Intake lane',
                'goal' => 'One consistent intake model for booked patients, online requests, and walk-ins.',
                'steps' => ['Book appointment', 'Approve online request', 'Check in walk-in', 'Queue patient', 'Seat / hand off'],
            ],
        ];
    }
}

if (!function_exists('dentalcare_major_flow_role')) {
    function dentalcare_major_flow_role(?string $role = null): array
    {
        $role = $role ?: (function_exists('active_role') ? active_role() : 'clinic_admin');
        $roles = dentalcare_major_flow_roles();
        return $roles[$role] ?? $roles['clinic_admin'];
    }
}

if (!function_exists('dentalcare_render_role_lane_card')) {
    function dentalcare_render_role_lane_card(?string $role = null, string $class = ''): void
    {
        $lane = dentalcare_major_flow_role($role);
        ?>
        <details class="card major-flow-lane compact-flow-help <?= e($class) ?>" aria-label="Role workflow help">
            <summary><span><strong><?= e((string)$lane['title']) ?></strong><small><?= e((string)$lane['goal']) ?></small></span><span class="badge success">Help</span></summary>
            <ol class="major-flow-steps compact">
                <?php foreach ((array)$lane['steps'] as $index => $step): ?><li><span><?= (int)$index + 1 ?></span><strong><?= e((string)$step) ?></strong></li><?php endforeach; ?>
            </ol>
        </details>
        <?php
    }
}

if (!function_exists('dentalcare_render_reception_launchpad')) {
    function dentalcare_render_reception_launchpad(bool $canIntake = true): void
    {
        if (!$canIntake) return;
        ?>
        <section class="card reception-flow-launchpad" aria-label="Reception daily actions">
            <div class="card-head"><div><span class="eyebrow">Reception flow</span><h2>Choose the correct intake path first</h2><p>Booked appointments, online requests, and walk-ins now start from separate actions but feed one queue model.</p></div><span class="badge success">Unified intake</span></div>
            <div class="reception-flow-actions">
                <a class="flow-action-card" href="appointments.php"><strong>Book appointment</strong><span>Create or move a future visit using provider/chair availability.</span></a>
                <a class="flow-action-card" href="appointment_requests.php"><strong>Approve online request</strong><span>Review the public request and confirm the schedule fast.</span></a>
                <button class="flow-action-card button-reset" type="button" data-open="walkin-form"><strong>Check in walk-in</strong><span>No appointment is required. Search existing patient or quick-register.</span></button>
                <button class="flow-action-card button-reset" type="button" data-open="appointment-checkin"><strong>Check in appointment</strong><span>Use only for confirmed appointments scheduled today.</span></button>
            </div>
        </section>
        <?php
    }
}

if (!function_exists('dentalcare_render_clinical_sequence_card')) {
    function dentalcare_render_clinical_sequence_card(bool $canWrite, bool $isAssistant, array $encounter): void
    {
        $assistantLabel = trim((string)($encounter['assistant_name'] ?? '')) ?: 'No Dental Assistant assigned';
        ?>
        <section class="card major-clinical-sequence <?= $isAssistant ? 'assistant-mode' : 'dentist-mode' ?>" aria-label="Chairside workflow sequence">
            <div class="card-head"><div><span class="eyebrow">Chairside sequence</span><h2><?= $isAssistant ? 'Assistant support tasks' : 'Dentist treatment path' ?></h2><p><?= $isAssistant ? 'Record support work only for this assigned encounter; Dentist verification remains required.' : 'Follow this order to prevent getting lost during treatment.' ?></p></div><span class="badge"><?= e($assistantLabel) ?></span></div>
            <ol class="major-flow-steps compact">
                <?php $steps = $isAssistant
                    ? ['Prepare patient/chair','Capture vitals','Upload X-ray / media','Document materials and support','Save delegated entry','Wait for Dentist verification']
                    : ['Start treatment','Assistant or none confirmed','Review vitals and alerts','Examine / odontogram','Diagnosis','Procedure outcome','Prescription decision','Complete to Cashier or no-payment discharge'];
                foreach ($steps as $index => $step): ?><li><span><?= (int)$index + 1 ?></span><strong><?= e($step) ?></strong></li><?php endforeach; ?>
            </ol>
            <?php if ($canWrite): ?><div class="status-actions"><button class="btn primary" type="button" data-next-clinical-required>Go to next missing item <kbd>Alt+N</kbd></button><button class="btn ghost" type="button" data-open="assistant-assignment-form">Assign / change assistant</button></div><?php endif; ?>
        </section>
        <?php
    }
}

if (!function_exists('dentalcare_major_go_live_items')) {
    function dentalcare_major_go_live_items(): array
    {
        return [
            ['area'=>'Reception', 'test'=>'Book future appointment, approve online request, and check in walk-in without appointment dependency.', 'pass'=>'All three create the correct patient/queue/appointment state without page jumps.'],
            ['area'=>'Dentist', 'test'=>'Start seated patient, choose assistant or none, complete intake, odontogram, diagnosis, procedure, prescription decision, and completion.', 'pass'=>'Dentist can finish without losing place or seeing unrelated page sections first.'],
            ['area'=>'Dental Assistant', 'test'=>'Assigned assistant opens only assigned encounters, records vitals/X-ray/support notes, and Dentist verifies delegated entries.', 'pass'=>'Assistant cannot finalize Dentist-only clinical decisions.'],
            ['area'=>'Cashier', 'test'=>'Open window, lock patient transaction, collect cash/card/GCash with reference, print itemized receipt, complete queue.', 'pass'=>'No accidental navigation until transaction is cancelled or completed.'],
            ['area'=>'Email', 'test'=>'Configure Gmail API, domain SMTP, log-only mode, diagnostics, queue retry, template preview, and test delivery.', 'pass'=>'No hosting-provider-specific wording or forced cPanel/Z.com assumption.'],
            ['area'=>'Data lifecycle', 'test'=>'Create patients, verify PYYYY0001 sequence, run demo reset, clinic reset, and factory reset.', 'pass'=>'Demo reset preserves live sequence; full reset restarts next visible patient as PYYYY0001.'],
            ['area'=>'Navigation', 'test'=>'Sign in as every role and click every visible sidebar/action link.', 'pass'=>'No visible link opens access-error/blank/white screen for that role.'],
            ['area'=>'Odontogram', 'test'=>'Click teeth/surfaces repeatedly in read/write and read-only mode.', 'pass'=>'No reload, no scroll to top, selected tooth remains in view.'],
        ];
    }
}

if (!function_exists('dentalcare_render_major_go_live_table')) {
    function dentalcare_render_major_go_live_table(): void
    {
        if (function_exists('dental_client_testing_wording_hidden') && dental_client_testing_wording_hidden()) {
            return;
        }
        ?>
        <section class="card table-wrap major-go-live-table"><div class="card-head"><div><span class="eyebrow">360 stabilization checklist</span><h2>Before selling to a clinic</h2><p>This internal role-by-role QA must pass before open release.</p></div><span class="badge warning">Pilot until passed</span></div><table><thead><tr><th>Area</th><th>Required test</th><th>Pass condition</th></tr></thead><tbody><?php foreach (dentalcare_major_go_live_items() as $item): ?><tr><td><strong><?= e((string)$item['area']) ?></strong></td><td><?= e((string)$item['test']) ?></td><td><?= e((string)$item['pass']) ?></td></tr><?php endforeach; ?></tbody></table></section>
        <?php
    }
}
