<?php
require_auth();
$u=current_user();
$adminMode=is_admin() && request('self','0')!=='1';
$catalog=function_exists('navigation_catalog')?navigation_catalog():[];

if($adminMode){
    $scopes=['super_admin','sub_admin','company','clinic','employee','client','courier','motofreight','mototaxi','taxi','private_driver','service_provider','property_owner','rental_company','moving_provider','shuttle_driver'];
    if(is_role('sub_admin'))$scopes=array_values(array_filter($scopes,static fn($s)=>!in_array($s,['super_admin','sub_admin'],true)));
    $defaultScope=is_super_admin()?'super_admin':'company';
    $selectedScope=preg_replace('/[^a-z_]/','',(string)request('role',$defaultScope));
    if(!in_array($selectedScope,$scopes,true))$selectedScope=$defaultScope;
    $settingKey='quick_actions_'.$selectedScope;
    $stored=json_decode((string)setting($settingKey,''),true);if(!is_array($stored))$stored=[];
    $scopeLabel=$selectedScope==='clinic'?'Clínicas':role_label($selectedScope);
}else{
    $selectedScope='self';
    $settingKey='quick_actions_user_'.(int)$u['id'];
    $stored=json_decode((string)setting($settingKey,''),true);if(!is_array($stored)||!$stored)$stored=dashboard_quick_action_keys($u);
    $scopeLabel='Minha conta';
}

$allowedCatalog=$catalog;
if(!$adminMode){
    $allowedNav=navigation_items((string)$u['role']);
    $allowedCatalog=[];foreach($allowedNav as $key=>$item)if(!in_array($key,['home','quick_actions','cart','orders','deliveries','notifications','clinics','login_history'],true))$allowedCatalog[$key]=$item;
}elseif($selectedScope==='clinic'){
    // Clínica usa o conjunto operacional de empresa + o painel clínico.
    $clinicKeys=['clinic','clinics','companies','company_clients','company_team','catalog','orders','deliveries','marketplace_admin','finance','wallet','information','login_history','banks','company_map','rides','car_wash','shuttle','favorite_addresses','services','properties','vehicles','vehicle_store','moving','public_orgs','contacts','subscriptions','charges','notifications','support','documents','reports','profile','new_area'];
    $allowedCatalog=[];foreach($clinicKeys as $key)if(isset($catalog[$key]))$allowedCatalog[$key]=$catalog[$key];
}
?>
<section class="page-intro"><div><span class="mini-label">⚡ PERSONALIZAÇÃO</span><h2><?= $adminMode?'Ações rápidas por perfil':'Minhas ações rápidas' ?></h2><p><?= $adminMode?'Escolha até cinco atalhos para cada perfil. Clínicas possuem configuração própria, separada das empresas comuns.':'Escolha até cinco atalhos para sua barra inferior. Você também pode acessar está tela tocando duas vezes rapidamente em qualquer atalho.' ?></p></div><?php if(is_admin()&&!$adminMode):?><a class="btn btn-secondary" href="dashboard.php?page=quick_actions">Configurar perfis</a><?php endif;?></section>
<section class="panel">
  <?php if($adminMode):?>
  <form method="get" action="dashboard.php" class="filter-bar"><input type="hidden" name="page" value="quick_actions"><div class="form-group"><label>Perfil para configurar</label><select name="role" onchange="this.form.submit()"><?php foreach($scopes as $r):$label=$r==='clinic'?'🏥 Clínicas':role_icon($r).' '.role_label($r);?><option value="<?= e($r) ?>"<?= selected($selectedScope,$r) ?>><?= e($label) ?></option><?php endforeach;?></select></div></form>
  <?php else:?><div class="notice"><strong><?= e($scopeLabel) ?></strong><br>As escolhas abaixo valem somente para este usuário e substituem a configuração geral do perfil.</div><?php endif;?>

  <form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="save_quick_actions"><input type="hidden" name="return_page" value="quick_actions"><input type="hidden" name="mode" value="<?= $adminMode?'admin':'self' ?>"><?php if($adminMode):?><input type="hidden" name="role" value="<?= e($selectedScope) ?>"><?php endif;?>
    <div class="form-grid" style="margin-top:16px">
      <?php for($i=0;$i<5;$i++):$current=$stored[$i]??'';?><div class="form-group"><label>Atalho <?= $i+1 ?></label><select name="quick_actions[]"><option value="">— Não usar —</option><?php foreach($allowedCatalog as $key=>$item):if(in_array($key,['home','quick_actions'],true))continue;?><option value="<?= e($key) ?>"<?= selected($current,$key) ?>><?= e($item[0].' '.$item[1]) ?></option><?php endforeach;?></select></div><?php endfor;?>
    </div>
    <div class="notice" style="margin-top:16px">Os cinco atalhos são respeitados na ordem escolhida. Um módulo que não estiver liberado para a conta é ignorado sem substituir os outros.</div>
    <div class="form-actions"><button class="btn btn-primary">Salvar ações rápidas</button><?php if(!$adminMode):?><button class="btn btn-secondary" name="reset" value="1" type="submit">Usar padrão do perfil</button><?php endif;?></div>
  </form>
</section>
