<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();
$pageTitle='Restaurant Print Queue';
if(!function_exists('h')){function h($v):string{return htmlspecialchars((string)$v,ENT_QUOTES,'UTF-8');}}
if(($_SERVER['REQUEST_METHOD']??'GET')==='POST'){
    if(function_exists('verify_csrf')) verify_csrf();
    $id=(int)($_POST['id']??0);$action=$_POST['action']??'';
    if($id>0 && in_array($action,['printed','pending','failed'],true)){
        $pdo->prepare("UPDATE restaurant_print_jobs SET status=:s, printed_at=IF(:s='printed',NOW(),printed_at) WHERE id=:id")->execute([':s'=>$action,':id'=>$id]);
    }
    header('Location: restaurant_print_queue.php');exit;
}
$rows=$pdo->query("SELECT pj.*,ro.order_no,t.table_no FROM restaurant_print_jobs pj LEFT JOIN restaurant_orders ro ON ro.id=pj.restaurant_order_id LEFT JOIN restaurant_tables t ON t.id=ro.table_id ORDER BY FIELD(pj.status,'pending','failed','printing','printed'), pj.id DESC LIMIT 300")->fetchAll(PDO::FETCH_ASSOC);
require_once __DIR__.'/../../includes/header.php';
?>
<div class="hero-band" style="padding:12px 16px!important"><div class="hero-title">Restaurant Print Queue</div><div class="hero-subtitle">Kitchen, bar, dessert and master tickets for local print agent/QZ Tray.</div></div>
<div class="card panel-card"><div class="table-responsive"><table class="table table-modern mb-0"><thead><tr><th>ID</th><th>Order</th><th>Table</th><th>Role</th><th>Type</th><th>Status</th><th>Payload</th><th></th></tr></thead><tbody><?php foreach($rows as $r):?><tr><td><?php echo (int)$r['id'];?></td><td><?php echo h($r['order_no']);?></td><td><?php echo h($r['table_no']);?></td><td><?php echo h($r['printer_role']);?></td><td><?php echo h($r['job_type']);?></td><td><span class="badge text-bg-<?php echo $r['status']==='pending'?'warning':($r['status']==='printed'?'success':($r['status']==='failed'?'danger':'secondary'));?>"><?php echo h($r['status']);?></span></td><td><pre class="mb-0 small"><?php echo h($r['payload']);?></pre></td><td class="text-end"><form method="post" class="d-inline"><?php if(function_exists('csrf_field')) echo csrf_field();?><input type="hidden" name="id" value="<?php echo (int)$r['id'];?>"><button name="action" value="printed" class="btn btn-sm btn-success">Printed</button><button name="action" value="pending" class="btn btn-sm btn-outline-warning">Retry</button></form></td></tr><?php endforeach;?></tbody></table></div></div>
<style>.panel-card{border-radius:16px;box-shadow:0 12px 30px rgba(15,23,42,.07)}.table-modern thead th{font-size:.72rem;text-transform:uppercase;color:#64748b;background:#f8fafc}pre{white-space:pre-wrap}</style>
<?php require_once __DIR__.'/../../includes/footer.php'; ?>
