<?php
$u=current_user();$isCompany=is_admin()||is_role(['company','employee']);$isCourier=user_can_work_deliveries($u);$isClient=!$isCompany&&!$isCourier;
if(is_role('mototaxi')&&!$isCourier){
  $rq=db()->prepare('SELECT * FROM delivery_mode_requests WHERE user_id=? ORDER BY id DESC LIMIT 1');$rq->execute([$u['id']]);$deliveryRequest=$rq->fetch();
  ?>
  <section class="page-intro"><div><span class="mini-label">NOVA MODALIDADE</span><h2>Trabalhar também com Entregas</h2><p>Como Mototaxista, você pode pedir ao administrador a liberação para também receber trabalhos de entrega.</p></div></section>
  <section class="panel"><div class="panel-header"><div><h3>Acesso à modalidade Entregas</h3><p>O acesso só fica ativo depois da aprovação do administrador.</p></div><?= $deliveryRequest?status_badge($deliveryRequest['status']):'<span class="status">Não solicitado</span>' ?></div>
  <?php if($deliveryRequest&&$deliveryRequest['status']==='pending'):?><div class="notice"><strong>Solicitação enviada.</strong><br>Você será notificado assim que o administrador aprovar ou recusar.</div>
  <?php else:?><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="request_delivery_mode"><input type="hidden" name="return_page" value="deliveries"><div class="form-group"><label>Mensagem opcional ao administrador</label><textarea name="notes" placeholder="Ex.: Tenho disponibilidade para realizar entregas na minha região."></textarea></div><div class="form-actions"><button class="btn btn-primary">Solicitar acesso a Entregas</button></div></form><?php endif;?>
  <?php if($deliveryRequest&&$deliveryRequest['status']==='rejected'&&!empty($deliveryRequest['admin_notes'])):?><div class="notice" style="margin-top:14px"><strong>Observação do administrador:</strong> <?= e($deliveryRequest['admin_notes']) ?></div><?php endif;?>
  </section>
  <?php return;
}
$companyId=is_admin()?(int)request('company_id',0):resolve_company_id_for_user($u);$sort=request('sort','schedule');$prefillClientId=strtoupper(trim((string)request('client_id','')));
if($isCompany){
  // Compatibilidade: pedidos comuns pagos também precisam aparecer na operação de entregas.
  if($companyId>0){
    try{
      $bq=db()->prepare("SELECT o.id FROM orders o LEFT JOIN delivery_jobs dj ON dj.order_id=o.id WHERE o.company_id=? AND COALESCE(o.fulfillment_type,'delivery')='delivery' AND o.payment_status='paid' AND o.status NOT IN ('delivered','cancelled') AND dj.id IS NULL ORDER BY o.id");
      $bq->execute([$companyId]);
      foreach($bq->fetchAll(PDO::FETCH_COLUMN) as $pendingOrderId)ensure_order_delivery_job((int)$pendingOrderId);
    }catch(Throwable $ignored){}
  }
  if(is_admin()&&!$companyId)$companyId=(int)db()->query('SELECT id FROM companies ORDER BY id LIMIT 1')->fetchColumn();
  $q=db()->prepare("SELECT cc.*,u.name,u.public_id,u.phone,u.avatar,u.role,u.work_status FROM company_couriers cc JOIN users u ON u.id=cc.user_id WHERE cc.company_id=? ORDER BY u.name");$q->execute([$companyId]);$couriers=$q->fetchAll();
  $q=db()->prepare("SELECT dj.*,c.name client_user_name,c.username client_username,c.public_id linked_client_public_id,c.avatar client_avatar,co.name courier_name,co.username courier_username,co.public_id courier_public_id,co.phone courier_phone FROM delivery_jobs dj LEFT JOIN users c ON c.id=dj.client_id LEFT JOIN users co ON co.id=dj.assigned_courier_id WHERE dj.company_id=? ORDER BY CASE WHEN dj.scheduled_at IS NULL THEN 1 ELSE 0 END,dj.scheduled_at,dj.id DESC");$q->execute([$companyId]);$jobs=$q->fetchAll();
}elseif($isCourier){
  $orderBy=$sort==='distance'?'dj.distance_km ASC':($sort==='late'?'CASE WHEN dj.scheduled_at<datetime("now") AND dj.status NOT IN ("delivered","cancelled") THEN 0 ELSE 1 END,dj.scheduled_at ASC':'CASE WHEN dj.scheduled_at IS NULL THEN 1 ELSE 0 END,dj.scheduled_at ASC,dj.distance_km ASC');
  $q=db()->prepare("SELECT dj.*,cp.name company_name,c.name client_user_name,c.username client_username,c.public_id linked_client_public_id,c.avatar client_avatar,c.phone client_phone,c.telegram client_telegram FROM delivery_jobs dj JOIN companies cp ON cp.id=dj.company_id LEFT JOIN users c ON c.id=dj.client_id WHERE dj.assigned_courier_id=? AND dj.status NOT IN ('delivered','cancelled','rejected') ORDER BY $orderBy");$q->execute([$u['id']]);$jobs=$q->fetchAll();$couriers=[];
}else{
  $q=db()->prepare("SELECT dj.*,cp.name company_name,co.name courier_name,co.username courier_username,co.public_id courier_public_id,co.phone courier_phone FROM delivery_jobs dj JOIN companies cp ON cp.id=dj.company_id LEFT JOIN users co ON co.id=dj.assigned_courier_id WHERE dj.client_id=? AND (dj.status NOT IN ('cancelled','rejected') AND (dj.status<>'delivered' OR datetime(COALESCE(dj.delivered_at,dj.updated_at,dj.created_at))>=datetime('now','-30 days'))) ORDER BY dj.id DESC");$q->execute([$u['id']]);$jobs=$q->fetchAll();$couriers=[];
}
$companies=is_admin()?db()->query('SELECT id,name FROM companies WHERE status="active" ORDER BY name')->fetchAll():[];
$courierCapacity=($isCompany&&$companyId)?company_capacity_info($companyId,'couriers'):['limit'=>0,'used'=>0,'remaining'=>0,'enabled'=>false,'reached'=>true];
?>
<section class="page-intro"><div><span class="mini-label">LOGÍSTICA</span><h2><?= $isClient?'Entregas destinadas a mim':($isCourier?'Minhas entregas':'Entregadores e entregas') ?></h2><p><?= $isCompany?'Empresa e funcionários acompanham pedidos liberados para entrega, equipe de entregadores e agendamentos com volumes, horário e responsável.':($isCourier?'Ordene pela distância, horário ou atraso e navegue pelo Waze/Google Maps.':'A entrega aparece até ser confirmada como entregue.') ?></p></div><?php if($isCompany):?><div class="actions"><a class="btn btn-secondary" href="dashboard.php?page=company_clients">Clientes da empresa</a><span class="status <?= $courierCapacity['reached']?'status-overdue':'status-active' ?>">Entregadores: <?= e(company_capacity_text($companyId,'couriers')) ?></span><?php if(!$courierCapacity['enabled']):?><button class="btn btn-secondary" disabled>Cadastro de entregadores não liberado</button><?php elseif(!$courierCapacity['reached']):?><button class="btn btn-secondary" data-modal-open="#linkCourierModal">Contratar autônomo</button><button class="btn btn-secondary" data-modal-open="#ownCourierModal">Entregador próprio</button><?php else:?><button class="btn btn-secondary" disabled>Limite de entregadores atingido</button><?php endif;?><button class="btn btn-primary" data-modal-open="#deliveryModal">+ Agendar entrega</button></div><?php endif;?></section>
<?php if(is_admin()):?><form class="filter-bar" method="get"><input type="hidden" name="page" value="deliveries"><div class="form-group"><label>Empresa</label><select name="company_id" data-auto-submit><?php foreach($companies as $c):?><option value="<?= (int)$c['id'] ?>"<?= selected($companyId,$c['id']) ?>><?= e($c['name']) ?></option><?php endforeach;?></select></div></form><?php endif;?>
<?php if($isCourier):?><form class="filter-bar" method="get"><input type="hidden" name="page" value="deliveries"><div class="form-group"><label>Ordenar por</label><select name="sort" data-auto-submit><option value="schedule"<?= selected($sort,'schedule') ?>>Horário agendado</option><option value="distance"<?= selected($sort,'distance') ?>>Menor distância</option><option value="late"<?= selected($sort,'late') ?>>Atrasadas primeiro</option></select></div></form><?php endif;?>
<?php if($isCompany):?><section class="panel"><div class="panel-header"><div><h3>Equipe de entregas</h3></div></div><div class="cards-list"><?php if(!$couriers):?><div class="empty-state"><strong>Nenhum entregador</strong></div><?php endif;foreach($couriers as $c):?><article class="item-card"><div class="item-body"><div class="profile-hero"><?= avatar_html($c) ?><div><h3><?= e(user_public_name($c)) ?></h3><small><?= e(public_user_id($c)) ?> • <?= e($c['relationship']==='internal'?'Próprio':'Autônomo') ?></small></div></div><div class="item-meta"><span><?= status_badge($c['work_status']) ?></span><span><?= e(format_phone($c['phone'])) ?></span></div><div class="actions"><?php if($c['phone']):?><a class="btn btn-accent btn-sm" target="_blank" href="<?= e(whatsapp_url($c['phone'],'Olá, sobre entregas da empresa na LinkExpress.')) ?>">WhatsApp</a><?php endif;?><?php if($c['status']==='active'):?><form method="post" action="actions.php"><?=csrf_field()?><input type="hidden" name="action" value="unlink_company_courier"><input type="hidden" name="return_page" value="deliveries"><input type="hidden" name="courier_id" value="<?=(int)$c['user_id']?>"><button class="btn btn-danger btn-sm" data-confirm="Encerrar vínculo com este entregador? A conta dele continuará ativa na plataforma.">Encerrar vínculo</button></form><?php endif;?></div></div></article><?php endforeach;?></div></section><?php endif;?>
<section class="panel"><div class="panel-header"><div><h3>Entregas</h3><p>Entregas concluídas ficam bloqueadas e não podem ter o status alterado novamente.</p></div></div><div class="table-wrap"><table><thead><tr><th>Cliente/Empresa</th><th>Agendamento</th><th>Volumes</th><th>Distância</th><th>Autorização</th><th>Status</th><th>Ações</th></tr></thead><tbody><?php if(!$jobs):?><tr><td colspan="7"><div class="empty-state"><strong>Nenhuma entrega ativa</strong></div></td></tr><?php endif;foreach($jobs as $j):$late=$j['scheduled_at']&&strtotime($j['scheduled_at'])<time()&&!terminal_status($j['status']);$canSee=$j['authorization_status']==='approved';$deliveryReviewed=false;if($isClient&&$j['status']==='delivered'&&$j['assigned_courier_id']){$rv=db()->prepare("SELECT id FROM reviews WHERE reviewer_id=? AND target_type='delivery_courier' AND delivery_job_id=? LIMIT 1");$rv->execute([$u['id'],$j['id']]);$deliveryReviewed=(bool)$rv->fetchColumn();}?><tr class="<?= $late?'row-late':'' ?>"><td><strong><?= e($isClient?($j['company_name']??'Empresa'):(!empty($j['client_user_name'])?user_public_name(['username'=>$j['client_username']??'','public_id'=>$j['linked_client_public_id']??($j['client_public_id']??''),'name'=>$j['client_user_name']]):$j['client_name'])) ?></strong><small style="display:block"><?= e($j['client_public_id']?:'') ?></small><?php if($isCourier&&$canSee):?><small style="display:block;margin-top:5px"><strong>Endereço:</strong> <?= e($j['address']?:'Não informado') ?></small><?php if(!empty($j['client_phone'])):?><small style="display:block"><strong>Contato:</strong> <?= e(format_phone($j['client_phone'])) ?></small><?php endif;?><?php endif;?></td><td><?= $j['scheduled_at']?e(date('d/m/Y H:i',strtotime($j['scheduled_at']))):'Sem horário' ?><?= $late?'<span class="status status-overdue" style="margin-left:6px">Atrasada</span>':'' ?></td><td><?= e($j['package_description']?:'Não informado') ?><small style="display:block"><?= (int)$j['box_qty'] ?> caixa(s) • <?= (int)$j['sack_qty'] ?> saco(s)</small></td><td><?= number_format((float)$j['distance_km'],1,',','.') ?> km</td><td><?= status_badge($j['authorization_status']) ?></td><td><?= status_badge($j['status']) ?></td><td><div class="actions">
<?php if($isClient&&$j['authorization_status']==='pending'):?><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="respond_delivery_authorization"><input type="hidden" name="return_page" value="deliveries"><input type="hidden" name="id" value="<?= (int)$j['id'] ?>"><label class="notice" style="display:block;margin-bottom:8px"><input type="checkbox" name="always_visible" value="1"> Deixar meu endereço sempre visível para esta empresa</label><button class="btn btn-accent btn-sm" name="decision" value="approved">Autorizar</button><button class="btn btn-danger btn-sm" name="decision" value="rejected">Recusar</button></form><?php endif;?>
<?php if($isCompany&&$canSee&&!$j['assigned_courier_id']):?><button class="btn btn-secondary btn-sm" data-modal-open="#assign<?= (int)$j['id'] ?>">Atribuir</button><?php endif;?>
<?php if($isClient&&$j['status']==='delivered'&&$j['assigned_courier_id']):?><?php if($deliveryReviewed):?><span class="status status-active">★ Avaliada</span><?php else:?><button class="btn btn-secondary btn-sm" type="button" data-modal-open="#rateDelivery<?= (int)$j['id'] ?>">★ Avaliar entrega</button><?php endif;?><?php endif;?>
<?php if($isCourier&&$canSee):?><a class="btn btn-secondary btn-sm" target="_blank" href="<?= e(maps_link($j['address'],$j['latitude'],$j['longitude'])) ?>">Google Maps</a><a class="btn btn-accent btn-sm" target="_blank" href="<?= e(waze_link($j['address'],$j['latitude'],$j['longitude'])) ?>">Waze</a><?php if($j['client_phone']):?><a class="btn btn-secondary btn-sm" target="_blank" href="<?= e(whatsapp_url($j['client_phone'],'Olá, estou com sua entrega LinkExpress.')) ?>">WhatsApp</a><?php endif;?><?php if($j['client_telegram']):?><a class="btn btn-secondary btn-sm" target="_blank" href="<?= e(telegram_url($j['client_telegram'])) ?>">Telegram</a><?php endif;?><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="update_delivery_job"><input type="hidden" name="return_page" value="deliveries"><input type="hidden" name="id" value="<?= (int)$j['id'] ?>"><select name="status"><option value="accepted">Aceitar</option><option value="on_route">Em rota</option><option value="delivered">Entregue</option><option value="cancelled">Cancelar</option></select><button class="btn btn-primary btn-sm">Atualizar</button></form><?php endif;?></div></td></tr>
<?php if($isClient&&$j['status']==='delivered'&&$j['assigned_courier_id']&&!$deliveryReviewed):?><div class="modal" id="rateDelivery<?= (int)$j['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Avaliar entrega</h2><button class="close-btn" type="button" data-modal-close>×</button></div><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="save_review"><input type="hidden" name="return_page" value="deliveries"><input type="hidden" name="target_type" value="delivery_courier"><input type="hidden" name="target_id" value="<?= (int)$j['assigned_courier_id'] ?>"><input type="hidden" name="delivery_job_id" value="<?= (int)$j['id'] ?>"><div class="form-group"><label>Nota por estrelas</label><select name="rating"><option value="5">★★★★★ Excelente</option><option value="4">★★★★☆ Muito bom</option><option value="3">★★★☆☆ Bom</option><option value="2">★★☆☆☆ Regular</option><option value="1">★☆☆☆☆ Ruim</option></select></div><div class="form-group"><label>Comentário</label><textarea name="comment" placeholder="Como foi a entrega?"></textarea></div><div class="form-actions"><button class="btn btn-primary">Publicar avaliação</button></div></form></div></div><?php endif;?>
<?php if($isCompany):?><div class="modal" id="assign<?= (int)$j['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Atribuir entregador</h2><button class="close-btn" data-modal-close>×</button></div><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="assign_delivery_job"><input type="hidden" name="return_page" value="deliveries"><input type="hidden" name="id" value="<?= (int)$j['id'] ?>"><div class="form-group"><label>Entregador</label><select name="courier_id"><?php foreach($couriers as $c):if($c['status']!=='active')continue;?><option value="<?= (int)$c['user_id'] ?>"><?= e($c['name'].' — '.status_label($c['work_status'])) ?></option><?php endforeach;?></select></div><div class="form-actions"><button class="btn btn-primary">Atribuir</button></div></form></div></div><?php endif;?><?php endforeach;?></tbody></table></div></section>
<?php if($isCompany):?>
<?php if($courierCapacity['enabled']&&!$courierCapacity['reached']):?><div class="modal" id="linkCourierModal"><div class="modal-card"><div class="modal-head"><h2>Contratar entregador autônomo</h2><button class="close-btn" data-modal-close>×</button></div><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="link_company_courier"><input type="hidden" name="return_page" value="deliveries"><input type="hidden" name="company_id" value="<?= (int)$companyId ?>"><div class="form-group"><label>ID LinkExpress</label><input class="input" name="public_id" data-user-id-preview placeholder="LXU-AB7K-9Q2M" required><small data-user-preview-output>Digite o ID para confirmar o nome.</small></div><div class="form-actions"><button class="btn btn-primary">Adicionar</button></div></form></div></div>
<div class="modal" id="ownCourierModal"><div class="modal-card"><div class="modal-head"><h2>Cadastrar entregador próprio</h2><button class="close-btn" data-modal-close>×</button></div><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="create_company_courier"><input type="hidden" name="return_page" value="deliveries"><input type="hidden" name="company_id" value="<?= (int)$companyId ?>"><div class="form-grid"><div class="form-group"><label>Nome</label><input class="input" name="name" required></div><div class="form-group"><label>E-mail</label><input class="input" type="email" name="email" required></div><div class="form-group"><label>WhatsApp</label><input class="input" name="phone" data-phone-mask></div><div class="form-group"><label>Senha inicial</label><input class="input" name="password" value="123456"></div></div><div class="form-actions"><button class="btn btn-primary">Cadastrar</button></div></form></div></div>
<?php endif;?>
<div class="modal" id="deliveryModal"><div class="modal-card modal-large"><div class="modal-head"><h2>Agendar entrega</h2><button class="close-btn" data-modal-close>×</button></div><form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="create_delivery_job"><input type="hidden" name="return_page" value="deliveries"><input type="hidden" name="company_id" value="<?= (int)$companyId ?>"><div class="form-grid"><div class="form-group full"><label>ID LinkExpress do cliente</label><input class="input" name="client_public_id" data-user-id-preview data-user-preview-purpose="delivery" placeholder="LXU-AB7K-9Q2M" value="<?= e($prefillClientId) ?>"><small data-user-preview-output>Digite o ID para preencher nome, endereço e distância automaticamente.</small></div><div class="form-group"><label>Nome avulso</label><input class="input" name="client_name" data-delivery-client-name></div><div class="form-group"><label>WhatsApp avulso</label><input class="input" name="client_phone" data-phone-mask data-delivery-client-phone></div><div class="form-group full"><label>Endereço da entrega</label><input class="input" name="address" data-delivery-address data-address-autocomplete data-lat-field="latitude" data-lng-field="longitude"><input type="hidden" name="latitude"><input type="hidden" name="longitude"><small>Ao informar um cliente autorizado, o endereço cadastrado será preenchido automaticamente.</small></div><div class="form-group"><label>Data e hora</label><input class="input" type="datetime-local" name="scheduled_at"></div><div class="form-group"><label>Distância estimada (km)</label><input class="input" name="distance_km" data-delivery-distance inputmode="decimal"><small>Calculada entre a localização da empresa e o endereço do cliente.</small></div><div class="form-group full"><label>Volumes/mercadorias</label><input class="input" name="package_description" placeholder="Ex.: compras, documentos, materiais..."></div><div class="form-group"><label>Quantidade de caixas</label><input class="input" type="number" min="0" name="box_qty" value="0"></div><div class="form-group"><label>Quantidade de sacos</label><input class="input" type="number" min="0" name="sack_qty" value="0"></div><div class="form-group full"><label>Observações</label><textarea name="notes"></textarea></div></div><div class="form-actions"><button class="btn btn-primary">Criar entrega</button></div></form></div></div>
<?php endif;?>

<?php if($isCompany&&$prefillClientId!==''):?><script>document.addEventListener('DOMContentLoaded',function(){var trigger=document.querySelector('[data-modal-open="#deliveryModal"]');if(trigger)trigger.click();});</script><?php endif;?>
