<?php
$u=current_user();
if(!user_can_work_deliveries($u)||!user_is_gas_courier($u)){http_response_code(403);exit('Área exclusiva para entregadores vinculados a uma distribuidora de gás.');}
$companyIds=gas_courier_company_ids((int)$u['id']);
$view=(string)request('view','active');if(!in_array($view,['active','history'],true))$view='active';
$marks=implode(',',array_fill(0,count($companyIds),'?'));
$params=array_merge([(int)$u['id']],$companyIds);
$statusSql=$view==='history'?"dj.status IN ('delivered','cancelled','rejected')":"dj.status NOT IN ('delivered','cancelled','rejected')";
$sql="SELECT dj.*,cp.name company_name,cp.phone company_phone,o.order_number,o.payment_status,o.payment_method,o.total order_total,c.name linked_client_name,c.username client_username,c.public_id linked_client_public_id,c.phone linked_client_phone,c.home_lat client_home_lat,c.home_lng client_home_lng FROM delivery_jobs dj JOIN companies cp ON cp.id=dj.company_id LEFT JOIN orders o ON o.id=dj.order_id LEFT JOIN users c ON c.id=dj.client_id WHERE dj.assigned_courier_id=? AND dj.company_id IN ($marks) AND $statusSql ORDER BY CASE WHEN dj.status='on_route' THEN 0 WHEN dj.status='accepted' THEN 1 WHEN dj.status='assigned' THEN 2 ELSE 3 END,CASE WHEN dj.scheduled_at IS NULL THEN 1 ELSE 0 END,dj.scheduled_at,dj.id DESC";
$q=db()->prepare($sql);$q->execute($params);$jobs=$q->fetchAll();

$q=db()->prepare("SELECT COUNT(*) FROM delivery_jobs WHERE assigned_courier_id=? AND company_id IN ($marks) AND status NOT IN ('delivered','cancelled','rejected')");$q->execute($params);$activeCount=(int)$q->fetchColumn();
$q=db()->prepare("SELECT COUNT(*) FROM delivery_jobs WHERE assigned_courier_id=? AND company_id IN ($marks) AND status='on_route'");$q->execute($params);$routeCount=(int)$q->fetchColumn();
$q=db()->prepare("SELECT COUNT(*) FROM delivery_jobs WHERE assigned_courier_id=? AND company_id IN ($marks) AND status='delivered'");$q->execute($params);$deliveredCount=(int)$q->fetchColumn();
?>
<section class="page-intro"><div><span class="mini-label">🔥 ENTREGADOR DE GÁS</span><h2>Minha área de trabalho</h2><p>Ordens das distribuidoras de gás vinculadas à sua conta, separadas das demais informações da plataforma.</p></div><div class="actions"><a class="btn <?= $view==='active'?'btn-primary':'btn-secondary' ?>" href="dashboard.php?page=gas_courier&view=active">Em andamento</a><a class="btn <?= $view==='history'?'btn-primary':'btn-secondary' ?>" href="dashboard.php?page=gas_courier&view=history">Histórico</a></div></section>

<div class="stats-grid">
  <div class="stat-card"><div class="stat-top"><span>Distribuidoras</span><span class="stat-icon">🔥</span></div><strong><?= count($companyIds) ?></strong><small>Vínculos ativos</small></div>
  <div class="stat-card"><div class="stat-top"><span>Entregas ativas</span><span class="stat-icon">📦</span></div><strong><?= $activeCount ?></strong><small>Aguardando conclusão</small></div>
  <div class="stat-card"><div class="stat-top"><span>Em rota</span><span class="stat-icon">🛵</span></div><strong><?= $routeCount ?></strong><small>Saíram para entrega</small></div>
  <div class="stat-card"><div class="stat-top"><span>Concluídas</span><span class="stat-icon">✅</span></div><strong><?= $deliveredCount ?></strong><small>Histórico total</small></div>
</div>

<section class="panel">
  <div class="panel-header"><div><h3>Status de trabalho</h3><p>Atualize sua disponibilidade sem sair desta área.</p></div><?= status_badge($u['work_status']??'offline') ?></div>
  <form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="update_work_status"><input type="hidden" name="return_page" value="gas_courier"><div class="form-grid"><div class="form-group"><label>Meu status</label><select name="work_status"><option value="available"<?= selected($u['work_status'],'available') ?>>Disponível</option><option value="busy"<?= selected($u['work_status'],'busy') ?>>Ocupado</option><option value="on_route"<?= selected($u['work_status'],'on_route') ?>>Em rota</option><option value="offline"<?= selected($u['work_status'],'offline') ?>>Offline</option></select></div><div class="form-group" style="justify-content:end"><button class="btn btn-secondary">Atualizar status</button></div></div></form>
</section>

<section class="panel"><div class="panel-header"><div><h3><?= $view==='history'?'Histórico de entregas':'Ordens de entrega de gás' ?></h3><p><?= $view==='history'?'Entregas concluídas ou encerradas.':'Cliente, endereço e produtos ficam reunidos na mesma ordem.' ?></p></div></div>
<div class="cards-list">
<?php if(!$jobs):?><div class="empty-state"><strong><?= $view==='history'?'Nenhuma entrega no histórico':'Nenhuma ordem de gás ativa' ?></strong><?= $view==='history'?'As entregas encerradas aparecerão aqui.':'Quando a distribuidora selecionar você, a ordem aparecerá nesta área.' ?></div><?php endif;?>
<?php foreach($jobs as $j):
  $clientName=!empty($j['linked_client_name'])?user_public_name(['username'=>$j['client_username']??'','public_id'=>$j['linked_client_public_id']??($j['client_public_id']??''),'name'=>$j['linked_client_name']]):($j['client_name']?:'Cliente');
  $clientPhone=$j['linked_client_phone']?:$j['client_phone'];
  $address=trim((string)$j['address']);
  $lat=$j['latitude']!==null?$j['latitude']:$j['client_home_lat'];$lng=$j['longitude']!==null?$j['longitude']:$j['client_home_lng'];
  $hideClientLocation=($j['status']==='delivered');
  if($hideClientLocation){$address='';$lat=null;$lng=null;$clientPhone='';}
?>
<article class="item-card"><div class="item-body">
  <div class="panel-header" style="margin-bottom:10px"><div><span class="mini-label"><?= e($j['company_name']) ?></span><h3><?= e($j['order_number']?'Pedido '.$j['order_number']:'Entrega #'.$j['id']) ?></h3></div><?= status_badge($j['status']) ?></div>
  <div class="item-meta"><span>👤 <?= e($clientName) ?></span><?php if($j['scheduled_at']):?><span>🕒 <?= e(date('d/m/Y H:i',strtotime($j['scheduled_at']))) ?></span><?php endif;?></div>
  <?php if($hideClientLocation):?><div class="notice">🔒 Entrega concluída. O endereço e o contato do cliente foram ocultados para preservar a privacidade.</div><?php else:?><p><strong>📍 Endereço:</strong> <?= e($address?:'Não informado') ?></p><?php endif;?>
  <p><strong>📦 Produtos / quantidade:</strong><br><?= nl2br(e($j['package_description']?:'Volumes não informados')) ?></p>
  <?php if(!empty($j['notes'])):?><p><strong>📝 Observações:</strong> <?= e($j['notes']) ?></p><?php endif;?>
  <?php if($j['order_number']):?><div class="notice"><strong>Pagamento:</strong> <?= status_badge($j['payment_status']?:'pending') ?><?php if($j['order_total']!==null):?> • <strong>Total:</strong> <?= money((float)$j['order_total']) ?><?php endif;?></div><?php endif;?>
  <div class="actions" style="margin-top:12px">
    <?php if($address!==''||($lat!==null&&$lng!==null)):?><a class="btn btn-secondary btn-sm" target="_blank" rel="noopener" href="<?= e(maps_link($address,$lat,$lng)) ?>">📍 Google Maps</a><a class="btn btn-accent btn-sm" target="_blank" rel="noopener" href="<?= e(waze_link($address,$lat,$lng)) ?>">🧭 Waze</a><?php endif;?>
    <?php if($clientPhone):?><a class="btn btn-secondary btn-sm" target="_blank" rel="noopener" href="<?= e(whatsapp_url($clientPhone,'Olá, sou o entregador responsável pela sua entrega'.($j['order_number']?' do pedido '.$j['order_number']:'').'.')) ?>">💬 WhatsApp do cliente</a><?php endif;?>
  </div>
  <?php if($view==='active'):?><div class="actions" style="margin-top:14px">
    <?php if(in_array($j['status'],['assigned','ready','waiting_authorization'],true)):?><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="update_delivery_job"><input type="hidden" name="return_page" value="gas_courier"><input type="hidden" name="id" value="<?= (int)$j['id'] ?>"><input type="hidden" name="status" value="accepted"><button class="btn btn-primary btn-sm">✓ Aceitar entrega</button></form><?php endif;?>
    <?php if($j['status']==='accepted'):?><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="update_delivery_job"><input type="hidden" name="return_page" value="gas_courier"><input type="hidden" name="id" value="<?= (int)$j['id'] ?>"><input type="hidden" name="status" value="on_route"><button class="btn btn-primary btn-sm">🛵 Sair para entrega</button></form><?php endif;?>
    <?php if($j['status']==='on_route'):?><form method="post" action="actions.php" onsubmit="return confirm('Confirmar que a entrega foi concluída?');"><?= csrf_field() ?><input type="hidden" name="action" value="update_delivery_job"><input type="hidden" name="return_page" value="gas_courier"><input type="hidden" name="id" value="<?= (int)$j['id'] ?>"><input type="hidden" name="status" value="delivered"><button class="btn btn-accent btn-sm">✅ Concluir entrega</button></form><?php endif;?>
    <form method="post" action="actions.php" onsubmit="return confirm('Cancelar esta ordem? Ela voltará para a distribuidora selecionar outro entregador.');"><?= csrf_field() ?><input type="hidden" name="action" value="update_delivery_job"><input type="hidden" name="return_page" value="gas_courier"><input type="hidden" name="id" value="<?= (int)$j['id'] ?>"><input type="hidden" name="status" value="cancelled"><button class="btn btn-danger btn-sm">Cancelar ordem</button></form>
  </div><?php endif;?>
</div></article>
<?php endforeach;?>
</div></section>
