<?php
require __DIR__ . '/app/bootstrap.php';
require __DIR__ . '/app/layout.php';
require_auth();
if(user_needs_onboarding(current_user())) redirect('complete_registration.php');
$pageExplicit=array_key_exists('page',$_GET);
$page = preg_replace('/[^a-z_]/','',request('page','home'));
// Compatibilidade com links/notificações antigos: permissões agora ficam dentro de Clientes da Empresa.
if($page==='edit_permissions') redirect('dashboard.php?page=company_clients#edit-permissions');
$current=current_user();
ensure_subscription_charge_for_user($current);
$current=current_user();
// V2.8.54 — no primeiro acesso abre o painel especializado, mas um clique
// explícito em “Visão Geral/Início” sempre volta para a Home da plataforma.
$linkedCompanyId=resolve_company_id_for_user($current);
if(!$pageExplicit && $page==='home'){
    if(in_array((string)($current['role']??''),['company','employee'],true) && $linkedCompanyId>0){
        if(company_is_clinic($linkedCompanyId)) $page='clinic';
        elseif(company_is_car_wash($linkedCompanyId)) $page='car_wash';
        elseif(company_is_gas($linkedCompanyId)) $page='gas_admin';
    } elseif(clinic_professional_for_user((int)($current['id']??0))) {
        $page='clinic_professional';
    }
}
if (admin_profile_completion_required($current) && $page!=='profile') $page='profile';
elseif (account_restricted($current) && !in_array($page,['subscriptions','charges','terms_policies','profile'],true)) $page=user_should_see_subscriptions($current)?'subscriptions':'charges';
elseif (!account_restricted($current) && documents_access_restricted($current) && !in_array($page,['documents','terms_policies','profile'],true)) $page='documents';
$allowed = navigation_items(current_user()['role']);
$subPages=['property_agenda','quick_actions','gas_history','gas_detail','order_detail','clinic_record','company_profile','clinic_queue','clinic_queue_clients'];
if (!isset($allowed[$page]) && !in_array($page,$subPages,true)) $page='home';
if($page==='properties') mark_properties_seen((int)$current['id']);
// O brilho/ícone de uma notificação específica para uma área cessa assim que o usuário entra nela.
mark_page_notifications_seen((int)$current['id'],$page);
$file=__DIR__.'/pages/'.$page.'.php';
if(!is_file($file)) $file=__DIR__.'/pages/home.php';
render_dashboard_header(page_title($page),$page);
require $file;
render_dashboard_footer();
