<?php
$u=current_user();$role=$u['role'];
$manualSql=is_super_admin()?'SELECT * FROM manual_items ORDER BY sort_order,id DESC':"SELECT * FROM manual_items WHERE status='active' ORDER BY sort_order,id DESC";
$manualItems=[];try{$manualItems=db()->query($manualSql)->fetchAll();}catch(Throwable $ignored){}
$apkInfo=platform_apk_info();
if(in_array($role,['super_admin','sub_admin'],true)){
  $adminUserWhere=$role==='sub_admin'?" WHERE role NOT IN ('super_admin','sub_admin')":'';
  $pendingWhere=$role==='sub_admin'?" WHERE status='pending' AND role NOT IN ('super_admin','sub_admin')":" WHERE status='pending'";
  $metrics=[
    ['Usuários',(int)db()->query('SELECT COUNT(*) FROM users'.$adminUserWhere)->fetchColumn(),'👥',$role==='sub_admin'?'Cadastros não administrativos':'Cadastros totais','users'],
    ['Empresas',(int)db()->query('SELECT COUNT(*) FROM companies')->fetchColumn(),'🏢','Negócios cadastrados','companies'],
    ['Pendentes',(int)db()->query('SELECT COUNT(*) FROM users'.$pendingWhere)->fetchColumn(),'⏳','Aguardando aprovação','users'],
    ['Recebido no mês',(float)db()->query("SELECT COALESCE(SUM(amount),0) FROM payments WHERE status='paid' AND substr(COALESCE(paid_at,created_at),1,7)=strftime('%Y-%m','now')")->fetchColumn(),'💰','Pagamentos confirmados','finance']
  ];
}elseif($role==='company'||$role==='employee'){
  $cid=resolve_company_id_for_user($u);
  $s=db()->prepare('SELECT COUNT(*) FROM products WHERE company_id=? AND deleted_at IS NULL');$s->execute([$cid]);$products=(int)$s->fetchColumn();
  $s=db()->prepare('SELECT COUNT(*) FROM orders WHERE company_id=?');$s->execute([$cid]);$orders=(int)$s->fetchColumn();
  $s=db()->prepare("SELECT COUNT(*) FROM orders WHERE company_id=? AND status NOT IN ('delivered','cancelled')");$s->execute([$cid]);$open=(int)$s->fetchColumn();
  $s=db()->prepare("SELECT COALESCE(SUM(total),0) FROM orders WHERE company_id=? AND status='delivered'");$s->execute([$cid]);$revenue=(float)$s->fetchColumn();
  $metrics=[['Produtos',$products,'🛍️','Itens no catálogo','catalog'],['Pedidos',$orders,'🧾','Pedidos recebidos','orders'],['Em andamento',$open,'⏳','Exigem atenção','orders'],['Faturamento',$revenue,'💰','Pedidos entregues','finance']];
}elseif($role==='client'){
  $s=db()->prepare('SELECT COUNT(*) FROM orders WHERE client_id=?');$s->execute([$u['id']]);$orders=(int)$s->fetchColumn();
  $s=db()->prepare('SELECT COUNT(*) FROM rides WHERE client_id=?');$s->execute([$u['id']]);$rides=(int)$s->fetchColumn();
  $s=db()->prepare('SELECT COUNT(*) FROM service_requests WHERE client_id=?');$s->execute([$u['id']]);$services=(int)$s->fetchColumn();
  $s=db()->prepare('SELECT COALESCE(SUM(amount),0) FROM payments WHERE payer_user_id=?');$s->execute([$u['id']]);$spent=(float)$s->fetchColumn();
  $metrics=[['Pedidos',$orders,'🛍️','Compras realizadas','orders'],['Corridas',$rides,'🚘','Solicitações de transporte','rides'],['Serviços',$services,'🛠️','Atendimentos solicitados','services'],['Pagamentos',$spent,'💳','Registros financeiros','finance']];
}elseif(in_array($role,['courier','motofreight'],true)){
  if(user_is_gas_courier($u)){
    $gasCompanies=gas_courier_company_ids((int)$u['id']);
    $qMarks=implode(',',array_fill(0,count($gasCompanies),'?'));
    $s=db()->prepare("SELECT COUNT(*) FROM delivery_jobs WHERE assigned_courier_id=? AND company_id IN ($qMarks) AND status NOT IN ('delivered','cancelled','rejected')");$s->execute(array_merge([(int)$u['id']],$gasCompanies));$active=(int)$s->fetchColumn();
    $s=db()->prepare("SELECT COUNT(*) FROM delivery_jobs WHERE assigned_courier_id=? AND company_id IN ($qMarks) AND status='delivered'");$s->execute(array_merge([(int)$u['id']],$gasCompanies));$done=(int)$s->fetchColumn();
    $q=db()->prepare('SELECT COUNT(*) FROM notifications WHERE user_id=? AND read_at IS NULL');$q->execute([(int)$u['id']]);$unread=(int)$q->fetchColumn();
    $metrics=[['Empresas de gás',count($gasCompanies),'🔥','Vínculos ativos','gas_courier'],['Entregas ativas',$active,'🛵','Ordens em andamento','gas_courier'],['Concluídas',$done,'✅','Histórico de entregas de gás','gas_courier'],['Notificações',$unread,'🔔','Avisos não lidos','notifications']];
  }else{
    $s=db()->prepare('SELECT COUNT(*) FROM orders WHERE delivery_user_id=?');$s->execute([$u['id']]);$done=(int)$s->fetchColumn();
    $s=db()->prepare("SELECT COUNT(*) FROM orders WHERE delivery_user_id=? AND status='on_route'");$s->execute([$u['id']]);$active=(int)$s->fetchColumn();
    $s=db()->prepare("SELECT COALESCE(SUM(delivery_fee),0) FROM orders WHERE delivery_user_id=? AND status='delivered'");$s->execute([$u['id']]);$earn=(float)$s->fetchColumn();
    $available=(int)db()->query("SELECT COUNT(*) FROM orders WHERE delivery_user_id IS NULL AND status IN ('ready','preparing')")->fetchColumn();
    $metrics=[['Minhas entregas',$done,'📦','Histórico total','deliveries'],['Em rota',$active,'🛵','Entregas atuais','deliveries'],['Disponíveis',$available,'🔔','Aguardando entregador','deliveries'],['Ganhos',$earn,'💰','Taxas de entrega','finance']];
  }
}elseif(in_array($role,['mototaxi','taxi','private_driver'],true)){
  $s=db()->prepare('SELECT COUNT(*) FROM rides WHERE driver_id=?');$s->execute([$u['id']]);$rides=(int)$s->fetchColumn();
  $s=db()->prepare("SELECT COUNT(*) FROM rides WHERE driver_id=? AND status IN ('accepted','on_route','in_progress')");$s->execute([$u['id']]);$active=(int)$s->fetchColumn();
  $s=db()->prepare("SELECT COALESCE(SUM(estimated_value),0) FROM rides WHERE driver_id=? AND status='completed'");$s->execute([$u['id']]);$earn=(float)$s->fetchColumn();
  $s=db()->prepare("SELECT COUNT(*) FROM rides WHERE driver_id IS NULL AND ride_type=? AND status='requested'");$s->execute([$role]);$available=(int)$s->fetchColumn();
  $metrics=[['Corridas',$rides,'🚘','Histórico total','rides'],['Em andamento',$active,'📍','Corridas atuais','rides'],['Disponíveis',$available,'🔔','Novas solicitações','rides'],['Ganhos',$earn,'💰','Corridas concluídas','finance']];
}elseif($role==='service_provider'){
  $s=db()->prepare('SELECT COUNT(*) FROM services WHERE provider_id=?');$s->execute([$u['id']]);$services=(int)$s->fetchColumn();
  $s=db()->prepare('SELECT COUNT(*) FROM service_requests WHERE provider_id=?');$s->execute([$u['id']]);$requests=(int)$s->fetchColumn();
  $s=db()->prepare("SELECT COUNT(*) FROM service_requests WHERE provider_id=? AND status IN ('accepted','in_progress')");$s->execute([$u['id']]);$active=(int)$s->fetchColumn();
  $s=db()->prepare("SELECT COALESCE(SUM(amount),0) FROM service_requests WHERE provider_id=? AND status='completed'");$s->execute([$u['id']]);$earn=(float)$s->fetchColumn();
  $metrics=[['Serviços',$services,'🛠️','Ofertas cadastradas','services'],['Solicitações',$requests,'📋','Histórico','services'],['Em atendimento',$active,'⏳','Serviços ativos','services'],['Ganhos',$earn,'💰','Serviços concluídos','finance']];
}elseif($role==='property_owner'){
  $s=db()->prepare('SELECT COUNT(*) FROM properties WHERE owner_id=?');$s->execute([$u['id']]);$properties=(int)$s->fetchColumn();
  $s=db()->prepare("SELECT COUNT(*) FROM properties WHERE owner_id=? AND status='available'");$s->execute([$u['id']]);$available=(int)$s->fetchColumn();
  $s=db()->prepare('SELECT COUNT(*) FROM property_bookings pb JOIN properties p ON p.id=pb.property_id WHERE p.owner_id=?');$s->execute([$u['id']]);$requests=(int)$s->fetchColumn();
  $s=db()->prepare("SELECT COALESCE(SUM(price),0) FROM properties WHERE owner_id=? AND status='rented'");$s->execute([$u['id']]);$revenue=(float)$s->fetchColumn();
  $metrics=[['Imóveis',$properties,'🏠','Cadastrados','properties'],['Disponíveis',$available,'🔑','Para aluguel ou venda','properties'],['Interesses',$requests,'📅','Visitas e reservas','properties'],['Receita mensal',$revenue,'💰','Imóveis alugados','finance']];
}else{
  $s=db()->prepare('SELECT COUNT(*) FROM vehicles WHERE owner_user_id=?');$s->execute([$u['id']]);$vehicles=(int)$s->fetchColumn();
  $s=db()->prepare("SELECT COUNT(*) FROM vehicles WHERE owner_user_id=? AND status='available'");$s->execute([$u['id']]);$available=(int)$s->fetchColumn();
  $s=db()->prepare('SELECT COUNT(*) FROM vehicle_reservations vr JOIN vehicles v ON v.id=vr.vehicle_id WHERE v.owner_user_id=?');$s->execute([$u['id']]);$res=(int)$s->fetchColumn();
  $s=db()->prepare("SELECT COALESCE(SUM(vr.total),0) FROM vehicle_reservations vr JOIN vehicles v ON v.id=vr.vehicle_id WHERE v.owner_user_id=? AND vr.status='approved'");$s->execute([$u['id']]);$revenue=(float)$s->fetchColumn();
  $metrics=[['Veículos',$vehicles,'🚘','Frota cadastrada','vehicles'],['Disponíveis',$available,'✅','Prontos para locação','vehicles'],['Reservas',$res,'📅','Solicitações','vehicles'],['Receita',$revenue,'💰','Reservas aprovadas','finance']];
}

if(is_admin()){
  $logAdminFilter=is_role('sub_admin')?" AND (u.role IS NULL OR u.role NOT IN ('super_admin','sub_admin'))":'';
  $logs=db()->query("SELECT l.*,u.name FROM activity_logs l LEFT JOIN users u ON u.id=l.user_id WHERE l.action<>'login' $logAdminFilter ORDER BY l.id DESC LIMIT 40")->fetchAll();
}else {$q=db()->prepare("SELECT l.*,u.name FROM activity_logs l LEFT JOIN users u ON u.id=l.user_id WHERE l.user_id=? AND l.action<>'login' ORDER BY l.id DESC LIMIT 40");$q->execute([$u['id']]);$logs=$q->fetchAll();}
$maxLog=0;foreach($logs as $log)$maxLog=max($maxLog,(int)$log['id']);if($maxLog>0)save_user_ui_state((int)$u['id'],'information_last_log_id',(string)$maxLog);
?>
<section class="page-intro"><div><span class="mini-label">INFORMAÇÕES</span><h2>Resumo, manual e atividades</h2><p>Indicadores da conta, vídeos explicativos e alterações recentes ficam reunidos aqui.</p></div><?php if(is_super_admin()):?><button class="btn btn-primary" type="button" data-modal-open="#manualItemModal">+ Adicionar ao manual</button><?php endif;?></section>
<section class="panel" id="platformUpgrade"><div class="panel-header"><div><h3>⬆ Atualização do aplicativo</h3><p>Consulte a versão do APK publicada pelo Administrador Sênior e faça o download quando houver atualização.</p></div><button class="btn btn-primary" type="button" data-apk-update-toggle>Verificar atualização</button></div><div class="notice" data-apk-update-box hidden><?php if($apkInfo):?><strong><?=e($apkInfo['label'])?></strong><?php if(!empty($apkInfo['size'])):?> • <?=e($apkInfo['size'])?><?php endif;?><?php if(!empty($apkInfo['updated_at'])):?><br><small>Publicado/atualizado em <?=e(date('d/m/Y H:i',strtotime($apkInfo['updated_at'])))?></small><?php endif;?><div class="actions" style="margin-top:10px"><a class="btn btn-accent" href="<?=e($apkInfo['url'])?>" download>⬇ Baixar atualização do APK</a></div><?php else:?><strong>Nenhuma nova versão publicada no momento.</strong><br><small>Quando o administrador publicar um APK, o botão de download aparecerá aqui.</small><?php endif;?></div></section>
<div class="stats-grid information-stats">
<?php foreach($metrics as $m): ?><a class="stat-card information-stat-link" href="dashboard.php?page=<?= e($m[4]??'information') ?>"><div class="stat-top"><span><?= e($m[0]) ?></span><span class="stat-icon"><?= $m[2] ?></span></div><strong><?= is_float($m[1])?money($m[1]):number_format($m[1],0,',','.') ?></strong><small><?= e($m[3]) ?></small><span class="information-card-arrow">›</span></a><?php endforeach; ?>
</div>
<section class="panel login-history-entry"><a class="information-history-link" href="dashboard.php?page=terms_policies"><span class="information-history-icon">📜</span><span><strong>Termos e Políticas</strong><small>Consulte os Termos de Uso, a Política de Privacidade e os documentos publicados pela plataforma.</small></span><b>›</b></a></section>
<section class="panel login-history-entry"><a class="information-history-link" href="dashboard.php?page=login_history"><span class="information-history-icon">🕘</span><span><strong>Histórico de logins</strong><small>Veja datas, horários e IPs dos acessos<?= is_role('super_admin')?' de todos os usuários':(is_role('sub_admin')?' dos usuários não administrativos':'') ?>.</small></span><b>›</b></a></section>
<section class="panel login-history-entry"><a class="information-history-link" href="dashboard.php?page=quick_actions&self=1"><span class="information-history-icon">⚡</span><span><strong>Escolher minhas ações rápidas</strong><small>Defina quais atalhos aparecem para você na navegação rápida da plataforma.</small></span><b>›</b></a></section>
<section class="panel manual-library" id="manual"><div class="panel-header"><div><h3>📘 Manual da plataforma</h3><p>Assista aos vídeos sem sair do site ou app. Use “Flutuar vídeo” para acompanhar enquanto pratica em outra área.</p></div></div><div class="manual-grid"><?php if(!$manualItems):?><div class="empty-state"><strong>Manual em preparação</strong>Os conteúdos explicativos aparecerão aqui.</div><?php endif;?><?php foreach($manualItems as $manualItem):$video=manual_video_source((string)$manualItem['video_url']);?><article class="manual-card"><div class="manual-card-copy"><div><h3><?=e($manualItem['title'])?></h3><?php if(is_super_admin()):?><?=status_badge($manualItem['status'])?><?php endif;?></div><?php if(!empty($manualItem['description'])):?><p><?=e($manualItem['description'])?></p><?php endif;?><?php if(!empty($manualItem['content'])):?><div class="manual-content"><?=nl2br(e($manualItem['content']))?></div><?php endif;?></div><?php if($video['kind']!==''):?><button class="btn btn-primary btn-sm" type="button" data-manual-open style="margin-top:10px">▶ Assistir vídeo</button><div class="manual-video-shell" data-manual-video hidden><?php if($video['kind']==='iframe'):?><iframe src="<?=e($video['url'])?>" title="<?=e($manualItem['title'])?>" loading="lazy" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe><?php elseif($video['kind']==='video'):?><video src="<?=e($video['url'])?>" controls playsinline preload="metadata"></video><?php else:?><a class="btn btn-secondary" href="<?=e($video['url'])?>" target="_blank" rel="noopener">Acessar Vídeo</a><?php endif;?><?php if(in_array($video['kind'],['iframe','video'],true)):?><div class="manual-video-actions"><button class="btn btn-secondary btn-sm" type="button" data-manual-float>▣ Flutuar vídeo</button><button class="btn btn-secondary btn-sm" type="button" data-manual-fullscreen>⛶ Tela cheia</button></div><?php endif;?></div><?php endif;?><?php if(is_super_admin()):?><div class="actions manual-admin-actions"><button class="btn btn-secondary btn-sm" type="button" data-modal-open="#manualItemModal<?=(int)$manualItem['id']?>">Editar</button><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="delete_manual_item"><input type="hidden" name="return_page" value="information"><input type="hidden" name="id" value="<?=(int)$manualItem['id']?>"><button class="btn btn-danger btn-sm" data-confirm="Apagar este item do manual?">Apagar</button></form></div><?php endif;?></article><?php endforeach;?></div></section>
<section class="panel">
  <div class="panel-header"><div><h3>Atividades recentes</h3><p>Últimas alterações registradas na sua conta<?= is_admin()?' e na plataforma':'' ?>.</p></div></div>
  <div class="activity-list information-activity-list">
    <?php if(!$logs):?><div class="empty-state"><strong>Nenhuma atividade ainda</strong>As alterações aparecerão aqui.</div><?php else:foreach($logs as $log):?>
      <div class="activity"><span class="activity-dot"></span><div><p><strong><?= e($log['name']?:'Sistema') ?></strong> — <?= e(activity_action_label((string)$log['action'])) ?></p><?php if(!empty($log['details'])):?><small><?= e(short_text($log['details'],120)) ?></small><?php endif;?><small><?= e(date('d/m/Y H:i',strtotime($log['created_at']))) ?></small></div></div>
    <?php endforeach;endif;?>
  </div>
</section>
<?php if(is_super_admin()):foreach($manualItems as $manualItem):?><div class="modal" id="manualItemModal<?=(int)$manualItem['id']?>"><div class="modal-card"><div class="modal-head"><h2>Editar manual</h2><button class="close-btn" type="button" data-modal-close>×</button></div><?php include __DIR__.'/_manual_form.php';?></div></div><?php endforeach;$manualItem=['id'=>'','title'=>'','description'=>'','content'=>'','video_url'=>'','status'=>'active','sort_order'=>0];?><div class="modal" id="manualItemModal"><div class="modal-card"><div class="modal-head"><h2>Novo conteúdo do manual</h2><button class="close-btn" type="button" data-modal-close>×</button></div><?php include __DIR__.'/_manual_form.php';?></div></div><?php endif;?>

<script>document.querySelector('[data-apk-update-toggle]')?.addEventListener('click',e=>{const box=document.querySelector('[data-apk-update-box]');if(!box)return;box.hidden=!box.hidden;e.currentTarget.textContent=box.hidden?'Verificar atualização':'Ocultar atualização';});document.querySelectorAll('[data-manual-open]').forEach(btn=>btn.addEventListener('click',()=>{const shell=btn.nextElementSibling;if(!shell||!shell.matches('[data-manual-video]'))return;shell.hidden=!shell.hidden;btn.textContent=shell.hidden?'▶ Assistir vídeo':'▼ Ocultar vídeo';}));</script>
