<?php
require_once __DIR__ . '/auth_guard.php';
require_once __DIR__ . '/../backend/config/database.php';

$db     = getDB();
$userId = $_SESSION['user_id'];
$userName = $_SESSION['user_name'];

// Filter
$filter = $_GET['status'] ?? 'all';
$allowed = ['all','pending','confirmed','out_for_delivery','delivered','cancelled'];
if(!in_array($filter, $allowed)) $filter = 'all';

if($filter === 'all'){
    $stmt = $db->prepare("SELECT o.*,GROUP_CONCAT(oi.product_name ORDER BY oi.id SEPARATOR ', ') AS items FROM orders o LEFT JOIN order_items oi ON o.id=oi.order_id WHERE o.user_id=? GROUP BY o.id ORDER BY o.created_at DESC");
    $stmt->execute([$userId]);
} else {
    $stmt = $db->prepare("SELECT o.*,GROUP_CONCAT(oi.product_name ORDER BY oi.id SEPARATOR ', ') AS items FROM orders o LEFT JOIN order_items oi ON o.id=oi.order_id WHERE o.user_id=? AND o.status=? GROUP BY o.id ORDER BY o.created_at DESC");
    $stmt->execute([$userId, $filter]);
}
$orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Count per status
$countStmt = $db->prepare("SELECT status, COUNT(*) as cnt FROM orders WHERE user_id=? GROUP BY status");
$countStmt->execute([$userId]);
$counts = ['all'=>0];
foreach($countStmt->fetchAll(PDO::FETCH_ASSOC) as $r){
    $counts[$r['status']] = (int)$r['cnt'];
    $counts['all'] += (int)$r['cnt'];
}

$currentPage = 'orders';
$pageTitle   = 'My Orders';

$statusSteps = ['pending','confirmed','out_for_delivery','delivered'];
function statusStyle($s){
    $map=['pending'=>['bg'=>'#fef3c7','color'=>'#d97706'],'confirmed'=>['bg'=>'#dbeafe','color'=>'#2563eb'],'out_for_delivery'=>['bg'=>'#ede9fe','color'=>'#7c3aed'],'delivered'=>['bg'=>'#d1fae5','color'=>'#059669'],'cancelled'=>['bg'=>'#fee2e2','color'=>'#dc2626']];
    return $map[$s]??['bg'=>'#f1f5f9','color'=>'#475569'];
}
$stepIdx = ['pending'=>0,'confirmed'=>1,'out_for_delivery'=>2,'delivered'=>3];

ob_start();
?>
<style>
.customer-sidebar{width:220px;flex-shrink:0;background:#fff;border-radius:14px;padding:1.25rem .875rem;border:1px solid #e8ecf0;position:sticky;top:80px;align-self:flex-start}
.sidebar-link{display:flex;align-items:center;gap:.75rem;padding:.65rem .875rem;border-radius:8px;color:#64748b;font-weight:500;font-size:.875rem;transition:all .18s;text-decoration:none}
.sidebar-link:hover{background:#f8fafc;color:#0f172a;}
.sidebar-link.active{background:#0f172a;color:#fff;font-weight:600;}
.sidebar-link.active svg{stroke:#f97316;}
.sidebar-link svg{width:16px;height:16px;stroke:currentColor;fill:none;flex-shrink:0;opacity:.7;}
.sidebar-link:hover svg,.sidebar-link.active svg{opacity:1;}
.filter-tab{padding:.5rem 1rem;border-radius:50px;font-size:.82rem;font-weight:600;cursor:pointer;border:1.5px solid #e2e8f0;background:#fff;color:#475569;transition:all .15s;text-decoration:none;display:inline-block}
.filter-tab.active{background:#0f172a;color:#fff;border-color:transparent}
@media(max-width:900px){.customer-layout{flex-direction:column!important}.customer-sidebar{width:100%!important;position:static!important}}
</style>
<?php
$extraStyles = ob_get_clean();
require_once __DIR__ . '/../backend/includes/head.php';
require_once __DIR__ . '/../backend/includes/navbar.php';
echo $extraStyles;
?>
<div style="max-width:1200px;margin:0 auto;padding:2rem 1.5rem;display:flex;gap:2rem;align-items:flex-start" class="customer-layout">
  <aside class="customer-sidebar">
    <div style="text-align:center;padding:.75rem 0 1.25rem;border-bottom:1px solid #f1f5f9;margin-bottom:1rem">
      <div style="width:52px;height:52px;border-radius:50%;background:linear-gradient(135deg,#0f172a,#1e293b);display:flex;align-items:center;justify-content:center;color:#f97316;font-weight:900;font-size:1.2rem;margin:0 auto .5rem"><?= strtoupper(substr($userName,0,1)) ?></div>
      <div style="font-weight:700;font-size:.875rem;color:#0f172a"><?= htmlspecialchars($userName) ?></div>
      <div style="color:#94a3b8;font-size:.72rem">Customer Account</div>
    </div>
    <nav style="display:flex;flex-direction:column;gap:.125rem">
      <a href="/stile-lpg/customer/dashboard.php" class="sidebar-link">
        <svg viewBox="0 0 24 24" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="9" rx="1"/><rect x="14" y="3" width="7" height="5" rx="1"/><rect x="14" y="12" width="7" height="9" rx="1"/><rect x="3" y="16" width="7" height="5" rx="1"/></svg>
        <span>Dashboard</span>
      </a>
      <a href="/stile-lpg/customer/orders.php" class="sidebar-link active">
        <svg viewBox="0 0 24 24" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M6 2 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4z"/><line x1="3" y1="6" x2="21" y2="6"/><path d="M16 10a4 4 0 0 1-8 0"/></svg>
        <span>My Orders</span>
      </a>
      <a href="/stile-lpg/customer/profile.php" class="sidebar-link">
        <svg viewBox="0 0 24 24" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
        <span>Profile</span>
      </a>
    </nav>
  </aside>

  <main style="flex:1;min-width:0">
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:1.75rem;flex-wrap:wrap;gap:1rem">
      <div>
        <h1 style="font-weight:900;font-size:1.5rem;color:#0f172a;margin-bottom:.25rem">My Orders</h1>
        <p style="color:#64748b;font-size:.875rem"><?= $counts['all'] ?> order<?= $counts['all']!==1?'s':'' ?> total</p>
      </div>
      <a href="/stile-lpg/services.php" class="btn-primary"><svg width="15" height="15" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24" style="vertical-align:middle"><path d="M12 5v14M5 12h14"/></svg> New Order</a>
    </div>

    <!-- Filter tabs -->
    <div style="display:flex;flex-wrap:wrap;gap:.5rem;margin-bottom:1.75rem">
      <?php $tabs=[['all','All'],['pending','Pending'],['confirmed','Confirmed'],['out_for_delivery','Out for Delivery'],['delivered','Delivered'],['cancelled','Cancelled']];
      foreach($tabs as [$slug,$label]): ?>
      <a href="/stile-lpg/customer/orders.php?status=<?= $slug ?>" class="filter-tab <?= $filter===$slug?'active':'' ?>">
        <?= $label ?><?php if(isset($counts[$slug])&&$counts[$slug]>0): ?> <span style="background:<?= $filter===$slug?'rgba(255,255,255,.25)':'#f1f5f9' ?>;border-radius:20px;padding:.1rem .45rem;font-size:.7rem;margin-left:.25rem"><?= $counts[$slug] ?></span><?php endif; ?>
      </a>
      <?php endforeach; ?>
    </div>

    <?php if(empty($orders)): ?>
    <div style="background:#fff;border-radius:20px;padding:4rem 1rem;text-align:center;border:1px solid #e2e8f0">
      <div style="width:64px;height:64px;border-radius:18px;background:#f1f5f9;display:flex;align-items:center;justify-content:center;margin:0 auto 1rem"><svg width="32" height="32" fill="none" stroke="#94a3b8" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24"><path d="M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></svg></div>
      <h3 style="color:#94a3b8;font-weight:700;font-size:1.1rem;margin:0 0 .5rem">No orders found</h3>
      <p style="color:#cbd5e1;font-size:.875rem;margin-bottom:1.5rem">Place your first LPG order today!</p>
      <a href="/stile-lpg/services.php" class="btn-primary" style="display:inline-flex"><svg width="15" height="15" fill="none" stroke="#fff" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24" style="vertical-align:middle"><path d="M8.5 14.5A2.5 2.5 0 0011 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 11-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 002.5 3z"/></svg> Order LPG Now</a>
    </div>
    <?php else: ?>
    <div style="display:flex;flex-direction:column;gap:1.25rem">
      <?php foreach($orders as $order):
        $st = statusStyle($order['status']);
        $label = ucwords(str_replace('_',' ',$order['status']));
        $isCancelled = $order['status'] === 'cancelled';
        $activeStep = $stepIdx[$order['status']] ?? -1;
      ?>
      <div class="card-hover" style="background:#fff;border-radius:20px;border:1px solid #e2e8f0;box-shadow:0 2px 12px rgba(0,0,0,.05);overflow:hidden">
        <!-- Order header -->
        <div style="padding:1.25rem 1.5rem;border-bottom:1px solid #f1f5f9;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:.75rem">
          <div style="display:flex;align-items:center;gap:1rem;flex-wrap:wrap">
            <div>
              <div style="font-size:.72rem;color:#94a3b8;font-weight:600;text-transform:uppercase;letter-spacing:.05em">Order</div>
              <div style="font-family:monospace;font-weight:700;font-size:.875rem;color:#0f172a">#<?= substr($order['id'],-10) ?></div>
            </div>
            <div style="width:1px;height:28px;background:#e2e8f0"></div>
            <div>
              <div style="font-size:.72rem;color:#94a3b8;font-weight:600;text-transform:uppercase;letter-spacing:.05em">Date</div>
              <div style="font-weight:700;font-size:.875rem;color:#0f172a"><?= date('M j, Y', strtotime($order['created_at'])) ?></div>
            </div>
            <div style="width:1px;height:28px;background:#e2e8f0"></div>
            <div>
              <div style="font-size:.72rem;color:#94a3b8;font-weight:600;text-transform:uppercase;letter-spacing:.05em">Amount</div>
              <div style="font-weight:900;font-size:.95rem;color:#f97316">₦<?= number_format($order['total']) ?></div>
            </div>
          </div>
          <span style="background:<?= $st['bg'] ?>;color:<?= $st['color'] ?>;font-size:.75rem;font-weight:700;padding:.3rem .85rem;border-radius:20px"><?= $label ?></span>
        </div>

        <!-- Progress steps (skip if cancelled) -->
        <?php if(!$isCancelled): ?>
        <div style="padding:1.25rem 1.5rem;border-bottom:1px solid #f1f5f9">
          <div style="display:flex;align-items:center;gap:0">
            <?php foreach($statusSteps as $idx => $step):
              $done  = $activeStep >= $idx;
              $active= $activeStep === $idx;
              $slabel= ucwords(str_replace('_',' ',$step));
            ?>
            <div style="display:flex;align-items:center;flex:1">
              <div style="display:flex;flex-direction:column;align-items:center;flex:1">
                <div style="width:28px;height:28px;border-radius:50%;background:<?= $done?'linear-gradient(135deg,#f97316,#fb923c)':'#f1f5f9' ?>;border:2px solid <?= $active?'#f97316':($done?'transparent':'#e2e8f0') ?>;display:flex;align-items:center;justify-content:center;color:<?= $done?'#fff':'#94a3b8' ?>;font-size:.7rem;font-weight:800;box-shadow:<?= $active?'0 0 0 3px rgba(249,115,22,.2)':'none' ?>"><?php if($done): ?><svg width="12" height="12" fill="none" stroke="#fff" stroke-width="3" viewBox="0 0 24 24"><polyline stroke-linecap="round" stroke-linejoin="round" points="20 6 9 17 4 12"/></svg><?php else: echo $idx+1; endif; ?></div>
                <div style="font-size:.65rem;font-weight:700;color:<?= $done?'#f97316':'#94a3b8' ?>;margin-top:.35rem;white-space:nowrap;text-align:center"><?= $slabel ?></div>
              </div>
              <?php if($idx < count($statusSteps)-1): ?>
              <div style="flex:1;height:2px;background:<?= $activeStep>$idx?'linear-gradient(90deg,#f97316,#fb923c)':'#e2e8f0' ?>;margin:0 .25rem;margin-bottom:1.1rem"></div>
              <?php endif; ?>
            </div>
            <?php endforeach; ?>
          </div>
        </div>
        <?php else: ?>
        <div style="padding:1rem 1.5rem;border-bottom:1px solid #f1f5f9;background:#fff5f5">
          <p style="color:#dc2626;font-size:.82rem;font-weight:600;margin:0;display:flex;align-items:center;gap:.4rem"><svg width="14" height="14" fill="none" stroke="#dc2626" stroke-width="2.5" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg> This order was cancelled.</p>
        </div>
        <?php endif; ?>

        <!-- Items row -->
        <div style="padding:1rem 1.5rem;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:.75rem">
          <div style="font-size:.85rem;color:#475569"><span style="font-weight:700">Items:</span> <?= htmlspecialchars($order['items'] ?? '—') ?></div>
          <div style="display:flex;gap:.5rem;align-items:center">
            <span style="background:#f0fdf4;border:1px solid #bbf7d0;color:#15803d;font-size:.72rem;font-weight:700;padding:.2rem .65rem;border-radius:20px;display:inline-flex;align-items:center;gap:.3rem"><svg width="12" height="12" fill="none" stroke="#15803d" stroke-width="2" viewBox="0 0 24 24"><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 000 7h5a3.5 3.5 0 010 7H6"/></svg> Cash on Delivery</span>
            <span style="background:#f1f5f9;color:#475569;font-size:.72rem;font-weight:600;padding:.2rem .65rem;border-radius:20px"><?= ucfirst($order['fulfillment'] ?? '—') ?></span>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <?php endif; ?>
  </main>
</div>

</body>
</html>
