<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/auth.php';

include "partials/header.php";

/* دالة هروب آمن */
if (!function_exists('e')) {
  function e($v): string {
    return htmlspecialchars((string)($v ?? ''), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
  }
}

/* الاستعلام: آخر 20 بند طلب (قد يظهر الطلب الواحد بعدة صفوف بحسب العناصر) */
$sql = "SELECT o.id, o.total, o.status, o.created_at,
               u.name  AS user_name, 
               u.phone AS user_phone, 
               p.name  AS product_name,
               oi.quantity, oi.price
        FROM orders o
        JOIN users u       ON o.user_id = u.id
        JOIN order_items oi ON o.id = oi.order_id
        JOIN products p     ON oi.product_id = p.id
        ORDER BY o.id DESC
        LIMIT 20";
$orders = db()->query($sql)->fetchAll(PDO::FETCH_ASSOC);

/* عدادات سريعة */
$totalUsers    = (int)db()->query("SELECT COUNT(*) FROM users")->fetchColumn();
$totalProducts = (int)db()->query("SELECT COUNT(*) FROM products")->fetchColumn();
$totalOrders   = (int)db()->query("SELECT COUNT(*) FROM orders")->fetchColumn();

/* شارة الحالة */
function status_badge($st): string {
  $s = strtolower((string)$st);
  $map = [
    'pending'   => ['قيد المراجعة',  'linear-gradient(145deg,#f59e0b,#fbbf24)', '#0f0f0f'],
    'paid'      => ['مدفوع',        'linear-gradient(145deg,#22c55e,#86efac)', '#0b1d10'],
    'approved'  => ['مؤكّد',        'linear-gradient(145deg,#22c55e,#86efac)', '#0b1d10'],
    'rejected'  => ['مرفوض',        'linear-gradient(145deg,#ef4444,#f87171)', '#0f0f0f'],
    'shipped'   => ['تم الشحن',     'linear-gradient(145deg,#38bdf8,#67e8f9)', '#0b1b1f'],
    'completed' => ['مكتمل',        'linear-gradient(145deg,#8b5cf6,#a78bfa)', '#0f0f0f'],
  ];
  [$label,$bg,$fg] = $map[$s] ?? [$st,'#30353b','#e5e7eb'];
  return '<span class="st-badge" style="background:'.$bg.';color:'.$fg.'">'.e($label).'</span>';
}
?>
<style>
@import url('https://fonts.googleapis.com/css2?family=Cairo:wght@400;700;900&display=swap');
:root{
  --gold:#d4af37; --ink:#eaeaea; --muted:#9aa7b1; --bg:#0b0b0b; --card:#121212;
}
*{box-sizing:border-box}
html,body{background:var(--bg);color:var(--ink);font-family:'Cairo',system-ui}
.admin-wrap{width:min(1200px,95%);margin:28px auto}
.hx{display:flex;justify-content:space-between;align-items:center;margin-bottom:16px}
.hx h2{margin:0;font-weight:900}
.stats{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-bottom:16px}
@media(max-width:860px){.stats{grid-template-columns:1fr}}
.stat{
  background:var(--card);
  border:1px solid rgba(212,175,55,.45);
  border-radius:16px;
  padding:16px;
  box-shadow:0 12px 26px rgba(0,0,0,.35);
  display:flex;align-items:center;justify-content:space-between;gap:10px
}
.stat .lbl{color:var(--muted);font-weight:700}
.stat .val{font-weight:900;font-size:24px}
.card{
  background:var(--card);
  border:1px solid rgba(212,175,55,.45);
  border-radius:16px;
  padding:16px;
  box-shadow:0 12px 26px rgba(0,0,0,.35);
}
.tbl{width:100%;border-collapse:separate;border-spacing:0 10px}
.tbl thead th{
  color:var(--gold);font-weight:800;text-align:right;padding:10px;border-bottom:1px solid rgba(212,175,55,.25);white-space:nowrap
}
.tbl tbody tr{
  background:#151515;border:1px solid rgba(212,175,55,.25);
  border-radius:12px;box-shadow:0 8px 18px rgba(0,0,0,.35)
}
.tbl tbody td{padding:10px;white-space:nowrap;vertical-align:middle}
.tbl tbody tr>td:first-child{border-radius:12px 0 0 12px}
.tbl tbody tr>td:last-child{border-radius:0 12px 12px 0}
.text-clip{max-width:260px;overflow:hidden;text-overflow:ellipsis;display:inline-block;vertical-align:bottom}
.money{font-weight:900}
.st-badge{display:inline-block;padding:8px 12px;border-radius:999px;font-weight:900}
.row-actions{display:flex;gap:6px}
.icon-btn{width:36px;height:36px;border-radius:10px;border:0;cursor:pointer;display:inline-grid;place-items:center}
.icon-btn.view{background:#0b0b0b;color:#eaeaea;border:1px solid rgba(212,175,55,.35)}
.icon-btn.more{background:linear-gradient(145deg,#b68f2a,#d4af37,#c8a951);color:#0f0f0f}
.note{color:var(--muted);font-size:12px}
</style>

<div class="admin-wrap">
  <div class="hx">
    <h2>لوحة التحكم</h2>
    <span class="note">آخر 20 بند من الطلبات</span>
  </div>

  <!-- بطاقات الإحصائيات -->
  <div class="stats">
    <div class="stat">
      <div class="lbl">👤 عدد المستخدمين</div>
      <div class="val"><?= number_format($totalUsers) ?></div>
    </div>
    <div class="stat">
      <div class="lbl">💍 عدد المنتجات</div>
      <div class="val"><?= number_format($totalProducts) ?></div>
    </div>
    <div class="stat">
      <div class="lbl">🛒 عدد الطلبات</div>
      <div class="val"><?= number_format($totalOrders) ?></div>
    </div>
  </div>

  <!-- جدول آخر الطلبات -->
  <div class="card">
    <h3 style="margin:0 0 10px">آخر الطلبات</h3>
    <div style="overflow:auto">
      <table class="tbl">
        <thead>
          <tr>
            <th>#</th>
            <th>العميل</th>
            <th>الهاتف</th>
            <th>المنتج</th>
            <th>الكمية</th>
            <th>السعر للوحدة</th>
            <th>الإجمالي</th>
            <th>الحالة</th>
            <th>تاريخ الطلب</th>
            <th>إجراءات</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($orders as $o): ?>
            <tr>
              <td><?= (int)$o['id'] ?></td>
              <td><span class="text-clip" title="<?= e($o['user_name']) ?>"><?= e($o['user_name']) ?></span></td>
              <td><?= e($o['user_phone']) ?></td>
              <td><span class="text-clip" title="<?= e($o['product_name']) ?>"><?= e($o['product_name']) ?></span></td>
              <td><?= (int)$o['quantity'] ?></td>
              <td class="money"><?= number_format((float)$o['price'], 2) ?> ر.س</td>
              <td class="money"><?= number_format((float)$o['price'] * (int)$o['quantity'], 2) ?> ر.س</td>
              <td><?= status_badge((string)$o['status']) ?></td>
              <td><?= e(date('Y-m-d H:i', strtotime((string)$o['created_at']))) ?></td>
              <td>
                <div class="row-actions">
                  <a class="icon-btn view" href="order_view.php?id=<?= (int)$o['id'] ?>" title="عرض"><i class="fa fa-eye"></i></a>
                  <a class="icon-btn more" href="orders.php?filter_id=<?= (int)$o['id'] ?>" title="عرض الطلب كاملاً"><i class="fa fa-up-right-from-square"></i></a>
                </div>
              </td>
            </tr>
          <?php endforeach; ?>
          <?php if (!$orders): ?>
            <tr><td colspan="10" style="text-align:center;color:#aaa">لا توجد طلبات حديثة.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<?php include "partials/footer.php"; ?>
