<?php
session_start();
$page_title = 'Order History';
$active_nav = 'order_history';
include("includes/header.php");

$status_f  = $_GET['status']    ?? 'all';
$date_from = $_GET['date_from'] ?? date('Y-m-01');
$date_to   = $_GET['date_to']   ?? date('Y-m-d');
$search    = trim($_GET['search'] ?? '');

$q  = "SELECT o.*,u.name as customer_name, (SELECT COUNT(*) FROM order_items WHERE order_id=o.id) as item_count FROM orders o LEFT JOIN users u ON o.user_id=u.id WHERE o.restaurant_id=?";
$pa = [$__rid]; $ty = "i";
if ($status_f !== 'all') { $q .= " AND o.order_status=?"; $pa[] = $status_f; $ty .= "s"; }
$q .= " AND DATE(o.created_at) BETWEEN ? AND ?"; $pa[] = $date_from; $pa[] = $date_to; $ty .= "ss";
if ($search) { $q .= " AND (u.name LIKE ? OR o.id LIKE ?)"; $s="%$search%"; $pa[]=$s; $pa[]=$s; $ty.="ss"; }
$q .= " ORDER BY o.created_at DESC";
$st = $conn->prepare($q); $st->bind_param($ty,...$pa); $st->execute();
$orders = $st->get_result();

// Period summary
$sum = $conn->prepare("SELECT COUNT(*) as cnt, COALESCE(SUM(total_amount),0) as rev FROM orders WHERE restaurant_id=? AND payment_status='paid' AND DATE(created_at) BETWEEN ? AND ?");
$sum->bind_param("iss",$__rid,$date_from,$date_to); $sum->execute();
$sum = $sum->get_result()->fetch_assoc();

$sc = ['pending'=>'badge-warning','accepted'=>'badge-primary','preparing'=>'badge-purple','ready'=>'badge-success','served'=>'badge-info','completed'=>'badge-success','cancelled'=>'badge-error'];
?>

<div style="display:flex;align-items:flex-start;justify-content:space-between;margin-bottom:24px;flex-wrap:wrap;gap:12px">
  <div>
    <h1 style="font-size:1.4rem;font-weight:800;letter-spacing:-.03em;margin-bottom:3px">Order History</h1>
    <p style="color:var(--text-muted);font-size:.875rem"><?php echo htmlspecialchars($__rest_name); ?> — all orders</p>
  </div>
  <form method="GET" style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
    <input type="hidden" name="status" value="<?php echo htmlspecialchars($status_f); ?>">
    <div style="position:relative">
      <svg style="position:absolute;left:10px;top:50%;transform:translateY(-50%);width:14px;height:14px;stroke:var(--text-light);fill:none" viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
      <input type="text" name="search" placeholder="Customer or order #" value="<?php echo htmlspecialchars($search); ?>"
             style="height:38px;border:1.5px solid var(--border);border-radius:10px;background:var(--white);padding:0 12px 0 32px;font-size:.82rem;font-family:var(--font);outline:none;width:180px">
    </div>
    <input type="date" name="date_from" value="<?php echo $date_from; ?>" style="height:38px;border:1.5px solid var(--border);border-radius:10px;background:var(--white);padding:0 10px;font-size:.82rem;font-family:var(--font);outline:none">
    <input type="date" name="date_to"   value="<?php echo $date_to; ?>"   style="height:38px;border:1.5px solid var(--border);border-radius:10px;background:var(--white);padding:0 10px;font-size:.82rem;font-family:var(--font);outline:none">
    <button type="submit" class="btn btn-primary btn-sm">Filter</button>
    <a href="order_history.php" class="btn btn-secondary btn-sm">Reset</a>
  </form>
</div>

<!-- Period summary -->
<div class="grid-2" style="margin-bottom:20px">
  <div class="card" style="padding:16px 20px;display:flex;align-items:center;gap:14px">
    <div style="width:40px;height:40px;background:var(--success-bg);border-radius:12px;display:flex;align-items:center;justify-content:center;flex-shrink:0">
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="var(--success)" stroke-width="2" stroke-linecap="round"><path d="M7 20V4l10 16V4M4 10h16M4 14h16"/></svg>
    </div>
    <div><div style="font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:3px">Revenue (Period)</div>
    <div style="font-size:1.25rem;font-weight:800;color:var(--success)">₦<?php echo number_format($sum['rev'],0); ?></div></div>
  </div>
  <div class="card" style="padding:16px 20px;display:flex;align-items:center;gap:14px">
    <div style="width:40px;height:40px;background:var(--primary-bg);border-radius:12px;display:flex;align-items:center;justify-content:center;flex-shrink:0">
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="var(--primary)" stroke-width="2" stroke-linecap="round"><path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2"/><rect x="9" y="3" width="6" height="4" rx="1"/></svg>
    </div>
    <div><div style="font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--text-muted);margin-bottom:3px">Paid Orders</div>
    <div style="font-size:1.25rem;font-weight:800;color:var(--primary)"><?php echo $sum['cnt']; ?></div></div>
  </div>
</div>

<!-- Status tabs -->
<div style="display:flex;gap:6px;margin-bottom:16px;flex-wrap:wrap">
  <?php foreach (['all'=>'All','pending'=>'Pending','accepted'=>'Accepted','preparing'=>'Preparing','ready'=>'Ready','served'=>'Served','completed'=>'Completed','cancelled'=>'Cancelled'] as $k=>$l):
    $extra = http_build_query(array_filter(['date_from'=>$date_from,'date_to'=>$date_to,'search'=>$search]));
  ?>
  <a href="?status=<?php echo $k; ?><?php echo $extra?"&$extra":''; ?>"
     class="btn btn-sm <?php echo $status_f===$k?'btn-primary':'btn-secondary'; ?>"><?php echo $l; ?></a>
  <?php endforeach; ?>
</div>

<div class="card">
  <?php if ($orders->num_rows === 0): ?>
    <div style="padding:56px;text-align:center;color:var(--text-muted)">
      <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="var(--border)" stroke-width="1.5" stroke-linecap="round" style="margin:0 auto 14px;display:block"><path d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2"/><rect x="9" y="3" width="6" height="4" rx="1"/></svg>
      <p style="font-weight:700;margin-bottom:4px">No orders found</p>
      <p style="font-size:.82rem">Try adjusting the date range or filters</p>
    </div>
  <?php else: ?>
    <div class="table-scroll">
<table class="data-table">
    <thead><tr><th>Order</th><th>Customer</th><th>Table</th><th>Items</th><th>Amount</th><th>Payment</th><th>Status</th><th>Date</th></tr></thead>
    <tbody>
    <?php while ($o = $orders->fetch_assoc()): ?>
    <tr>
      <td style="font-weight:700;color:var(--primary)">#<?php echo str_pad($o['id'],4,'0',STR_PAD_LEFT); ?></td>
      <td style="font-size:.83rem"><?php echo htmlspecialchars($o['customer_name'] ?? 'Guest'); ?></td>
      <td style="font-size:.82rem"><?php $ohl=trim((string)($o['table_label']??'')); echo $ohl!==''?htmlspecialchars($ohl):($o['table_number']?'T-'.htmlspecialchars($o['table_number']):'—'); ?></td>
      <td style="font-weight:600;text-align:center"><?php echo $o['item_count']; ?></td>
      <td style="font-weight:700">₦<?php echo number_format($o['total_amount'],0); ?></td>
      <td><span class="badge <?php echo $o['payment_status']==='paid'?'badge-success':'badge-warning'; ?>"><?php echo ucfirst($o['payment_status']); ?></span></td>
      <td><span class="badge <?php echo $sc[$o['order_status']]??'badge-muted'; ?>"><?php echo ucfirst($o['order_status']); ?></span></td>
      <td style="font-size:.78rem;color:var(--text-muted);white-space:nowrap"><?php echo date('M j, Y g:i A', strtotime($o['created_at'])); ?></td>
    </tr>
    <?php endwhile; ?>
    </tbody>
  </table>
</div>
  <?php endif; ?>
</div>

<?php include("incl