<?php

declare(strict_types=1);

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

$isSuper = superuser_primary_workspace();
$showInternalQa = function_exists('dental_internal_qa_visible') ? dental_internal_qa_visible() : true;
$productionMode = function_exists('dental_production_mode') ? dental_production_mode() : false;

$sections = [
    ['title'=>'People & access','description'=>'Manage clinic users, professional profiles, patient numbering, and operational responsibility.','icon'=>'doctor','links'=>[
        ['staff.php','Staff Accounts & Roles','Invitations, work assignments, roles, and Dentist credentials','doctor'],
        ['patient_numbering.php','Patient Numbering','Control patient ID format, next number, and manual override policy','settings'],
        ['permission_matrix.php','Permission Matrix','Review role access and separation-of-duty rules','shield'],
    ]],
    ['title'=>'Clinic operations','description'=>'Configure services, resources, operating hours, clinical scheduling, and first-time clinic readiness.','icon'=>'building','links'=>[
        ['setup_wizard.php','Clinic Setup Wizard','Complete clinic profile, hours, chairs, services, staff, cashier, and portal readiness','settings'],
        ['services.php','Dental Services','Service names, duration, fees, and preparation buffers','clinical'],
        ['chairs.php','Chairs & Resources','Create chairs, bind dentists, and control maintenance','tooth'],
        ['inhouse_team.php','In-house Care Team','Assign accountable staff and shared-chair coverage by service','doctor'],
        ['operation_hours.php','Operation Hours','Branch hours, closures, and appointment intervals','clock'],
        ['doctor_schedule.php','Doctor Schedule Builder','Recurring schedules, leave, and exceptions','calendar'],
    ]],
    ['title'=>'Communication & files','description'=>'Maintain outbound communication, protected templates, reminders, and clinic uploads.','icon'=>'mail','links'=>[
        ['email_settings.php','Email & SMTP','Sender identity, queue health, diagnostics, and delivery history','mail'],
        ['email_templates.php','Email Templates','Account, appointment, reminder, follow-up, and receipt messages','message'],
        ['sms_settings.php','SMS Readiness','Provider setup, test send, templates, and outbox readiness','message'],
        ['reminders.php','Patient Reminders','Automatic appointment, follow-up, and recall reminders','clock'],
        ['uploads.php','Files & Uploads','Policies, forms, templates, and controlled references','upload'],
    ]],
];

if ($isSuper) {
    $dataLinks = [
        ['data_tools.php','Data Import & Reset','Import approved records, remove demo data, or perform protected resets','database'],
        ['backup_restore.php','Backup & Restore Center','Create, verify, download, upload, and document restore tests','backup'],
    ];
    if ($showInternalQa || !$productionMode) {
        array_splice($dataLinks, 1, 0, [[
            'demo_accounts.php','Demo Data & Orientation','Create or remove fictional role-based records for training','doctor'
        ]]);
    }
    $sections[] = ['title'=>'Data & recovery','description'=>'Protect records, import approved datasets, and recover the installation safely.','icon'=>'database','links'=>$dataLinks];

    $systemLinks = [
        ['system_setup.php','System Control Center','Owner-only health, updates, permissions, security, backups, and environment controls','settings'],
        ['production_monitoring.php','Production Monitor','Review runtime health, performance, workflow blockers, and role acceptance gates','chart'],
        ['system_setup.php?tab=environment','Environment & Deployment','Production, pilot, development, and internal QA visibility','settings'],
        ['kiosk.php','Kiosk Mode & Launchers','Generate protected workstation launchers for clinic stations','fullscreen'],
    ];
    if ($showInternalQa) {
        $systemLinks[] = ['go_live_checklist.php','Go-Live Checklist','Owner readiness gate before orientation or production use','shield'];
        $systemLinks[] = ['system_smoke_test.php','QA Smoke Test','Run role-flow, schema, release, and edit-readiness checks','shield'];
    }
    $systemLinks[] = ['installer_builder.php','Installer Builder','Create licensed full and locked demonstration packages','package'];
    $systemLinks[] = ['license.php','License Status','Review the current domain authorization','key'];
    $sections[] = ['title'=>'System & licensing','description'=>'Superuser-only environment, release, workstation, and installation authorization controls.','icon'=>'settings','links'=>$systemLinks];
}

// Never render a card that the active task view or signed-in account cannot open.
foreach ($sections as &$section) {
    $section['links'] = array_values(array_filter((array)$section['links'], static fn(array $link): bool => task_link_allowed((string)$link[0])));
}
unset($section);
$sections = array_values(array_filter($sections, static fn(array $section): bool => !empty($section['links'])));

render_header('Operations Control Center');
?>
<section class="admin-hero card">
    <div><span class="eyebrow">Operations Control Center</span><h2>Resolve clinic operations and configuration from one governed workspace.</h2><p>Clinic Administrators manage people, schedules, services, communication, and operating readiness here. Deployment, updates, backups, licensing, kiosk launchers, and release controls remain in the signed-in Superuser’s System Control area.</p><div class="status-actions"><a class="btn ghost" href="settings.php">Open Landing Page Editor</a><?php if($isSuper && task_link_allowed('system_setup.php')):?><a class="btn primary" href="system_setup.php">Open System Control</a><?php endif;?></div></div>
    <div class="admin-hero-icon"><?=dental_icon('settings')?></div>
</section>
<div class="admin-category-grid">
<?php foreach($sections as $section): ?>
<section class="admin-category card">
    <div class="admin-category-head"><span class="admin-category-icon"><?=dental_icon($section['icon'])?></span><div><h2><?=e($section['title'])?></h2><p><?=e($section['description'])?></p></div></div>
    <div class="admin-link-list">
    <?php foreach($section['links'] as [$url,$label,$description,$icon]): ?>
        <a href="<?=e($url)?>"><span class="admin-link-icon"><?=dental_icon($icon)?></span><span><strong><?=e($label)?></strong><small><?=e($description)?></small></span><span class="admin-link-arrow">→</span></a>
    <?php endforeach; ?>
    </div>
</section>
<?php endforeach; ?>
</div>
<?php render_footer();
