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

$uid = (int)$_SESSION['user_id'];
$range = $_GET['range'] ?? 'all';   // all | 30d | month

$base = "SELECT o.*, r.name AS restaurant_name, r.logo AS restaurant_logo
         FROM orders o LEFT JOIN restaurants r ON o.restaurant_id = r.id
         WHERE o.user_id = ?";
$params = [$uid]; $types = "i";

if ($range === '30d') {
    $base .= " AND o.created_at >= (NOW() - INTERVAL 30 DAY)";
} elseif ($range === 'month') {
    $base .= " AND YEAR(o.created_at) = YEAR(NOW()) AND MONTH(o.created_at) = MONTH(NOW())";
}
$base .= " ORDER BY o.created_at DESC";

$stmt = $conn->prepare($base);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$orders = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

function oh_badge($s) {
    $map = [
        'pending'   => ['Pending',   'var(--warning)', 'var(--warning-bg)'],
        'confirmed' => ['Confirmed', 'var(--primary)', 'var(--primary-bg)'],
        'preparing' => ['Preparing', '#7C3AED',        '#F3E8FF'],
        'ready'     => ['Ready',     'var(--primary)', 'var(--primary-bg)'],
        'completed' => ['Completed', 'var(--success)', 'var(--success-bg)'],
        'cancelled' => ['Cancelled', 'var(--error)',   'var(--error-bg)'],
    ];
    return $map[$s] ?? [ucfirst($s), 'var(--text-muted)', 'var(--bg)'];
}

$grouped = [];
foreach ($orders as $o) {
    $grouped[date('F Y', strtotime($o['created_at']))][] = $o;
}
?>

<style>
.app-topbar { display: none; }
.main-content { padding-top: calc(env(safe-area-inset-top) + 6px); }
.oh-wrap { max-width: 600px; margin: 0 auto; }

.sub-topbar { display: flex; align-items: center; justify-content: space-between; padding: 4px 2px 18px; }
.sub-topbar-left { display: flex; align-items: center; gap: 12px; }
.sub-topbar .sub-back { width: 36px; height: 36px; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: var(--primary); background: var(--primary-bg); flex-shrink: 0; }
.sub-topbar .sub-title { font-size: 1.15rem; font-weight: 800; letter-spacing: -.02em; color: var(--text); }
.sub-topbar .icon-btn { color: var(--primary); }

.oh-pills { display: flex; gap: 8px; margin-bottom: 20px; overflow-x: auto; -webkit-overflow-scrolling: touch; scrollbar-width: none; padding-bottom: 2px; }
.oh-pills::-webkit-scrollbar { display: none; }
.oh-pill { padding: 9px 18px; border-radius: 30px; font-size: .84rem; font-weight: 700; border: 1.5px solid var(--border); background: #fff; color: var(--text-muted); white-space: nowrap; flex-shrink: 0; text-decoration: none; }
.oh-pill.active { background: var(--primary); color: #fff; border-color: var(--primary); }

.oh-month { font-size: .68rem; font-weight: 800; letter-spacing: .1em; text-transform: uppercase; color: var(--text-light); margin: 18px 4px 12px; }

.oh-card { display: block; background: #fff; border-radius: 18px; border: 1px solid var(--border); box-shadow: 0 4px 18px rgba(15,23,42,.06); padding: 14px; margin-bottom: 14px; text-decoration: none; color: var(--text); }
.oh-card:active { background: var(--bg); }
.oh-top { display: flex; align-items: center; gap: 14px; }
.oh-thumb { width: 52px; height: 52px; border-radius: 14px; overflow: hidden; flex-shrink: 0; background: linear-gradient(135deg, var(--primary-bg), #dce8fb); display: flex; align-items: center; justify-content: center; font-weight: 800; color: var(--primary); font-size: 1.1rem; }
.oh-thumb img { width: 100%; height: 100%; object-fit: cover; }
.oh-info { flex: 1; min-width: 0; }
.oh-name { font-weight: 700; font-size: .95rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.oh-date { font-size: .76rem; color: var(--text-muted); margin-top: 3px; }
.oh-badge { font-size: .7rem; font-weight: 800; padding: 5px 11px; border-radius: 20px; flex-shrink: 0; }
.oh-foot { display: flex; align-items: center; justify-content: space-between; margin-top: 12px; padding-top: 12px; border-top: 1px solid var(--border); }
.oh-amt { font-weight: 800; font-size: .95rem; color: var(--primary); }
.oh-details { font-size: .82rem; font-weight: 700; color: var(--primary); display: flex; align-items: center; gap: 4px; }

.oh-empty { text-align: center; padding: 60px 24px; }
.oh-empty .ee-ic { width: 76px; height: 76px; border-radius: 50%; background: var(--primary-bg); display: flex; align-items: center; justify-content: center; margin: 0 auto 18px; color: var(--primary); }
.oh-empty h3 { font-size: 1.05rem; font-weight: 800; margin-bottom: 6px; }
.oh-empty p { font-size: .86rem; color: var(--text-muted); margin-bottom: 20px; line-height: 1.5; }
.oh-empty a.cta { display: inline-flex; align-items: center; gap: 8px; background: var(--primary); color: #fff; font-weight: 700; padding: 12px 22px; border-radius: 14px; box-shadow: 0 6px 18px rgba(34,90,227,.3); text-decoration: none; }
</style>

<div class="oh-wrap">

  <div class="sub-topbar">
    <div class="sub-topbar-left">
      <a href="profile.php" class="sub-back" aria-label="Back" onclick="return goBack(event)">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M19 12H5m0 0l7 7M5 12l7-7"/></svg>
      </a>
      <span class="sub-title">Order History</span>
    </div>
    <a href="help_center.php" class="icon-btn" title="Help">
      <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 115.83 1c0 2-3 2-3 4"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
    </a>
  </div>

  <?php if (empty($orders) && $range === 'all'): ?>
    <div class="oh-empty">
      <div class="ee-ic"><svg width="34" height="34" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="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"/><path d="M9 12h6M9 16h4"/></svg></div>
      <h3>No past orders</h3>
      <p>Orders you complete will show up here.</p>
      <a href="scan.php" class="cta">
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M3 7V5a2 2 0 012-2h2M17 3h2a2 2 0 012 2v2M21 17v2a2 2 0 01-2 2h-2M7 21H5a2 2 0 01-2-2v-2"/><rect x="7" y="7" width="10" height="10" rx="1"/></svg>
        Scan &amp; Order
      </a>
    </div>
  <?php else: ?>
    <div class="oh-pills">
      <a href="?range=all"   class="oh-pill <?php echo $range==='all'   ? 'active' : ''; ?>">All Time</a>
      <a href="?range=30d"   class="oh-pill <?php echo $range==='30d'   ? 'active' : ''; ?>">Last 30 Days</a>
      <a href="?range=month" class="oh-pill <?php echo $range==='month' ? 'active' : ''; ?>">This Month</a>
    </div>

    <?php if (empty($orders)): ?>
      <div class="oh-empty">
        <div class="ee-ic"><svg width="34" height="34" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="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>
        <h3>Nothing in this period</h3>
        <p>Try a different time range.</p>
      </div>
    <?php else: foreach ($grouped as $month => $list): ?>
      <div class="oh-month"><?php echo strtoupper($month); ?></div>
      <?php foreach ($list as $o):
        [$blabel, $bcolor, $bbg] = oh_badge($o['order_status']);
        $rname = $o['restaurant_name'] ?? 'Restaurant';
        $logo_path = $o['restaurant_logo'] ? '../restaurantadmin/uploads/logos/' . $o['restaurant_logo'] : null;
        $has_logo  = $logo_path && file_exists(dirname(__FILE__) . '/' . $logo_path);
      ?>
      <a href="order_detail.php?id=<?php echo $o['id']; ?>" class="oh-card">
        <div class="oh-top">
          <div class="oh-thumb">
            <?php if ($has_logo): ?><img src="<?php echo htmlspecialchars($logo_path); ?>" alt=""><?php else: echo htmlspecialchars(strtoupper(substr($rname,0,1))); endif; ?>
          </div>
          <div class="oh-info">
            <div class="oh-name"><?php echo htmlspecialchars($rname); ?></div>
            <div class="oh-date"><?php echo date('M j, H:i', strtotime($o['created_at'])); ?><?php echo $o['table_number'] ? ' · Table '.htmlspecialchars($o['table_number']) : ''; ?></div>
          </div>
          <span class="oh-badge" style="color:<?php echo $bcolor; ?>;background:<?php echo $bbg; ?>"><?php echo $blabel; ?></span>
        </div>
        <div class="oh-foot">
          <span class="oh-amt">₦<?php echo number_format($o['total_amount'], 2); ?></span>
          <span class="oh-details">Details
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><polyline points="9 18 15 12 9 6"/></svg>
          </span>
        </div>
      </a>
      <?php endforeach; ?>
    <?php endforeach; endif; ?>
  <?php endif; ?>
</div>

<?php include("includes/footer.php"); ?>
