<?php
function navigation_catalog() {
    return [
        'home' => ['🏠','Visão Geral'],
        'autoescola' => ['🚗','Painel da Autoescola'],
        'users' => ['👥','Usuários'],
        'companies' => ['🏢','Empresas'],
        'company_clients' => ['🧑‍🤝‍🧑','Clientes da Empresa'],
        'company_team' => ['🧑‍💼','Funcionários'],
        'edit_permissions' => ['🔐','Permissões de Edição'],
        'segments' => ['🧩','Categorias e Segmentos'],
        'plans' => ['💎','Planos'],
        'subscriptions' => ['📅','Mensalidades'],
        'catalog' => ['🛍️','Produtos'],
        'qr_scanner' => ['📷','Ler QR Code'],
        'cart' => ['🛒','Meu Carrinho'],
        'orders' => ['🧾','Pedidos'],
        'services' => ['🛠️','Serviços'],
        'rides' => ['🚘','Corridas'],
        'favorite_addresses' => ['📍','Endereços Favoritos'],
        'fleet' => ['🚖','Frota e Despachos'],
        'properties' => ['🏠','Imóveis'],
        'vehicles' => ['🚗','Locadora'],
        'vehicle_store' => ['🚙','Loja de Veículos'],
        'moving' => ['🚚','Mudanças e Fretes'],
        'club' => ['🎯','Clube e Associados'],
        'car_wash' => ['🚗💦','Lava-Jato'],
        'clinic' => ['🏥','Clínica'],
        'clinic_professional' => ['🩺','Painel do Profissional'],
        'clinic_patient' => ['🧑‍⚕️','Minha Saúde'],
        'clinic_queue' => ['🎫','Fila Virtual'],
        'clinic_links' => ['🔗','Instituições Vinculadas'],
        'petcare' => ['🐾','Veterinária / Pet Shop'],
        'pet_tutor' => ['🐶','Área do Tutor'],
        'clinics' => ['🏥','Clínicas Próximas'],
        'shuttle' => ['🚐','Lotação'],
        'bus_trips' => ['🚌','Viagens — Ônibus'],
        'marketplace_admin' => ['⭐','Marketplace'],
        'gas_admin' => ['🔥','Distribuidora de Gás'],
        'gas_courier' => ['🛵','Área de Trabalho — Gás'],
        'my_gas' => ['🔥','Meu Gás'],
        'whatsapp_stats' => ['📲','Acessos WhatsApp'],
        'finance' => ['💰','Financeiro'],
        'wallet' => ['👛','Carteira'],
        'provider_clients' => ['🤝','Meus Clientes'],
        'affiliations' => ['🔗','Meus Vínculos'],
        'company_profile' => ['🏢','Perfil da Empresa'],
        'user_density' => ['📊','Usuários por Cidade'],
        'fees' => ['🧾','Taxas da Plataforma'],
        'terms_policies' => ['📜','Termos e Políticas'],
        'receipt_search' => ['🔎','Buscar Comprovante'],
        'admin_activity' => ['📈','Relatório de Administradores'],
        'new_area' => ['📱','Central de Integrações'],
        'careers' => ['💼','Currículos e Vagas'],
        'banners' => ['✨','Banners'],
        'home_content' => ['✏️','Tela Inicial'],
        'monitoring' => ['📡','Monitoramento'],
        'notifications' => ['🔔','Notificações'],
        'support' => ['💬','Suporte'],
        'settings' => ['⚙️','Configurações'],
        'backups' => ['🗄️','Backup e Restauração'],
        'banks' => ['🏦','Bancos'],
        'company_map' => ['🗺️','Mapa de Empresas'],
        'charges' => ['💳','Cobranças'],
        'contacts' => ['🪪','Meus Contatos'],
        'deliveries' => ['🛵','Entregadores e Entregas'],
        'public_orgs' => ['🏛️','Órgãos Públicos'],
        'information' => ['ℹ️','Informações'],
        'login_history' => ['🕘','Histórico de Logins'],
        'quick_actions' => ['⚡','Ações Rápidas'],
        'documents' => ['📄','Documentos'],
        'reports' => ['🚩','Denúncias'],
        'profile' => ['👤','Meu Perfil'],
        'client_profile' => ['👤','Perfil do Cliente'],
    ];
}

function navigation_items($role) {
    $all = navigation_catalog();
    $shared = ['clinic_patient','careers','clinics','new_area','wallet','information','login_history','banks','company_map','rides','car_wash','shuttle','bus_trips','favorite_addresses','services','properties','vehicles','vehicle_store','moving','public_orgs','contacts','subscriptions','charges','notifications','support','documents','reports','profile','client_profile','marketplace_admin','affiliations'];
    $map = [
        'super_admin' => array_keys($all),
        'sub_admin' => array_keys($all),
        'company' => array_values(array_unique(array_merge(['home','companies','company_clients','company_team','edit_permissions','catalog','orders','deliveries','club','marketplace_admin','finance'], $shared))),
        'client' => array_values(array_unique(array_merge(['home','clinic_patient','catalog','qr_scanner','cart','orders','services','deliveries','finance'], $shared))),
        'courier' => array_values(array_unique(array_merge(['home','company_clients','catalog','orders','deliveries','finance'], $shared))),
        'motofreight' => array_values(array_unique(array_merge(['home','company_clients','catalog','orders','deliveries','finance'], $shared))),
        'mototaxi' => array_values(array_unique(array_merge(['home','catalog','deliveries','finance'], $shared))),
        'taxi' => array_values(array_unique(array_merge(['home','finance'], $shared))),
        'private_driver' => array_values(array_unique(array_merge(['home','finance'], $shared))),
        'service_provider' => array_values(array_unique(array_merge(['home','services','provider_clients','marketplace_admin','finance'], $shared))),
        'clinic_professional' => array_values(array_unique(array_merge(['home','clinic_professional','clinic_patient','clinics','notifications','profile'], $shared))),
        'property_owner' => array_values(array_unique(array_merge(['home','finance'], $shared))),
        'rental_company' => array_values(array_unique(array_merge(['home','companies','marketplace_admin','finance'], $shared))),
        'moving_provider' => array_values(array_unique(array_merge(['home','finance'], $shared))),
        'shuttle_driver' => array_values(array_unique(array_merge(['home','shuttle','finance'], $shared))),
        'employee' => array_values(array_unique(array_merge(['home','company_clients','company_team','edit_permissions','catalog','orders','deliveries','club'], $shared))),
    ];
    $keys = isset($map[$role]) ? $map[$role] : ['home','profile'];
    $current = current_user();
    $companyType = (string)($current['company_type'] ?? '');
    $linkedCompanyId = resolve_company_id_for_user($current);
    $isClinicCompany = $linkedCompanyId > 0 && company_is_clinic($linkedCompanyId);
    $isClinicOwner = $isClinicCompany && clinic_company_owner_user_id($linkedCompanyId)===(int)($current['id']??0);
    $isCarWashCompany = $linkedCompanyId > 0 && company_is_car_wash($linkedCompanyId);
    $transportKind = user_transport_company_kind($current);

    // Todo perfil ativo também pode usar a plataforma como consumidor. Os painéis
    // administrativos continuam condicionados ao papel e ao segmento da conta.
    if (!in_array($role,['super_admin','sub_admin'],true)) {
        $keys=array_values(array_unique(array_merge($keys,['catalog','qr_scanner','cart','orders','vehicles','vehicle_store','my_gas','affiliations'])));
    }

    if (!user_can_access_club()) $keys = array_values(array_filter($keys, static fn($key) => $key !== 'club'));
    if (!in_array($role,['super_admin','sub_admin','company','employee','courier','motofreight','mototaxi','client'],true)) {
        $keys = array_values(array_filter($keys, static fn($key) => $key !== 'deliveries'));
    }
    // Locadora e loja de veículos possuem modo de vitrine para qualquer usuário;
    // somente empresas do segmento recebem os controles de gestão dentro da página.
    if (!in_array($role,['super_admin','sub_admin'],true) && $role !== 'moving_provider' && !($role === 'company' && $companyType === 'moving') && !company_has_visible_module('moving')) {
        $keys = array_values(array_filter($keys, static fn($key) => $key !== 'moving'));
    }
    if ($role === 'company' && in_array($transportKind,['taxi','mototaxi'],true)) {
        $keys[] = 'fleet';
        $keys[] = 'rides';
    }
    if ($role === 'employee' && in_array($transportKind,['taxi','mototaxi'],true)) {
        $keys[] = 'fleet';
        $keys[] = 'rides';
    }
    if ($role === 'mototaxi' && user_can_work_deliveries($current)) $keys[] = 'orders';
    if ($role === 'company' && $isCarWashCompany) $keys[] = 'car_wash';
    if ($role === 'employee' && $isCarWashCompany) $keys[] = 'car_wash';
    $isGasCompany = $linkedCompanyId > 0 && company_is_gas($linkedCompanyId);
    if (in_array($role,['company','employee'],true) && $isGasCompany) $keys[] = 'gas_admin';
    if (user_can_work_deliveries($current) && user_is_gas_courier($current)) $keys[] = 'gas_courier';
    if (!in_array($role,['super_admin','sub_admin'],true)) $keys[] = 'my_gas';
    if (in_array($role,['super_admin','sub_admin'],true)) $keys[] = 'whatsapp_stats';
    if ($role === 'company' && $isClinicOwner) $keys[] = 'clinic';
    if ($isClinicCompany || clinic_professional_memberships((int)($current['id']??0),true)) $keys[] = 'clinic_queue';
    if (clinic_professional_memberships((int)($current['id']??0),true)) $keys[] = 'clinic_professional';
    if ($role === 'client') $keys[] = 'clinic_patient';
    if (clinic_professional_memberships((int)($current['id']??0),true) || clinic_patient_memberships((int)($current['id']??0))) $keys[] = 'clinic_links';
    if (in_array($role,['company','employee'],true) && $linkedCompanyId>0 && company_is_petcare($linkedCompanyId)) $keys[] = 'petcare';
    if ($role==='client') $keys[] = 'pet_tutor';
    if ($role === 'company' && $companyType === 'shuttle') $keys[] = 'shuttle';
    if ($role === 'employee' && $companyType === 'shuttle') $keys[] = 'shuttle';
    if (!in_array($role,['super_admin','sub_admin','company','employee'],true)) $keys = array_values(array_filter($keys, static fn($key) => !in_array($key,['company_team','edit_permissions'],true)));
    if(in_array($role,['courier','motofreight'],true)&&!courier_linked_companies((int)($current['id']??0)))$keys=array_values(array_filter($keys,static fn($key)=>$key!=='company_clients'));
    if(!in_array($role,['super_admin','sub_admin','company','employee','courier','motofreight'],true))$keys=array_values(array_filter($keys,static fn($key)=>$key!=='company_clients'));
    if (!in_array($role,['super_admin','sub_admin'],true)) $keys = array_values(array_filter($keys, static fn($key) => $key !== 'segments'));
    if (!in_array($role,['super_admin','sub_admin'],true) && !user_has_bank_access($current)) $keys = array_values(array_filter($keys, static fn($key) => $key !== 'banks'));

    if (!is_admin() && !wallet_enabled_for_user($current)) $keys = array_values(array_filter($keys, static fn($key) => $key !== 'wallet'));
    if (!is_admin() && !user_should_see_subscriptions($current)) $keys = array_values(array_filter($keys, static fn($key) => $key !== 'subscriptions'));
    if (($role ?? '') !== 'service_provider' || !provider_clients_enabled_for_user($current)) $keys = array_values(array_filter($keys, static fn($key) => $key !== 'provider_clients'));
    if (!is_admin()) $keys = array_values(array_filter($keys, static fn($key) => !in_array($key,['user_density','fees','admin_activity'],true)));
    if (($role ?? '') === 'sub_admin') $keys = array_values(array_filter($keys, static fn($key) => $key !== 'admin_activity'));
    if (($role ?? '') !== 'super_admin') $keys = array_values(array_filter($keys, static fn($key) => $key !== 'home_content'));
    if (($role ?? '') === 'sub_admin') $keys = array_values(array_filter($keys, static fn($key) => $key !== 'petcare'));
    // Terceira etapa: Sub Admin só enxerga módulos financeiros/sensíveis liberados pelo Administrador Sênior.
    if ($role === 'sub_admin') {
        $sensitive=subadmin_sensitive_modules();
        $keys=array_values(array_filter($keys, static function($key) use($current,$sensitive){ return !in_array($key,$sensitive,true) || subadmin_has_module_access($current,$key); }));
        $keys=array_values(array_filter($keys, static fn($key) => !in_array($key,['clinic','gas_admin','my_gas'],true)));
    }
    // Administrador Sênior só entra no painel interno de uma clínica enquanto existir denúncia clínica em análise.
    if ($role === 'super_admin' && !clinic_super_admin_has_any_report_access()) $keys=array_values(array_filter($keys, static fn($key) => $key !== 'clinic'));
    if (!is_admin() && user_new_area_enabled($current)) $keys[] = 'new_area';
    if (!is_admin() && !user_new_area_enabled($current)) $keys = array_values(array_filter($keys, static fn($key) => $key !== 'new_area'));
    // Permissões de edição agora ficam dentro de Clientes da Empresa.
    $keys = array_values(array_filter($keys, static fn($key) => $key !== 'edit_permissions'));

    // V2.8.53 — clínica mantém seu painel próprio, mas também conserva os módulos
    // gerais da plataforma (corridas, serviços, imóveis, lava-jato, lotação etc.).
    // A chave `clinic` já foi adicionada acima quando a empresa é clínica.

    $keys = array_values(array_unique($keys));
    $out = [];
    foreach ($keys as $key) if(isset($all[$key])) $out[$key] = $all[$key];
    return $out;
}


function dashboard_attention_counts(array $user): array {
    $userId=(int)$user['id'];
    $q=db()->prepare('SELECT COUNT(*) FROM notifications WHERE (user_id=? OR user_id IS NULL) AND read_at IS NULL');
    $q->execute([$userId]);
    $notifications=(int)$q->fetchColumn();

    if (in_array(($user['role'] ?? ''), ['super_admin','sub_admin'], true)) {
        $charges=(int)db()->query("SELECT COUNT(*) FROM charges WHERE status IN ('pending','overdue','proof_sent','rejected')")->fetchColumn();
    } else {
        $q=db()->prepare("SELECT COUNT(*) FROM charges WHERE ((user_id=? AND status IN ('pending','overdue','rejected')) OR (issuer_user_id=? AND status='proof_sent'))");
        $q->execute([$userId,$userId]);
        $charges=(int)$q->fetchColumn();
    }

    $lastSeen=(int)user_ui_state($userId,'information_last_log_id','0');
    if (($user['role'] ?? '') === 'super_admin') {
        $q=db()->prepare("SELECT COUNT(*) FROM activity_logs WHERE id>? AND action<>'login'");
        $q->execute([$lastSeen]);
    } elseif (($user['role'] ?? '') === 'sub_admin') {
        $q=db()->prepare("SELECT COUNT(*) FROM activity_logs l LEFT JOIN users u ON u.id=l.user_id WHERE l.id>? AND l.action<>'login' AND (u.role IS NULL OR u.role NOT IN ('super_admin','sub_admin'))");
        $q->execute([$lastSeen]);
    } else {
        $q=db()->prepare("SELECT COUNT(*) FROM activity_logs WHERE id>? AND user_id=? AND action<>'login'");
        $q->execute([$lastSeen,$userId]);
    }
    $information=(int)$q->fetchColumn();
    $documents=pending_required_documents_count($user,false);
    $result=['notifications'=>$notifications,'charges'=>$charges,'information'=>$information,'documents'=>$documents];
    if(in_array((string)($user['role']??''),['company','employee'],true)){
        $companyId=resolve_company_id_for_user($user);
        if($companyId>0){
            try{
                $q=db()->prepare("SELECT COUNT(*) FROM orders WHERE company_id=? AND status NOT IN ('delivered','cancelled')");
                $q->execute([$companyId]);$result['orders']=(int)$q->fetchColumn();
                $q=db()->prepare("SELECT COUNT(*) FROM delivery_jobs WHERE company_id=? AND status NOT IN ('delivered','cancelled','rejected')");
                $q->execute([$companyId]);$result['deliveries']=(int)$q->fetchColumn();
            }catch(Throwable $ignored){}
        }
    }
    foreach(unread_notification_page_counts($userId) as $targetPage=>$count){
        if($targetPage==='notifications')continue;
        $result[$targetPage]=($result[$targetPage]??0)+(int)$count;
    }
    return $result;
}

function dashboard_quick_action_keys(array $user): array {
    $role=(string)($user['role'] ?? 'client');
    $companyId=resolve_company_id_for_user($user);
    $isClinic=$companyId>0 && company_is_clinic($companyId);
    $defaults=[
        'super_admin'=>['users','companies','information','notifications','charges'],
        'sub_admin'=>['users','companies','information','notifications','charges'],
        'company'=>['company_clients','catalog','orders','deliveries','charges'],
        'clinic'=>['clinic','clinic_queue','clinics','services','rides','notifications'],
        'clinic_professional'=>['clinic_professional','clinic_queue','clinic_patient','clinics','notifications','profile'],
        'employee'=>['company_clients','orders','deliveries','notifications','profile'],
        'client'=>['pet_tutor','clinic_patient','rides','favorite_addresses','notifications'],
        'courier'=>['deliveries','finance','charges','notifications','profile'],
        'motofreight'=>['deliveries','moving','finance','notifications','profile'],
        'mototaxi'=>['rides','deliveries','finance','notifications','profile'],
        'taxi'=>['rides','finance','charges','notifications','profile'],
        'private_driver'=>['rides','finance','charges','notifications','profile'],
        'service_provider'=>['services','finance','charges','notifications','profile'],
        'property_owner'=>['properties','finance','charges','notifications','profile'],
        'rental_company'=>['vehicles','finance','charges','notifications','profile'],
        'moving_provider'=>['moving','finance','charges','notifications','profile'],
        'shuttle_driver'=>['shuttle','finance','charges','notifications','profile'],
    ];
    $scope=$isClinic?'clinic':$role;
    $userStored=json_decode((string)setting('quick_actions_user_'.(int)($user['id']??0),''),true);
    $scopeStored=json_decode((string)setting('quick_actions_'.$scope,''),true);
    $hasUserCustom=is_array($userStored)&&count($userStored)>0;
    $hasScopeCustom=is_array($scopeStored)&&count($scopeStored)>0;
    if($hasUserCustom)$keys=$userStored;
    elseif($hasScopeCustom)$keys=$scopeStored;
    else $keys=$defaults[$scope]??($defaults[$role]??['information','notifications','charges','profile']);

    $allowed=navigation_items($role);
    // Só força atalhos especiais quando ninguém personalizou a barra. Assim nenhum
    // dos cinco atalhos escolhidos "some" ao liberar Clínica ou Central de Integrações.
    if(!$hasUserCustom&&!$hasScopeCustom){
        if($isClinic&&isset($allowed['clinic']))$keys=array_values(array_unique(array_merge(['clinic'],$keys)));
        if(isset($allowed['gas_courier'])&&user_is_gas_courier($user))$keys=array_values(array_unique(array_merge(['gas_courier'],$keys)));
        if(user_new_area_enabled($user)&&isset($allowed['new_area']))$keys=array_values(array_unique(array_merge(['new_area'],$keys)));
    }
    $result=[];
    foreach($keys as $key){
        $key=preg_replace('/[^a-z_]/','',(string)$key);
        $hiddenQuick=['cart','notifications','clinics','login_history','quick_actions','qr_scanner'];
        if($key!==''&&$key!=='home'&&!in_array($key,$hiddenQuick,true)&&isset($allowed[$key])&&!in_array($key,$result,true))$result[]=$key;
        if(count($result)>=5)break;
    }
    if(!$result){
        foreach($allowed as $key=>$item){if($key==='home'||in_array($key,['cart','notifications','clinics','login_history','quick_actions','qr_scanner'],true))continue;$result[]=$key;if(count($result)>=5)break;}
    }
    return $result;
}

function render_brand_link(string $href, string $subtitle = '', string $extraClass = ''): void {
    $brandName=platform_name();$brandLogo=platform_logo_url();
    ?>
    <a class="brand brand-rich <?= e($extraClass) ?>" href="<?= e($href) ?>">
        <img class="brand-wordmark dynamic-brand-logo" src="<?= e($brandLogo) ?>" alt="<?= e($brandName) ?>">
        <span class="dynamic-brand-name"><?= e($brandName) ?></span>
        <?php if ($subtitle !== ''): ?><span class="brand-subtitle"><?= e($subtitle) ?></span><?php endif; ?>
    </a>
    <?php
}

function render_public_header($title = '') {
    $fullTitle = $title ? $title . ' • ' . platform_name() : platform_name();
    $publicApk = platform_apk_info();
    ?>
<!doctype html>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<meta name="theme-color" content="#17182a">
<title><?= e($fullTitle) ?></title>
<meta name="description" content="<?= e(platform_name()) ?>: plataforma multissserviços para delivery, mobilidade, serviços, imóveis e locação.">
<link rel="manifest" href="<?= e(url('manifest.php')) ?>">
<link rel="icon" href="<?= e(platform_logo_url()) ?>">
<link rel="stylesheet" href="<?= e(url('assets/app.css')) ?>?v=2.9.20">
<style>:root{--primary:<?= e(setting('primary_color','#6d6fff')) ?>;--accent:<?= e(setting('secondary_color','#00d4a6')) ?>}</style>
</head>
<body class="public-body">
<div class="ambient ambient-one"></div><div class="ambient ambient-two"></div>
<header class="public-header">
    <?php render_brand_link(url('index.php'), 'Conectando negócios e mobilidade'); ?>
    <button class="mobile-menu" type="button" data-public-menu>☰</button>
    <nav class="public-nav" data-public-nav>
        <?php if (current_user()): ?><a href="<?= e(url('marketplace.php')) ?>">Marketplace</a><?php endif; ?>
        <a href="<?= e(url('index.php#servicos')) ?>">Serviços</a>
        <a href="<?= e(url('index.php#como-funciona')) ?>">Como funciona</a>
        <a href="<?= e(url('index.php#planos')) ?>">Planos</a>
        <a href="<?= e(url('terms.php')) ?>">Termos e políticas</a>
        <?php if($publicApk):?><a href="<?= e(url('index.php#baixar-aplicativo')) ?>">Baixar app</a><?php endif;?>
        <button class="pwa-install-trigger pwa-install-nav" type="button" data-pwa-install hidden title="Instalar aplicativo">📲 <span>Instalar</span></button>
        <?php if (current_user()): ?><a class="btn btn-primary btn-sm" href="<?= e(url('dashboard.php')) ?>">Acessar Conta</a><?php else: ?>
        <a href="<?= e(url('login.php')) ?>">Entrar</a><a class="btn btn-primary btn-sm" href="<?= e(url('register.php')) ?>">Criar conta</a><?php endif; ?>
    </nav>
</header>
<main>
<?php foreach (pull_flashes() as $flash): ?><div class="public-flash alert alert-<?= e($flash['type']) ?>" data-alert><?= e($flash['message']) ?><button type="button">×</button></div><?php endforeach; ?>
<?php
}

function render_public_footer() {
    ?>
</main>
<footer class="public-footer">
    <div><?php render_brand_link(url('index.php'), 'Ecossistema completo para sua cidade'); ?></div>
    <div><strong>Contato</strong><a href="mailto:<?= e(setting('support_email','suporte@linkexpress.local')) ?>"><?= e(setting('support_email','suporte@linkexpress.local')) ?></a><a href="<?= e(whatsapp_url(setting('whatsapp','5571999999999'),'',0,0,'platform_support')) ?>" target="_blank" rel="noopener">WhatsApp</a></div>
    <div><strong>Plataforma</strong><?php if(current_user()):?><a href="<?= e(url('marketplace.php')) ?>">Marketplace</a><?php endif;?><a href="<?= e(url('terms.php')) ?>">Termos e políticas</a><a href="<?= e(url('login.php')) ?>">Entrar</a><a href="<?= e(url('register.php')) ?>">Cadastrar</a></div>
    <p class="footer-copy">© <?= date('Y') ?> <?= e(platform_name()) ?>. Todos os direitos reservados.</p>
</footer>
<script src="<?= e(url('assets/app.js')) ?>?v=2.9.12"></script>
<script src="<?= e(url('assets/map-tools.js')) ?>?v=2.9.12"></script>
</body></html>
<?php
}

function render_dashboard_header($title, $page) {
    $user = current_user();
    track_admin_presence($user);
    if (admin_profile_completion_required($user)) $nav=['profile'=>['👤','Completar Perfil']];
    elseif (account_restricted($user)) $nav=['charges'=>['💳','Cobranças'],'profile'=>['👤','Perfil']];
    elseif (documents_access_restricted($user)) $nav=['documents'=>['📄','Documentos'],'profile'=>['👤','Perfil']];
    else $nav=navigation_items($user['role']);
    $unreadStmt = db()->prepare('SELECT COUNT(*) FROM notifications WHERE (user_id=? OR user_id IS NULL) AND read_at IS NULL');
    $unreadStmt->execute([$user['id']]);
    $unread = (int)$unreadStmt->fetchColumn();
    $attention = dashboard_attention_counts($user);
    $carWashLive = isset($nav['car_wash']) && car_wash_has_open_availability(7);
    $propertyAttention = isset($nav['properties']) ? property_attention_kind($user) : '';
    ?>
<!doctype html>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<meta name="theme-color" content="#111221">
<title><?= e($title) ?> • <?= e(platform_name()) ?></title>
<link rel="manifest" href="<?= e(url('manifest.php')) ?>">
<link rel="icon" href="<?= e(platform_logo_url()) ?>">
<link rel="stylesheet" href="<?= e(url('assets/app.css')) ?>?v=2.9.20">
<style>:root{--primary:<?= e(setting('primary_color','#6d6fff')) ?>;--accent:<?= e(setting('secondary_color','#00d4a6')) ?>}</style>
</head>
<body class="dashboard-body">
<div class="app-shell">
<aside class="sidebar" data-sidebar>
    <?php render_brand_link(url('dashboard.php?page=home'), role_label($user['role']), 'sidebar-brand'); ?>
    <div class="user-mini">
        <?= avatar_html($user) ?>
        <div><strong><?= e($user['name']) ?></strong><small><?= e($user['company_name'] ?: role_label($user['role'])) ?></small></div>
    </div>
    <nav class="side-nav">
        <?php $sidebarHidden=['cart','notifications','clinics','login_history','quick_actions','qr_scanner','client_profile','company_profile']; ?>
        <?php foreach ($nav as $key => $item): if(in_array($key,$sidebarHidden,true)) continue; ?>
        <?php $attentionCount=(int)($attention[$key]??0); ?>
        <a class="<?= $page === $key ? 'active' : '' ?><?= $attentionCount>0?' attention-bounce':'' ?><?= ($key==='car_wash'&&$carWashLive)?' car-wash-live':'' ?><?= ($key==='properties'&&$propertyAttention)?(' property-live property-live-'.$propertyAttention):'' ?><?= $key==='new_area'?' new-area-pulse':'' ?>" href="<?= e(url('dashboard.php?page=' . $key)) ?>"><span><?= $item[0] ?></span><?= e($item[1]) ?><?php if ($key === 'notifications' && $unread): ?><b><?= $unread ?></b><?php elseif($key === 'cart' && cart_count((int)$user['id'])):?><b><?= cart_count((int)$user['id']) ?></b><?php elseif($attentionCount>0):?><b><?= $attentionCount ?></b><?php endif; ?></a>
        <?php endforeach; ?>
    </nav>
    <div class="sidebar-footer"><a href="<?= e(url('logout.php')) ?>">↪ Sair</a></div>
</aside>
<div class="workspace">
<header class="topbar">
    <button class="icon-btn desktop-mobile-menu-trigger" type="button" data-sidebar-toggle aria-label="Acessar Menu">☰</button><?php if($page!=='home'):?><a class="icon-btn mobile-dashboard-home" href="<?= e(url('dashboard.php?page=home')) ?>" aria-label="Voltar à Dashboard" title="Dashboard">⌂</a><?php endif;?>
    <div><small><?= e(platform_name()) ?></small><h1><?= e($title) ?></h1></div>
    <div class="top-actions">
        <button class="icon-btn pwa-install-trigger" type="button" data-pwa-install hidden title="Instalar aplicativo" aria-label="Instalar aplicativo">📲</button>
        <button class="icon-btn" type="button" data-theme-toggle title="Alternar tema">◐</button>
        <a class="icon-btn notification-button<?= $unread>0?' attention-bounce':'' ?>" href="<?= e(url('dashboard.php?page=notifications')) ?>">🔔<?php if ($unread): ?><span><?= $unread ?></span><?php endif; ?></a>
        <div class="online-pill"><i></i><?= e(status_label($user['work_status'])) ?></div>
    </div>
</header>
<main class="content">
<?php foreach (pull_flashes() as $flash): ?><div class="alert alert-<?= e($flash['type']) ?>" data-alert><?= e($flash['message']) ?><button type="button">×</button></div><?php endforeach; ?>
<?php
}

function render_global_mobile_quick_actions(string $page = ''): void {
    $user=current_user();
    if(!$user) return;
    if(admin_profile_completion_required($user)) $nav=['profile'=>['👤','Completar Perfil']];
    elseif(account_restricted($user)) $nav=['charges'=>['💳','Cobranças'],'profile'=>['👤','Perfil']];
    elseif(documents_access_restricted($user)) $nav=['documents'=>['📄','Documentos'],'profile'=>['👤','Perfil']];
    else $nav=navigation_items((string)$user['role']);
    $attention=dashboard_attention_counts($user);
    $cartCount=cart_count((int)$user['id']);
    $keys=dashboard_quick_action_keys($user);
    $carWashLive = isset($nav['car_wash']) && car_wash_has_open_availability(7);
    $propertyAttention = isset($nav['properties']) ? property_attention_kind($user) : '';
    $visible=[];$relocated=['cart','notifications','clinics','login_history','quick_actions'];
    foreach($keys as $key){
        if(isset($nav[$key])&&!in_array($key,$relocated,true)) $visible[]=$key;
        if(count($visible)>=5) break;
    }
    if(!$visible){
        foreach($nav as $key=>$item){
            if($key==='home'||in_array($key,$relocated,true)) continue;
            $visible[]=$key;
            if(count($visible)>=5) break;
        }
    }
    if(!$visible) return;
    ?>
    <nav class="mobile-floating-actions global-mobile-floating-actions" aria-label="Ações rápidas">
      <div class="quick-actions quick-actions-dock">
        <?php foreach($visible as $key): $item=$nav[$key]; $count=(int)($attention[$key]??0); if($key==='cart')$count=$cartCount; ?>
          <a class="quick-action<?= $count>0?' attention-bounce':'' ?><?= $page===$key?' active':'' ?><?= ($key==='car_wash'&&$carWashLive)?' car-wash-live':'' ?><?= ($key==='properties'&&$propertyAttention)?(' property-live property-live-'.$propertyAttention):'' ?><?= $key==='new_area'?' new-area-pulse':'' ?>" href="<?= e(url('dashboard.php?page='.$key)) ?>" data-quick-edit-url="<?= e(url('dashboard.php?page=quick_actions&self=1')) ?>" aria-label="<?= e($item[1]) ?>" title="Toque duas vezes rapidamente para editar este atalho">
            <span><?= $item[0] ?></span><b><?= e($item[1]) ?></b><?php if($count>0):?><em><?= $count ?></em><?php endif;?>
          </a>
        <?php endforeach;?>
      </div>
    </nav>
    <?php
}

function render_dashboard_footer() {
    ?>
</main>
<?php render_global_mobile_quick_actions(preg_replace('/[^a-z_]/','',(string)request('page','home'))); ?>
<footer class="dashboard-footer"><span><?= e(platform_name()) ?> <?= date('Y') ?></span><span>PHP + SQLite • PWA responsiva</span></footer>
</div></div>
<div class="sidebar-overlay" data-sidebar-overlay></div>
<script src="<?= e(url('assets/app.js')) ?>?v=2.9.12"></script>
<script src="<?= e(url('assets/map-tools.js')) ?>?v=2.9.12"></script>
</body></html>
<?php
}

function page_title($page) {
    if($page==='property_agenda') return 'Agenda de Piscina';
    if($page==='quick_actions') return 'Ações Rápidas';
    if($page==='gas_history') return 'Histórico de Vendas de Gás';
    if($page==='gas_detail') return 'Detalhes da Distribuidora de Gás';
    if($page==='gas_courier') return 'Área de Trabalho — Entregador de Gás';
    $nav = navigation_items(current_user()['role']);
    return isset($nav[$page]) ? $nav[$page][1] : 'Painel';
}
