<?php
$u=current_user();$isSuper=is_super_admin();
if(!$isSuper&&!is_role(['company','employee'])){http_response_code(403);exit('Sem permissão.');}
$gasCompanies=[];
if($isSuper){
    $allCompanies=db()->query("SELECT id,name,status FROM companies WHERE status='active' ORDER BY name")->fetchAll();
    foreach($allCompanies as $row)if(company_is_gas((int)$row['id']))$gasCompanies[]=$row;
    $companyId=(int)request('company_id',0);if(!$companyId&&$gasCompanies)$companyId=(int)$gasCompanies[0]['id'];
}else $companyId=resolve_company_id_for_user($u);
if($companyId<1||!company_is_gas($companyId)){
    if($isSuper){?><section class="panel"><div class="empty-state"><strong>Nenhuma distribuidora de gás ativa</strong>Cadastre ou ative uma empresa do segmento de gás para visualizar este painel.</div></section><?php return;}
    http_response_code(403);exit('Painel disponível somente para distribuidoras de gás.');
}
$cq=db()->prepare('SELECT * FROM companies WHERE id=?');$cq->execute([$companyId]);$company=$cq->fetch();

$today=today();$month=substr($today,0,7);
$base=" FROM orders o JOIN order_items oi ON oi.order_id=o.id JOIN products p ON p.id=oi.product_id WHERE o.company_id=? AND COALESCE(p.is_gas_cylinder,0)=1";
$q=db()->prepare("SELECT COALESCE(SUM(oi.total),0) revenue,COALESCE(SUM(oi.qty),0) cylinders,COALESCE(SUM((oi.price-COALESCE(p.cost_price,0))*oi.qty),0) profit".$base." AND o.status='delivered' AND date(COALESCE(o.updated_at,o.created_at))=?");$q->execute([$companyId,$today]);$daily=$q->fetch();
$q=db()->prepare("SELECT COALESCE(SUM(oi.total),0) revenue,COALESCE(SUM(oi.qty),0) cylinders,COALESCE(SUM((oi.price-COALESCE(p.cost_price,0))*oi.qty),0) profit".$base." AND o.status='delivered' AND substr(COALESCE(o.updated_at,o.created_at),1,7)=?");$q->execute([$companyId,$month]);$monthly=$q->fetch();
$q=db()->prepare("SELECT COALESCE(SUM(stock),0) FROM products WHERE company_id=? AND status='active' AND COALESCE(is_gas_cylinder,0)=1");$q->execute([$companyId]);$stock=(float)$q->fetchColumn();
$q=db()->prepare("SELECT COALESCE(SUM(oi.qty),0)".$base." AND o.status='on_route'");$q->execute([$companyId]);$inDelivery=(float)$q->fetchColumn();
$q=db()->prepare("SELECT COUNT(DISTINCT o.id)".$base." AND o.status='on_route'");$q->execute([$companyId]);$deliveriesInProgress=(int)$q->fetchColumn();
$q=db()->prepare("SELECT COUNT(DISTINCT u.id) FROM users u LEFT JOIN company_couriers cc ON cc.user_id=u.id AND cc.company_id=? AND cc.status='approved' WHERE u.status='active' AND u.work_status<>'offline' AND (u.company_id=? OR cc.id IS NOT NULL) AND u.role IN ('courier','motofreight','mototaxi')");$q->execute([$companyId,$companyId]);$couriersOnline=(int)$q->fetchColumn();

$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();
$profiles=[];$near=0;$late=0;$avgSum=0;$avgCount=0;
foreach($clients as $client){$profile=gas_consumption_profile($companyId,(int)$client['client_id']);if(!$profile)continue;$profile['client']=$client;$profiles[]=$profile;if($profile['status']==='near')$near++;if($profile['status']==='late')$late++;if(($profile['avg_days']??0)>0){$avgSum+=(float)$profile['avg_days'];$avgCount++;}}
$avgConsumption=$avgCount?round($avgSum/$avgCount,1):0;

$q=db()->prepare("SELECT o.id,o.order_number,o.status,o.total,o.created_at,o.updated_at,u.name client_name,u.username client_username,u.public_id client_public_id,u.phone client_phone,SUM(oi.qty) gas_qty,SUM(oi.total) gas_total 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 COALESCE(p.is_gas_cylinder,0)=1 GROUP BY o.id ORDER BY o.id DESC LIMIT 30");$q->execute([$companyId]);$history=$q->fetchAll();
$gasContext=$isSuper?'&company_id='.$companyId:'';
?>
<section class="page-intro"><div><span class="mini-label">🔥 DISTRIBUIDORA DE GÁS</span><h2><?= e($company['name']??'Distribuidora de Gás') ?></h2><p><?= $isSuper?'Visão administrativa da distribuidora selecionada.':'Consumo, previsão de recompra, estoque, entregas e desempenho do segmento de gás em um só lugar.' ?></p></div><div class="actions gas-admin-shortcuts"><a class="btn btn-secondary btn-sm" href="dashboard.php?page=catalog<?= $isSuper?'&company_id='.$companyId:'' ?>">🛍️ Produtos</a><a class="btn btn-secondary btn-sm" href="dashboard.php?page=orders<?= $isSuper?'&company_id='.$companyId:'' ?>">🧾 Pedidos</a><a class="btn btn-secondary btn-sm" href="dashboard.php?page=deliveries<?= $isSuper?'&company_id='.$companyId:'' ?>">📍 Entregas</a></div></section>
<?php if($isSuper&&count($gasCompanies)>1):?><section class="panel" style="padding:12px 14px"><form class="filter-bar" method="get"><input type="hidden" name="page" value="gas_admin"><div class="form-group"><label>Distribuidora de gás</label><select name="company_id" data-auto-submit><?php foreach($gasCompanies as $gc):?><option value="<?= (int)$gc['id'] ?>"<?= selected($companyId,$gc['id']) ?>><?= e($gc['name']) ?></option><?php endforeach;?></select></div></form></section><?php endif;?>
<div class="stats-grid">
  <a class="stat-card" style="text-decoration:none;color:inherit" href="dashboard.php?page=gas_history&period=today<?= e($gasContext) ?>"><div class="stat-top"><span>Vendas hoje</span><span class="stat-icon">💰</span></div><strong><?= money((float)$daily['revenue']) ?></strong><small><?= number_format((float)$daily['cylinders'],0,',','.') ?> botijão(ões) • tocar para detalhes</small></a>
  <a class="stat-card" style="text-decoration:none;color:inherit" href="dashboard.php?page=gas_history&period=month<?= e($gasContext) ?>"><div class="stat-top"><span>Vendas no mês</span><span class="stat-icon">📈</span></div><strong><?= money((float)$monthly['revenue']) ?></strong><small><?= number_format((float)$monthly['cylinders'],0,',','.') ?> botijão(ões) • lucro estimado: <?= money((float)$monthly['profit']) ?></small></a>
  <a class="stat-card" style="text-decoration:none;color:inherit" href="dashboard.php?page=gas_detail&view=stock<?= e($gasContext) ?>"><div class="stat-top"><span>Estoque</span><span class="stat-icon">🧯</span></div><strong><?= number_format($stock,0,',','.') ?></strong><small>Botijões marcados no catálogo • tocar para detalhes</small></a>
  <a class="stat-card" style="text-decoration:none;color:inherit" href="dashboard.php?page=gas_detail&view=clients<?= e($gasContext) ?>"><div class="stat-top"><span>Clientes ativos</span><span class="stat-icon">👥</span></div><strong><?= count($profiles) ?></strong><small>Média de consumo: <?= $avgConsumption?e(number_format($avgConsumption,1,',','.')).' dias':'Aguardando histórico' ?></small></a>
  <a class="stat-card" style="text-decoration:none;color:inherit" href="dashboard.php?page=gas_detail&view=near<?= e($gasContext) ?>"><div class="stat-top"><span>Próximos de comprar</span><span class="stat-icon">🟡</span></div><strong><?= $near ?></strong><small>Dentro da janela prevista • tocar para detalhes</small></a>
  <a class="stat-card" style="text-decoration:none;color:inherit" href="dashboard.php?page=gas_detail&view=late<?= e($gasContext) ?>"><div class="stat-top"><span>Atrasados</span><span class="stat-icon">🔴</span></div><strong><?= $late ?></strong><small>Previsão de troca já passou • tocar para detalhes</small></a>
  <a class="stat-card" style="text-decoration:none;color:inherit" href="dashboard.php?page=gas_detail&view=deliveries<?= e($gasContext) ?>"><div class="stat-top"><span>Em entrega</span><span class="stat-icon">🛵</span></div><strong><?= $deliveriesInProgress ?></strong><small><?= number_format($inDelivery,0,',','.') ?> botijão(ões) em rota • tocar para detalhes</small></a>
  <a class="stat-card" style="text-decoration:none;color:inherit" href="dashboard.php?page=gas_detail&view=couriers<?= e($gasContext) ?>"><div class="stat-top"><span>Entregadores online</span><span class="stat-icon">🟢</span></div><strong><?= $couriersOnline ?></strong><small>Vinculados e disponíveis • tocar para detalhes</small></a>
</div>
<section class="panel"><div class="panel-header"><div><h3>📊 Painel de consumo dos clientes</h3><p>O cálculo usa o intervalo entre compras entregues e fica mais preciso conforme o histórico aumenta.</p></div></div>
<?php if(!$profiles):?><div class="empty-state"><strong>Ainda não há histórico suficiente</strong>Marque os botijões no cadastro de Produtos. A previsão começa após pedidos entregues.</div><?php else:?><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 rápida</th></tr></thead><tbody><?php foreach($profiles as $gp):$cl=$gp['client'];?><tr><td><strong><?= e(user_public_name($cl)) ?></strong><small style="display:block"><?= e($cl['name']?:'—') ?> • <?= e($cl['public_id']?:'') ?></small></td><td><?= e(date('d/m/Y',strtotime($gp['last_purchase']))) ?><small style="display:block"><?= (int)$gp['days_since'] ?> dia(s) atrás</small></td><td><?= e(number_format((float)$gp['avg_days'],1,',','.')) ?> dias</td><td><?= e(date('d/m/Y',strtotime($gp['predicted_date']))) ?></td><td><?= e(gas_status_label($gp['status'])) ?></td><td><?php if(!empty($cl['phone'])):?><a class="btn btn-accent btn-sm" target="_blank" rel="noopener" href="<?= e(whatsapp_url($cl['phone'],'Olá! Pelo seu histórico, seu gás está próximo da data prevista para acabar. Deseja solicitar uma nova entrega?',(int)$cl['client_id'],$companyId,'gas_prediction')) ?>">WhatsApp</a><?php else:?>—<?php endif;?></td></tr><?php endforeach;?></tbody></table></div><?php endif;?></section>
<section class="panel"><div class="panel-header"><div><h3>Histórico de vendas de gás</h3><p>Últimos pedidos contendo produtos marcados como botijão de gás.</p></div><a class="btn btn-secondary btn-sm" href="dashboard.php?page=gas_history&period=all<?= e($gasContext) ?>">Acessar histórico completo</a></div><div class="table-wrap"><table><thead><tr><th>Pedido</th><th>Cliente</th><th>Botijões</th><th>Valor</th><th>Status</th><th>Data</th></tr></thead><tbody><?php foreach($history as $row):?><tr><td><strong><?= e($row['order_number']) ?></strong></td><td><?= e(user_public_name(['username'=>$row['client_username'],'public_id'=>$row['client_public_id'],'name'=>$row['client_name']])) ?></td><td><?= e(number_format((float)$row['gas_qty'],0,',','.')) ?></td><td><?= money((float)$row['gas_total']) ?></td><td><?= status_badge($row['status']) ?></td><td><?= e(date('d/m/Y H:i',strtotime($row['updated_at']?:$row['created_at']))) ?></td></tr><?php endforeach;?></tbody></table></div></section>
