<?php
$u=current_user();$params=[];$where='1=0';$linkedCompanyId=0;$personalMode=request('mode')==='mine';$personalOrders=false;
if($personalMode){$where='o.client_id=?';$params[]=$u['id'];$personalOrders=true;}
elseif(is_role(['company','employee'])){
  $linkedCompanyId=resolve_company_id_for_user($u);
  if($linkedCompanyId>0){$where='o.company_id=?';$params[]=$linkedCompanyId;}else{$where='1=0';}
}
elseif(is_role('client')){$where='o.client_id=?';$params[]=$u['id'];$personalOrders=true;}
elseif(user_can_work_deliveries($u)){$where="(o.delivery_user_id=? OR (o.delivery_user_id IS NULL AND o.status IN ('preparing','ready')))";$params[]=$u['id'];}
else{$where='o.client_id=?';$params[]=$u['id'];$personalOrders=true;}
$sql="SELECT o.*,c.name company_name,c.owner_user_id,ou.pix_key company_pix_key,ou.pix_key_type company_pix_key_type,ou.pix_billing_enabled company_pix_billing_enabled,cl.name client_name,cl.username client_username,cl.public_id client_public_id,cl.home_lat client_home_lat,cl.home_lng client_home_lng,cl.phone client_phone,d.name delivery_name,d.username delivery_username,d.public_id delivery_public_id,d.phone delivery_phone,rc.receipt_path auto_receipt_path FROM orders o JOIN companies c ON c.id=o.company_id LEFT JOIN users ou ON ou.id=c.owner_user_id LEFT JOIN users cl ON cl.id=o.client_id LEFT JOIN users d ON d.id=o.delivery_user_id LEFT JOIN receipts rc ON rc.source_type='order' AND rc.source_id=o.id WHERE ".$where.' ORDER BY o.id DESC';
$q=db()->prepare($sql);$q->execute($params);$orders=$q->fetchAll();
$canUpdate=!$personalOrders&&(is_admin()||is_role(['company','employee'])||user_can_work_deliveries($u));
?>
<form class="filter-bar" method="get"><input type="hidden" name="page" value="order_detail"><div class="form-group" style="flex:1"><label>Consultar pelo código do pedido</label><input class="input" name="code" placeholder="Ex.: PED-000123" required></div><div class="actions"><button class="btn btn-primary">🔎 Ver informações</button></div></form>
<section class="panel">
  <div class="panel-header"><div><h2><?= $personalOrders?'Minhas compras':'Pedidos e entregas' ?></h2><p>Acompanhe o fluxo do pedido até a confirmação da entrega. Compras concluídas podem ser avaliadas por estrelas.</p></div><div class="actions"><?php if(!$personalOrders&&!is_admin()):?><a class="btn btn-secondary" href="dashboard.php?page=orders&mode=mine">🧾 Minhas compras</a><?php endif;?><?php if($personalOrders):?><a class="btn btn-primary" href="dashboard.php?page=catalog&mode=shop">+ Fazer pedido</a><?php endif;?></div></div>
  <div class="table-wrap"><table><thead><tr><th>Pedido</th><th>Empresa/Cliente</th><th>Total</th><th>Pagamento</th><th>Entregador</th><th>Status</th><th>Ação</th></tr></thead><tbody>
  <?php if(!$orders):?><tr><td colspan="7"><div class="empty-state"><strong>Nenhum pedido</strong>Os pedidos aparecerão aqui.</div></td></tr><?php endif;?>
  <?php foreach($orders as $o):
    $companyReviewed=false;$courierReviewed=false;$orderPay=calculate_platform_fee((int)($o['owner_user_id']??0),(float)$o['total'],'order',(int)$o['id']);
    $companyPixAllowed=!empty($o['company_pix_billing_enabled'])&&trim((string)($o['company_pix_key']??''))!=='';
    $orderPixKey=$companyPixAllowed?trim((string)$o['company_pix_key']):trim((string)setting('pix_key',''));
    $orderPixLabel=$companyPixAllowed?'Pix da empresa':'Pix da plataforma';
    $isGasOrder=company_is_gas((int)$o['company_id']);$orderCouriers=[];$canAssignCourier=(is_admin()||is_role(['company','employee']))&&($o['fulfillment_type']??'delivery')!=='pickup'&&$o['payment_status']==='paid'&&empty($o['delivery_user_id'])&&!in_array($o['status'],['delivered','cancelled'],true);
    if($canAssignCourier){$gcq=db()->prepare("SELECT cc.user_id,u.name,u.username,u.public_id,u.work_status 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' ORDER BY CASE WHEN u.work_status='available' THEN 0 WHEN u.work_status='on_route' THEN 1 WHEN u.work_status='busy' THEN 2 ELSE 3 END,u.name");$gcq->execute([(int)$o['company_id']]);$orderCouriers=$gcq->fetchAll();}
    if($personalOrders&&$o['status']==='delivered'){
      $rv=db()->prepare("SELECT target_type FROM reviews WHERE reviewer_id=? AND order_id=? AND target_type IN ('company','delivery_courier')");
      $rv->execute([$u['id'],$o['id']]);foreach($rv->fetchAll(PDO::FETCH_COLUMN) as $rt){if($rt==='company')$companyReviewed=true;if($rt==='delivery_courier')$courierReviewed=true;}
    }
  ?>
    <tr>
      <td><strong><?= e($o['order_number']) ?></strong><small style="display:block"><?= e(date('d/m/Y H:i',strtotime($o['created_at']))) ?></small><?php if(($o['fulfillment_type']??'')==='pickup'&&!empty($o['pickup_scheduled_at'])):?><small style="display:block;margin-top:4px">🎂 Retirada <?= e(date('d/m H:i',strtotime($o['pickup_scheduled_at']))) ?></small><?php endif;?></td>
      <td><strong><?= e($o['company_name']) ?></strong><small style="display:block"><?= e(!empty($o['client_name'])?user_public_name(['username'=>$o['client_username'],'public_id'=>$o['client_public_id'],'name'=>$o['client_name']]):'Cliente não informado') ?></small></td>
      <td><strong><?= money($orderPay['total']) ?></strong><?php if($orderPay['fee']>0):?><small style="display:block">Pedido <?= money($orderPay['base']) ?> • taxa <?= money($orderPay['fee']) ?> paga por <?= ($orderPay['fee_payer']??'client')==='provider'?'empresa':'cliente' ?></small><?php endif;?></td>
      <?php $payLabels=['pix'=>'Pix','card'=>'Cartão','cash'=>'Dinheiro'];$payKey=strtolower((string)$o['payment_method']); ?>
      <td><strong><?= e($payLabels[$payKey]??status_label($payKey)) ?></strong><br><?= status_badge($o['payment_status']) ?>
        <?php if(!empty($o['payment_proof'])&&(is_admin()||is_role(['company','employee','client']))):?><small style="display:block;margin-top:6px"><a href="<?= e(media_url($o['payment_proof'])) ?>" target="_blank" rel="noopener">📎 Ver comprovante Pix</a></small><?php endif;?>
        <?php if($o['payment_status']==='paid'&&!empty($o['payment_confirmed_at'])):?><small style="display:block;margin-top:4px">Confirmado em <?= e(date('d/m/Y H:i',strtotime($o['payment_confirmed_at']))) ?></small><?php endif;?><?php if(!empty($o['auto_receipt_path'])):?><small style="display:block;margin-top:6px"><a href="<?= e(generated_receipt_url((string)$o['auto_receipt_path'],'order',(int)$o['id'])) ?>" target="_blank">🧾 Acessar Comprovante</a></small><?php endif;?>
      </td>
      <td><?= e($o['delivery_name']?:'Aguardando') ?></td>
      <td><?= status_badge($o['status']) ?></td>
      <td><div class="actions">
        <a class="btn btn-secondary btn-sm" href="dashboard.php?page=order_detail&id=<?=(int)$o['id']?>">🔎 Detalhes</a><?php if($canUpdate&&!in_array($o['status'],['delivered','cancelled'],true)):?><button class="btn btn-secondary btn-sm" data-modal-open="#orderStatus<?= (int)$o['id'] ?>">Atualizar</button><?php else:?><span class="muted">Acompanhar</span><?php endif;?>
        <?php if($personalOrders&&strtolower((string)$o['payment_method'])==='pix'&&$o['payment_status']!=='paid'&&$o['status']!=='cancelled'):?><button class="btn btn-accent btn-sm" type="button" data-modal-open="#orderProof<?= (int)$o['id'] ?>">💠 <?= !empty($o['payment_proof'])?'Ver Pix / trocar comprovante':'Pagar com Pix' ?></button><?php endif;?>
        <?php if($canAssignCourier):?><button class="btn btn-primary btn-sm" type="button" data-modal-open="#assignOrderCourier<?= (int)$o['id'] ?>">🛵 Selecionar entregador</button><?php endif;?>
        <?php if((is_admin()||is_role(['company','employee']))&&$o['payment_status']!=='paid'&&$o['status']!=='cancelled'):?>
          <form method="post" action="actions.php" style="display:inline" onsubmit="return confirm('Confirmar que este pedido foi pago?');"><?= csrf_field() ?><input type="hidden" name="action" value="confirm_order_payment"><input type="hidden" name="return_page" value="orders"><input type="hidden" name="id" value="<?= (int)$o['id'] ?>"><button class="btn btn-accent btn-sm">✓ Confirmar pagamento</button></form>
          <?php if(!empty($o['payment_proof'])):?><form method="post" action="actions.php" style="display:inline" onsubmit="return confirm('Recusar este comprovante?');"><?= csrf_field() ?><input type="hidden" name="action" value="reject_order_payment_proof"><input type="hidden" name="return_page" value="orders"><input type="hidden" name="id" value="<?= (int)$o['id'] ?>"><button class="btn btn-danger btn-sm">Recusar comprovante</button></form><?php endif;?>
        <?php endif;?>
        <?php if(user_can_work_deliveries($u)&&(int)($o['delivery_user_id']??0)===(int)$u['id']&&$o['payment_status']!=='paid'&&$o['status']!=='cancelled'):?><form method="post" action="actions.php" style="display:inline" onsubmit="return confirm('Confirmar que o cliente efetuou o pagamento?');"><?= csrf_field() ?><input type="hidden" name="action" value="confirm_order_payment"><input type="hidden" name="return_page" value="orders"><input type="hidden" name="id" value="<?= (int)$o['id'] ?>"><button class="btn btn-accent btn-sm">💵 Cliente pagou</button></form><?php endif;?>
        <?php if($personalOrders&&$o['status']==='delivered'):?>
          <?php if($companyReviewed):?><span class="status status-active">★ Compra avaliada</span><?php else:?><button class="btn btn-secondary btn-sm" type="button" data-modal-open="#rateOrder<?= (int)$o['id'] ?>">★ Avaliar compra</button><?php endif;?>
          <?php if($o['delivery_user_id']):?><?php if($courierReviewed):?><span class="status status-active">★ Entrega avaliada</span><?php else:?><button class="btn btn-secondary btn-sm" type="button" data-modal-open="#rateOrderCourier<?= (int)$o['id'] ?>">★ Avaliar entrega</button><?php endif;?><?php endif;?>
        <?php endif;?>
      </div></td>
    </tr>

    <?php if($canUpdate&&!in_array($o['status'],['delivered','cancelled'],true)):?>
      <div class="modal" id="orderStatus<?= (int)$o['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Pedido <?= e($o['order_number']) ?></h2><button class="close-btn" data-modal-close>×</button></div>
        <div class="notice"><strong>Tipo:</strong> <?= e($o['fulfillment_type']==='pickup'?'Retirada no estabelecimento':'Entrega') ?><?php if($o['fulfillment_type']==='pickup'&&!empty($o['pickup_scheduled_at'])):?><br><strong>🎂 Retirada agendada:</strong> <?= e(date('d/m/Y \à\s H:i',strtotime($o['pickup_scheduled_at']))) ?><?php endif;?><br><strong>Entrega:</strong> <?= e($o['address']?:'Local não informado') ?><br><strong>Observações:</strong> <?= e($o['notes']?:'Nenhuma') ?></div>
        <?php if(user_can_work_deliveries($u)&&$o['fulfillment_type']!=='pickup'):?><div class="actions" style="margin-top:12px"><a class="btn btn-secondary btn-sm" target="_blank" rel="noopener" href="<?= e(maps_link($o['address'],$o['client_home_lat'],$o['client_home_lng'])) ?>">Google Maps</a><a class="btn btn-accent btn-sm" target="_blank" rel="noopener" href="<?= e(waze_link($o['address'],$o['client_home_lat'],$o['client_home_lng'])) ?>">Waze</a><?php if($o['client_phone']):?><a class="btn btn-secondary btn-sm" target="_blank" href="<?= e(whatsapp_url($o['client_phone'],'Olá, sou o entregador do seu pedido '.$o['order_number'].'.')) ?>">WhatsApp</a><?php endif;?></div><?php endif;?>
        <form method="post" action="actions.php" style="margin-top:16px"><?= csrf_field() ?><input type="hidden" name="action" value="update_order_status"><input type="hidden" name="return_page" value="orders"><input type="hidden" name="id" value="<?= (int)$o['id'] ?>"><div class="form-group"><label>Novo status</label><select name="status"><?php foreach(['received'=>'Recebido','preparing'=>'Em preparo','ready'=>'Pronto','on_route'=>'Saiu para entrega','delivered'=>'Entregue','cancelled'=>'Cancelado'] as $k=>$v):?><option value="<?= e($k) ?>"<?= selected($o['status'],$k) ?>><?= e($v) ?></option><?php endforeach;?></select></div><div class="form-actions"><button class="btn btn-primary">Salvar status</button></div></form>
      </div></div>
    <?php endif;?>

    <?php if($canAssignCourier):?>
      <div class="modal" id="assignOrderCourier<?= (int)$o['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Selecionar entregador</h2><button class="close-btn" type="button" data-modal-close>×</button></div>
        <div class="notice"><strong>Pedido pago:</strong> <?= e($o['order_number']) ?><br>Ao selecionar, a ordem de entrega será vinculada ao pedido e enviada ao entregador com cliente, endereço e produtos.</div>
        <?php if(!$orderCouriers):?><div class="empty-state"><strong>Nenhum entregador ativo</strong>Cadastre ou vincule um entregador na área Entregadores e Entregas.</div><div class="form-actions"><a class="btn btn-primary" href="dashboard.php?page=deliveries<?= is_admin()?'&company_id='.(int)$o['company_id']:'' ?>">Gerenciar entregadores</a></div><?php else:?>
        <form method="post" action="actions.php"><?= csrf_field() ?><input type="hidden" name="action" value="assign_order_courier"><input type="hidden" name="return_page" value="orders"><input type="hidden" name="id" value="<?= (int)$o['id'] ?>"><div class="form-group"><label>Entregador da empresa</label><select name="courier_id" required><?php foreach($orderCouriers as $gc):?><option value="<?= (int)$gc['user_id'] ?>"><?= e(user_public_name($gc).' — '.status_label($gc['work_status'])) ?></option><?php endforeach;?></select></div><div class="form-actions"><button class="btn btn-primary">Enviar ordem de entrega</button></div></form><?php endif;?>
      </div></div>
    <?php endif;?>

    <?php if($personalOrders&&strtolower((string)$o['payment_method'])==='pix'&&$o['payment_status']!=='paid'&&$o['status']!=='cancelled'):?>
      <div class="modal" id="orderProof<?= (int)$o['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Comprovante Pix</h2><button class="close-btn" type="button" data-modal-close>×</button></div>
        <div class="notice"><strong>Pedido:</strong> <?= e($o['order_number']) ?><br><strong>Produtos/entrega:</strong> <?= money($orderPay['base']) ?><?php if($orderPay['fee']>0):?><br><strong>Taxa da plataforma:</strong> <?= money($orderPay['fee']) ?> <small>(paga por <?= ($orderPay['fee_payer']??'client')==='provider'?'empresa':'cliente' ?>)</small><?php endif;?><br><strong>Total a pagar:</strong> <?= money($orderPay['total']) ?><?php if($orderPixKey!==''):?><hr style="border:0;border-top:1px solid var(--border);margin:12px 0"><strong>💠 <?= e($orderPixLabel) ?>:</strong><br><span class="pix-value"><?= e($orderPixKey) ?></span><div class="actions pix-copy-actions"><button type="button" class="btn btn-accent btn-sm" data-copy-text="<?= e($orderPixKey) ?>">📋 Copiar chave Pix</button></div><?php else:?><br><strong>⚠ Pix ainda não configurado.</strong><br><small>A empresa e a plataforma ainda não possuem uma chave Pix disponível para este pedido.</small><?php endif;?><br>Após pagar, envie a imagem ou PDF do comprovante. A empresa ainda precisará confirmar o pagamento.</div>
        <?php if(!empty($o['payment_proof'])):?><div class="actions" style="margin:12px 0"><a class="btn btn-secondary btn-sm" target="_blank" rel="noopener" href="<?= e(media_url($o['payment_proof'])) ?>">Ver comprovante atual</a></div><?php endif;?>
        <form method="post" action="actions.php" enctype="multipart/form-data"><?= csrf_field() ?><input type="hidden" name="action" value="upload_order_payment_proof"><input type="hidden" name="return_page" value="orders"><input type="hidden" name="id" value="<?= (int)$o['id'] ?>"><div class="form-group"><label>Comprovante do Pix</label><input class="input" type="file" name="payment_proof_file" accept="image/jpeg,image/png,image/webp,application/pdf" required><small>JPG, PNG, WebP ou PDF.</small></div><div class="form-actions"><button class="btn btn-primary">Enviar comprovante</button></div></form>
      </div></div>
    <?php endif;?>

    <?php if($personalOrders&&$o['status']==='delivered'&&!$companyReviewed):?>
      <div class="modal" id="rateOrder<?= (int)$o['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Avaliar compra</h2><button class="close-btn" 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="orders"><input type="hidden" name="target_type" value="company"><input type="hidden" name="target_id" value="<?= (int)$o['company_id'] ?>"><input type="hidden" name="order_id" value="<?= (int)$o['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 sua compra?"></textarea></div>
          <div class="form-actions"><button class="btn btn-primary">Publicar avaliação</button></div>
        </form>
      </div></div>
    <?php endif;?>

    <?php if($personalOrders&&$o['status']==='delivered'&&$o['delivery_user_id']&&!$courierReviewed):?>
      <div class="modal" id="rateOrderCourier<?= (int)$o['id'] ?>"><div class="modal-card"><div class="modal-head"><h2>Avaliar 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="save_review"><input type="hidden" name="return_page" value="orders"><input type="hidden" name="target_type" value="delivery_courier"><input type="hidden" name="target_id" value="<?= (int)$o['delivery_user_id'] ?>"><input type="hidden" name="order_id" value="<?= (int)$o['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 endforeach;?>
  </tbody></table></div>
</section>
