<?php
$u=current_user();$id=(int)request('id',0);$code=trim((string)request('code',''));if($id<1&&$code===''){?><section class="panel"><div class="empty-state"><strong>Pedido não informado</strong>Use a área Pedidos para consultar pelo código.</div></section><?php return;}
$where=$id>0?'o.id=?':'upper(o.order_number)=upper(?)';$value=$id>0?$id:$code;
$q=db()->prepare("SELECT o.*,c.name company_name,c.logo company_logo,c.phone company_phone,cl.name client_name,cl.public_id client_public_id,cl.phone client_phone,d.name delivery_name,d.public_id delivery_public_id,d.phone delivery_phone,r.receipt_path auto_receipt_path FROM orders o JOIN companies c ON c.id=o.company_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 r ON r.source_type='order' AND r.source_id=o.id WHERE $where LIMIT 1");$q->execute([$value]);$o=$q->fetch();
if(!$o){?><section class="panel"><div class="empty-state"><strong>Pedido não encontrado</strong>Confira o código informado.</div></section><?php return;}
$linkedCompanyId=in_array((string)($u['role']??''),['company','employee'],true)?resolve_company_id_for_user($u):0;$allowed=is_admin()||($linkedCompanyId>0&&$linkedCompanyId===(int)$o['company_id'])||((int)$u['id']===(int)$o['client_id'])||((int)$u['id']===(int)($o['delivery_user_id']??0));if(!$allowed){http_response_code(403);exit('Sem permissão para visualizar este pedido.');}
$iq=db()->prepare('SELECT * FROM order_items WHERE order_id=? ORDER BY id');$iq->execute([(int)$o['id']]);$items=$iq->fetchAll();
$dq=db()->prepare('SELECT * FROM delivery_jobs WHERE order_id=? LIMIT 1');$dq->execute([(int)$o['id']]);$job=$dq->fetch();
?>
<section class="page-intro"><div><span class="mini-label">🧾 CONSULTA DO PEDIDO</span><h2><?=e($o['order_number'])?></h2><p>Informações completas vinculadas ao código do pedido.</p></div><div class="actions"><a class="btn btn-secondary" href="dashboard.php?page=orders">← Pedidos</a><?php if($o['auto_receipt_path']):?><a class="btn btn-primary" target="_blank" href="<?=e(generated_receipt_url((string)$o['auto_receipt_path'],'order',(int)$o['id']))?>">🧾 Comprovante PNG</a><?php endif;?></div></section>
<section class="stats-grid"><div class="stat-card"><div class="stat-top"><span>Total</span><span class="stat-icon">💰</span></div><strong><?=money($o['total'])?></strong><small><?=e(status_label($o['payment_status']))?></small></div><div class="stat-card"><div class="stat-top"><span>Status</span><span class="stat-icon">📦</span></div><strong><?=e(status_label($o['status']))?></strong><small><?=e(date('d/m/Y H:i',strtotime($o['created_at'])))?></small></div><div class="stat-card"><div class="stat-top"><span>Cliente</span><span class="stat-icon">👤</span></div><strong><?=e($o['client_name']?:'—')?></strong><small><?=e($o['client_public_id']?:'')?></small></div><div class="stat-card"><div class="stat-top"><span>Entregador</span><span class="stat-icon">🛵</span></div><strong><?=e($o['delivery_name']?:'Aguardando')?></strong><small><?=e($o['delivery_public_id']?:'')?></small></div></section>
<section class="panel"><div class="panel-header"><div><h3>Dados do pedido</h3></div></div><div class="form-grid"><div class="notice"><strong>Empresa</strong><br><?=e($o['company_name'])?></div><div class="notice"><strong>Forma de pagamento</strong><br><?=e(status_label($o['payment_method']))?> • <?=e(status_label($o['payment_status']))?></div><div class="notice full"><strong>Endereço</strong><br><?=e($o['address']?:'Retirada / não informado')?></div><?php if(($o['fulfillment_type']??'')==='pickup'&&!empty($o['pickup_scheduled_at'])):?><div class="notice full"><strong>🎂 Data e horário da retirada</strong><br><?=e(date('d/m/Y \à\s H:i',strtotime($o['pickup_scheduled_at'])))?></div><?php endif;?><div class="notice full"><strong>Observações</strong><br><?=e($o['notes']?:'Nenhuma')?></div></div></section>
<section class="panel"><div class="panel-header"><div><h3>Produtos / itens</h3></div></div><div class="table-wrap"><table><thead><tr><th>Item</th><th>Qtd.</th><th>Unitário</th><th>Total</th></tr></thead><tbody><?php foreach($items as $it):?><tr><td><strong><?=e($it['name'])?></strong></td><td><?=e((string)$it['qty'])?></td><td><?=money($it['price'])?></td><td><strong><?=money($it['total'])?></strong></td></tr><?php endforeach;?></tbody></table></div></section>
<?php if($job):?><section class="panel"><div class="panel-header"><div><h3>Ordem de entrega</h3></div><?=status_badge($job['status'])?></div><p><strong>Destino:</strong> <?=e($job['address'])?></p><p><strong>Volumes:</strong> <?=e($job['package_description']?:'—')?></p><p><strong>Agendamento:</strong> <?=e($job['scheduled_at']?date('d/m/Y H:i',strtotime($job['scheduled_at'])):'Sem horário')?></p></section><?php endif;?>
