<?php
$u=current_user();$isSuper=is_super_admin();
$gasClients=[];
if($isSuper){
    $gasClients=db()->query("SELECT DISTINCT u.id,u.name,u.username,u.public_id,u.email,u.phone,u.home_address,u.home_number FROM orders o JOIN order_items oi ON oi.order_id=o.id JOIN products p ON p.id=oi.product_id JOIN users u ON u.id=o.client_id WHERE o.status='delivered' AND COALESCE(p.is_gas_cylinder,0)=1 AND u.role='client' ORDER BY u.name")->fetchAll();
    $uid=(int)request('user_id',0);if(!$uid&&$gasClients)$uid=(int)$gasClients[0]['id'];
    $selectedClient=null;foreach($gasClients as $gcUser)if((int)$gcUser['id']===$uid){$selectedClient=$gcUser;break;}
    if(!$selectedClient&&$uid>0){$q=db()->prepare("SELECT id,name,username,public_id,email,phone,home_address,home_number FROM users WHERE id=? AND role='client'");$q->execute([$uid]);$selectedClient=$q->fetch();}
}else{$uid=(int)$u['id'];$selectedClient=$u;}

$gasCompanies=[];
if($uid>0){$q=db()->prepare("SELECT o.company_id,c.name,c.phone,MAX(COALESCE(o.updated_at,o.created_at)) last_at FROM orders o JOIN order_items oi ON oi.order_id=o.id JOIN products p ON p.id=oi.product_id JOIN companies c ON c.id=o.company_id WHERE o.client_id=? AND o.status='delivered' AND COALESCE(p.is_gas_cylinder,0)=1 GROUP BY o.company_id ORDER BY last_at DESC");$q->execute([$uid]);$gasCompanies=$q->fetchAll();}
$companyId=(int)request('company',0);if(!$companyId&&$gasCompanies)$companyId=(int)$gasCompanies[0]['company_id'];
$company=null;foreach($gasCompanies as $gc)if((int)$gc['company_id']===$companyId){$company=$gc;break;}
$profile=$company?gas_consumption_profile($companyId,$uid):null;$history=$company?gas_purchase_history($companyId,$uid):[];
$activeDelivery=null;if($company){$q=db()->prepare("SELECT DISTINCT o.* 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 o.client_id=? AND COALESCE(p.is_gas_cylinder,0)=1 AND o.status NOT IN ('delivered','cancelled') ORDER BY o.id DESC LIMIT 1");$q->execute([$companyId,$uid]);$activeDelivery=$q->fetch();}
?>
<section class="page-intro"><div><span class="mini-label">🔥 MEU GÁS</span><h2>Painel de Consumo<?= $isSuper&&$selectedClient?' • '.e(user_public_name($selectedClient)):'' ?></h2><p><?= $isSuper?'Visão administrativa do consumo de gás do cliente selecionado.':'Acompanhe seu histórico e a previsão da próxima troca com base nas compras concluídas.' ?></p></div><div class="actions"><?php if($isSuper):?><a class="btn btn-secondary btn-sm" href="dashboard.php?page=gas_admin<?= $companyId?'&company_id='.$companyId:'' ?>">🔥 Distribuidora de Gás</a><?php else:?><a class="btn btn-secondary btn-sm" href="marketplace.php?segment=gas">🔎 Encontrar distribuidoras</a><a class="btn btn-secondary btn-sm" href="dashboard.php?page=orders">🧾 Meus pedidos</a><?php endif;?></div></section>
<?php if($isSuper):?><section class="panel" style="padding:12px 14px"><form class="filter-bar" method="get"><input type="hidden" name="page" value="my_gas"><div class="form-group"><label>Cliente</label><select name="user_id" data-auto-submit><?php if(!$gasClients):?><option value="">Nenhum cliente com histórico</option><?php endif;?><?php foreach($gasClients as $gcUser):?><option value="<?= (int)$gcUser['id'] ?>"<?= selected($uid,$gcUser['id']) ?>><?= e(user_public_name($gcUser).' • '.($gcUser['public_id']?:$gcUser['email'])) ?></option><?php endforeach;?></select></div><?php if(count($gasCompanies)>1):?><div class="form-group"><label>Distribuidora</label><select name="company" data-auto-submit><?php foreach($gasCompanies as $gc):?><option value="<?= (int)$gc['company_id'] ?>"<?= selected($companyId,$gc['company_id']) ?>><?= e($gc['name']) ?></option><?php endforeach;?></select></div><?php endif;?></form></section><?php elseif(count($gasCompanies)>1):?><section class="panel" style="padding:12px 14px"><form class="filter-bar" method="get"><input type="hidden" name="page" value="my_gas"><div class="form-group"><label>Distribuidora</label><select name="company" data-auto-submit><?php foreach($gasCompanies as $gc):?><option value="<?= (int)$gc['company_id'] ?>"<?= selected($companyId,$gc['company_id']) ?>><?= e($gc['name']) ?></option><?php endforeach;?></select></div></form></section><?php endif;?>
<?php if(!$company||!$profile||empty($profile['last_purchase'])):?><section class="panel"><div class="empty-state"><strong><?= $isSuper?'Nenhum histórico de gás para este cliente':'Seu histórico de gás ainda está vazio' ?></strong><p>Depois que uma compra de botijão for marcada como entregue, o sistema começará a calcular a média automaticamente.</p><?php if(!$isSuper):?><a class="btn btn-primary btn-sm" href="marketplace.php?segment=gas">🔥 Procurar distribuidora de gás</a><?php endif;?></div></section><?php else:?>
<div class="stats-grid">
  <div class="stat-card"><div class="stat-top"><span>Seu gás</span><span class="stat-icon">🔥</span></div><strong><?= (int)$profile['days_since'] ?> dias</strong><small>de consumo desde a última compra</small></div>
  <div class="stat-card"><div class="stat-top"><span>Última compra</span><span class="stat-icon">🛒</span></div><strong><?= e(date('d/m/Y',strtotime($profile['last_purchase']))) ?></strong><small><?= e($company['name']) ?></small></div>
  <div class="stat-card"><div class="stat-top"><span>Previsão de acabar</span><span class="stat-icon">📅</span></div><strong><?= e(date('d/m/Y',strtotime($profile['predicted_date']))) ?></strong><small><?= e(gas_status_label($profile['status'])) ?></small></div>
  <div class="stat-card"><div class="stat-top"><span>Consumo médio</span><span class="stat-icon">📈</span></div><strong><?= e(number_format((float)$profile['avg_days'],1,',','.')) ?> dias</strong><small>Baseado em <?= count($history) ?> compra(s)</small></div>
</div>
<section class="panel"><div class="panel-header"><div><h3><?= e(gas_status_label($profile['status'])) ?></h3><p><?= $profile['status']==='normal'?'O consumo está dentro da previsão atual.':($profile['status']==='near'?'O gás está próximo da data estimada para acabar.':'A data prevista já passou; talvez seja hora de pedir novamente.') ?></p></div><?php if(!$isSuper):?><div class="actions"><a class="btn btn-primary btn-sm" href="dashboard.php?page=catalog&store=<?= $companyId ?>">🛒 Comprar novamente</a><?php if(!empty($company['phone'])):?><a class="btn btn-accent btn-sm" target="_blank" rel="noopener" href="<?= e(whatsapp_url($company['phone'],'Olá! Gostaria de pedir gás novamente.',0,$companyId,'my_gas_reorder')) ?>">WhatsApp</a><?php endif;?></div><?php endif;?></div>
<?php if($activeDelivery):?><div class="notice"><strong>🛵 Entrega em andamento</strong><br>Pedido <?= e($activeDelivery['order_number']) ?> — <?= e(status_label($activeDelivery['status'])) ?>. <?php if(!$isSuper):?><a href="dashboard.php?page=orders">Acompanhar pedido</a><?php endif;?></div><?php endif;?>
<div class="grid-2" style="margin-top:16px"><div class="notice"><strong>📍 Endereço cadastrado</strong><br><?= e(trim(($selectedClient['home_address']??'').' '.($selectedClient['home_number']??''))?:'Nenhum endereço cadastrado') ?><?php if(!$isSuper):?><div style="margin-top:8px"><a href="dashboard.php?page=profile">Editar endereço</a></div><?php endif;?></div><div class="notice"><strong>💳 Formas de pagamento</strong><br>Pix, cartão ou dinheiro, conforme disponibilidade da distribuidora.<br><small><?php $lastOrder=$history[0]??null;if($lastOrder){$oq=db()->prepare('SELECT payment_method,total FROM orders WHERE id=?');$oq->execute([(int)$lastOrder['id']]);$lo=$oq->fetch();echo 'Última compra: '.e(ucfirst((string)($lo['payment_method']??'Não informada'))).' • '.money((float)($lo['total']??0));}else echo 'Nenhuma compra concluída ainda.';?></small></div></div></section>
<section class="panel"><div class="panel-header"><div><h3>Histórico de compras</h3><p>Quanto mais compras forem concluídas, mais precisa fica a previsão.</p></div></div><div class="table-wrap"><table><thead><tr><th>Data</th><th>Pedido</th><th>Botijões</th><th>Valor em gás</th><th>Total do pedido</th></tr></thead><tbody><?php foreach($history as $h):?><tr><td><?= e(date('d/m/Y',strtotime($h['purchase_date']))) ?></td><td><?= e($h['order_number']) ?></td><td><?= e(number_format((float)$h['cylinder_qty'],0,',','.')) ?></td><td><?= money((float)$h['gas_amount']) ?></td><td><?= money((float)$h['total']) ?></td></tr><?php endforeach;?></tbody></table></div></section>
<?php endif;?>
