<?php
$u=current_user();$isSuper=is_super_admin();
if(!$isSuper&&!is_role(['company','employee'])){http_response_code(403);exit('Sem permissão.');}
$companyId=$isSuper?(int)request('company_id',0):resolve_company_id_for_user($u);
if($isSuper&&!$companyId){$rows=db()->query("SELECT id FROM companies WHERE status='active' ORDER BY id")->fetchAll(PDO::FETCH_COLUMN);foreach($rows as $cid){if(company_is_gas((int)$cid)){$companyId=(int)$cid;break;}}}
if($companyId<1||!company_is_gas($companyId)){http_response_code(403);exit('Distribuidora de gás não encontrada.');}
$view=(string)request('view','stock');if(!in_array($view,['stock','clients','near','late','deliveries','couriers'],true))$view='stock';
$context=$isSuper?'&company_id='.$companyId:'';
$titles=['stock'=>'Estoque de botijões','clients'=>'Clientes ativos','near'=>'Próximos de comprar','late'=>'Clientes atrasados','deliveries'=>'Entregas em andamento','couriers'=>'Entregadores online'];$title=$titles[$view];
?>
<section class="page-intro"><div><span class="mini-label">🔥 DETALHES DA DISTRIBUIDORA</span><h2><?= e($title) ?></h2><p>Informações detalhadas do indicador selecionado no painel de gás.</p></div><div class="actions"><a class="btn btn-secondary" href="dashboard.php?page=gas_admin<?= e($context) ?>">← Painel de gás</a></div></section>
<?php if($view==='stock'):
$q=db()->prepare("SELECT * FROM products WHERE company_id=? AND deleted_at IS NULL AND COALESCE(is_gas_cylinder,0)=1 ORDER BY status DESC,name");$q->execute([$companyId]);$rows=$q->fetchAll();?>
<section class="panel"><div class="panel-header"><div><h3>Produtos marcados como botijão</h3><p>Estoque atual e limite de alerta.</p></div><a class="btn btn-primary btn-sm" href="dashboard.php?page=catalog<?= e($context) ?>">Gerenciar produtos</a></div><div class="table-wrap"><table><thead><tr><th>Produto</th><th>Estoque</th><th>Alerta baixo</th><th>Preço</th><th>Status</th></tr></thead><tbody><?php foreach($rows as $r):?><tr><td><strong><?= e($r['name']) ?></strong><small style="display:block"><?= e($r['gas_weight_kg']) ?> kg</small></td><td><?= e(number_format((float)$r['stock'],0,',','.')) ?></td><td><?= e(number_format((float)$r['low_stock_threshold'],0,',','.')) ?></td><td><?= money((float)$r['price']) ?></td><td><?= status_badge($r['status']) ?></td></tr><?php endforeach;?></tbody></table></div></section>
<?php elseif(in_array($view,['clients','near','late'],true)):
$q=db()->prepare("SELECT DISTINCT o.client_id,u.name,u.username,u.public_id,u.phone FROM orders o JOIN order_items oi ON oi.order_id=o.id JOIN products p ON p.id=oi.product_id LEFT JOIN users u ON u.id=o.client_id WHERE o.company_id=? AND o.status='delivered' AND o.client_id IS NOT NULL AND COALESCE(p.is_gas_cylinder,0)=1 ORDER BY o.id DESC");$q->execute([$companyId]);$clients=$q->fetchAll();$rows=[];foreach($clients as $cl){$profile=gas_consumption_profile($companyId,(int)$cl['client_id']);if($view==='near'&&$profile['status']!=='near')continue;if($view==='late'&&$profile['status']!=='late')continue;$profile['client']=$cl;$rows[]=$profile;}?>
<section class="panel"><div class="panel-header"><div><h3><?= e($title) ?></h3><p><?= count($rows) ?> cliente(s) neste grupo.</p></div><a class="btn btn-primary btn-sm" href="dashboard.php?page=company_clients<?= e($context) ?>">Pesquisar clientes / criar entrega</a></div><div class="table-wrap"><table><thead><tr><th>Cliente</th><th>Última compra</th><th>Média</th><th>Previsão</th><th>Situação</th><th>Ação</th></tr></thead><tbody><?php if(!$rows):?><tr><td colspan="6"><div class="empty-state"><strong>Nenhum cliente neste grupo</strong></div></td></tr><?php endif;?><?php foreach($rows as $gp):$cl=$gp['client'];?><tr><td><strong><?= e(user_public_name($cl)) ?></strong><small style="display:block"><?= e(format_phone($cl['phone'])) ?></small></td><td><?= e($gp['last_purchase']?date('d/m/Y',strtotime($gp['last_purchase'])):'—') ?></td><td><?= e(number_format((float)$gp['avg_days'],1,',','.')) ?> dias</td><td><?= e($gp['predicted_date']?date('d/m/Y',strtotime($gp['predicted_date'])):'—') ?></td><td><?= e(gas_status_label($gp['status'])) ?></td><td><a class="btn btn-primary btn-sm" href="dashboard.php?page=deliveries<?= e($context) ?>&client_id=<?= urlencode(public_user_id($cl)) ?>">Criar entrega</a></td></tr><?php endforeach;?></tbody></table></div></section>
<?php elseif($view==='deliveries'):
$q=db()->prepare("SELECT dj.*,u.name client_name,u.public_id,co.name courier_name FROM delivery_jobs dj LEFT JOIN users u ON u.id=dj.client_id LEFT JOIN users co ON co.id=dj.assigned_courier_id WHERE dj.company_id=? AND dj.status NOT IN ('delivered','cancelled','rejected') AND (dj.order_id IS NULL OR EXISTS(SELECT 1 FROM order_items oi JOIN products p ON p.id=oi.product_id WHERE oi.order_id=dj.order_id AND COALESCE(p.is_gas_cylinder,0)=1)) ORDER BY dj.id DESC");$q->execute([$companyId]);$rows=$q->fetchAll();?>
<section class="panel"><div class="panel-header"><div><h3>Entregas em andamento</h3></div><a class="btn btn-primary btn-sm" href="dashboard.php?page=deliveries<?= e($context) ?>">Acessar Entregas</a></div><div class="table-wrap"><table><thead><tr><th>Cliente</th><th>Pedido/volumes</th><th>Entregador</th><th>Endereço</th><th>Status</th></tr></thead><tbody><?php if(!$rows):?><tr><td colspan="5"><div class="empty-state"><strong>Nenhuma entrega em andamento</strong></div></td></tr><?php endif;?><?php foreach($rows as $r):?><tr><td><strong><?= e($r['client_name']?:'Cliente') ?></strong><small style="display:block"><?= e($r['public_id']?:$r['client_public_id']) ?></small></td><td><?= e($r['package_description']?:'Entrega #'.$r['id']) ?></td><td><?= e($r['courier_name']?:'Aguardando seleção') ?></td><td><?= e($r['address']) ?></td><td><?= status_badge($r['status']) ?></td></tr><?php endforeach;?></tbody></table></div></section>
<?php else:
$q=db()->prepare("SELECT u.id,u.name,u.username,u.public_id,u.phone,u.work_status,cc.relationship FROM company_couriers cc JOIN users u ON u.id=cc.user_id WHERE cc.company_id=? AND cc.status='active' AND u.status='active' AND u.work_status<>'offline' ORDER BY u.name");$q->execute([$companyId]);$rows=$q->fetchAll();?>
<section class="panel"><div class="panel-header"><div><h3>Entregadores online</h3><p><?= count($rows) ?> disponível(is) agora.</p></div><a class="btn btn-primary btn-sm" href="dashboard.php?page=deliveries<?= e($context) ?>">Gerenciar equipe</a></div><div class="cards-list"><?php if(!$rows):?><div class="empty-state"><strong>Nenhum entregador online</strong></div><?php endif;?><?php foreach($rows as $r):?><article class="item-card"><div class="item-body"><div class="profile-hero"><?= avatar_html($r) ?><div><h3><?= e(user_public_name($r)) ?></h3><small><?= e(public_user_id($r)) ?> • <?= e($r['relationship']==='internal'?'Próprio':'Autônomo') ?></small></div></div><div class="item-meta"><span><?= status_badge($r['work_status']) ?></span><span><?= e(format_phone($r['phone'])) ?></span></div></div></article><?php endforeach;?></div></section>
<?php endif;?>
