<?php
include "session.php";
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header("Cache-Control: no-cache, must-revalidate");

require_once __DIR__ . '/../db.php';

/* ══ POST actions ══ */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['toggle_featured'])) {
    $pdo->prepare("UPDATE products SET is_featured = NOT is_featured WHERE id = ?")
        ->execute([intval($_POST['product_id'])]);
    $_SESSION['message'] = "تم تحديث حالة التميز بنجاح";
    header("Location: index.php"); exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['toggle_active'])) {
    $pdo->prepare("UPDATE products SET is_active = NOT is_active WHERE id = ?")
        ->execute([intval($_POST['product_id'])]);
    $_SESSION['message'] = "تم تحديث حالة المنتج بنجاح";
    header("Location: index.php"); exit;
}

/* ══ فلاتر ══ */
$search      = trim($_GET['search']      ?? '');
$filter_cat  = intval($_GET['filter_cat']  ?? 0);
$filter_stat = $_GET['filter_stat'] ?? 'all';
$sort        = $_GET['sort']        ?? 'newest';

$categories = $pdo->query("SELECT id, name FROM categories ORDER BY name")->fetchAll();

/* ══ خصائص المتغيرات (استعلام منفصل لتجنب GROUP_CONCAT المتداخلة) ══ */
$variants_map = [];
try {
    $vRows = $pdo->query("
        SELECT pv.product_id,
               a.name AS attr_name,
               GROUP_CONCAT(DISTINCT va.attribute_value ORDER BY va.attribute_value SEPARATOR ' | ') AS attr_values
        FROM product_variants pv
        INNER JOIN variant_attributes va ON pv.id = va.variant_id
        INNER JOIN attributes a ON va.attribute_id = a.id
        GROUP BY pv.product_id, a.id, a.name
        ORDER BY pv.product_id, a.name
    ")->fetchAll();
    foreach ($vRows as $vr) {
        $pid = $vr['product_id'];
        if (!isset($variants_map[$pid])) $variants_map[$pid] = [];
        $variants_map[$pid][] = $vr['attr_name'] . ': ' . $vr['attr_values'];
    }
} catch (Exception $e) {}

/* ══════════════════════════════════════════════════════════════
   الاستعلام الرئيسي
   المبيعات تُحسب بطريقتين:
   ① منتج بمتغيرات  → SUM(initial_stock) - SUM(stock)  في product_variants
   ② منتج بدون متغيرات → initial_stock_quantity - stock_quantity  في products

   نستخدم CASE لاختيار الطريقة الصحيحة تلقائياً:
   - إن كان للمنتج متغيرات (COUNT(pv.id) > 0) نستخدم ①
   - وإلا نستخدم ②
══════════════════════════════════════════════════════════════ */
$sql = "
    SELECT
        p.*,
        c.name AS category_name,
        GROUP_CONCAT(DISTINCT dc.name SEPARATOR ', ') AS delivery_companies,
        pi.image_url AS image,

        /* ── هل للمنتج متغيرات؟ ── */
        COUNT(DISTINCT pv.id) AS variant_count,

        /* ── المخزون الحالي ── */
        CASE
            WHEN COUNT(DISTINCT pv.id) > 0
                THEN COALESCE(SUM(DISTINCT pv.stock), 0)
            ELSE p.stock_quantity
        END AS calculated_stock,

        /* ── المخزون الأولي ── */
        CASE
            WHEN COUNT(DISTINCT pv.id) > 0
                THEN COALESCE(SUM(DISTINCT pv.initial_stock), 0)
            ELSE p.initial_stock_quantity
        END AS total_initial,

        /* ── المبيعات = الأولي - الحالي ── */
        CASE
            WHEN COUNT(DISTINCT pv.id) > 0
                THEN GREATEST(
                    COALESCE(SUM(DISTINCT pv.initial_stock), 0)
                  - COALESCE(SUM(DISTINCT pv.stock), 0),
                0)
            ELSE GREATEST(p.initial_stock_quantity - p.stock_quantity, 0)
        END AS total_sold

    FROM products p
    LEFT JOIN categories c ON p.category_id = c.id
    LEFT JOIN product_delivery_companies pdc ON p.id = pdc.product_id
    LEFT JOIN delivery_companies dc ON pdc.delivery_company_id = dc.id
    LEFT JOIN product_images pi ON p.id = pi.product_id AND pi.is_primary = 1
    LEFT JOIN product_variants pv ON p.id = pv.product_id
    WHERE 1=1
";
$params = [];

if (!empty($search)) {
    $sql .= " AND (p.name LIKE :search OR c.name LIKE :search)";
    $params[':search'] = '%' . $search . '%';
}
if ($filter_cat > 0) {
    $sql .= " AND p.category_id = :cat";
    $params[':cat'] = $filter_cat;
}
if ($filter_stat === 'active')   $sql .= " AND p.is_active = 1";
if ($filter_stat === 'inactive') $sql .= " AND p.is_active = 0";

$sql .= " GROUP BY p.id";
$sql .= match($sort) {
    'price_asc'   => " ORDER BY p.price ASC",
    'price_desc'  => " ORDER BY p.price DESC",
    'stock_asc'   => " ORDER BY calculated_stock ASC",
    'sales_desc'  => " ORDER BY total_sold DESC",
    'sales_asc'   => " ORDER BY total_sold ASC",
    default       => " ORDER BY p.created_at DESC",
};

$stmt = $pdo->prepare($sql);
foreach ($params as $k => $v) $stmt->bindValue($k, $v);
$stmt->execute();
$products = $stmt->fetchAll();

/* ══ إحصائيات ══ */
$total       = count($products);
$active      = count(array_filter($products, fn($p) => $p['is_active']));
$featured    = count(array_filter($products, fn($p) => $p['is_featured']));
$low_stock   = count(array_filter($products, fn($p) => $p['calculated_stock'] <= 3 && $p['calculated_stock'] > 0));
$out_stock   = count(array_filter($products, fn($p) => $p['calculated_stock'] == 0));
$total_sales = array_sum(array_column($products, 'total_sold'));
$max_sold    = $total > 0 ? max(array_column($products, 'total_sold')) : 0;
$min_sold    = $total > 0 ? min(array_column($products, 'total_sold')) : 0;
?>
<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>إدارة المنتجات</title>
<link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;700;800;900&display=swap" rel="stylesheet">
<style>
:root{
    --primary:#1E40AF;--primary-l:#3B82F6;--primary-d:#1E3A8A;
    --success:#059669;--success-l:#D1FAE5;
    --danger:#DC2626;--danger-l:#FEE2E2;
    --warning:#D97706;--warning-l:#FEF3C7;
    --info:#0284C7;--info-l:#E0F2FE;
    --purple:#7C3AED;--purple-l:#EDE9FE;
    --teal:#0D9488;--teal-l:#CCFBF1;
    --gold:#B45309;--gold-l:#FEF3C7;
    --rose:#E11D48;--rose-l:#FFE4E6;
    --bg:#F1F5F9;--surface:#FFFFFF;--surface-2:#F8FAFC;
    --border:#E2E8F0;--text:#0F172A;--text-2:#475569;--text-3:#94A3B8;
    --shadow-sm:0 1px 3px rgba(0,0,0,0.06);--shadow-md:0 4px 16px rgba(0,0,0,0.08);
    --radius:14px;--radius-sm:8px;--tr:all 0.22s cubic-bezier(0.4,0,0.2,1);
}
*,*::before,*::after{margin:0;padding:0;box-sizing:border-box;font-family:'Tajawal',sans-serif}
body{background:var(--bg);color:var(--text);padding:20px;min-height:100vh}
::-webkit-scrollbar{width:5px;height:5px}
::-webkit-scrollbar-track{background:#f1f5f9}
::-webkit-scrollbar-thumb{background:var(--primary-l);border-radius:10px}
.container{max-width:1500px;margin:0 auto}

.header{display:flex;justify-content:space-between;align-items:center;padding:18px 24px;background:var(--surface);border-radius:var(--radius);box-shadow:var(--shadow-sm);border:1px solid var(--border);margin-bottom:20px;animation:fadeDown 0.4s ease}
@keyframes fadeDown{from{opacity:0;transform:translateY(-12px)}to{opacity:1;transform:translateY(0)}}
.header h1{color:var(--primary);font-size:21px;font-weight:900;display:flex;align-items:center;gap:10px}
.icon-wrap{background:linear-gradient(135deg,var(--primary),var(--primary-l));color:white;width:38px;height:38px;border-radius:10px;display:flex;align-items:center;justify-content:center}

.msg{padding:13px 18px;border-radius:var(--radius-sm);display:flex;align-items:center;gap:10px;font-weight:600;margin-bottom:18px;animation:slideIn 0.3s ease}
@keyframes slideIn{from{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:translateY(0)}}
.msg-success{background:var(--success-l);color:var(--success);border:1px solid #A7F3D0}
.msg-error  {background:var(--danger-l);color:var(--danger);border:1px solid #FECACA}

.stats-grid{display:grid;grid-template-columns:repeat(6,1fr);gap:14px;margin-bottom:20px;animation:fadeUp 0.4s ease 0.05s both}
@keyframes fadeUp{from{opacity:0;transform:translateY(12px)}to{opacity:1;transform:translateY(0)}}
@media(max-width:1200px){.stats-grid{grid-template-columns:repeat(3,1fr)}}
@media(max-width:600px) {.stats-grid{grid-template-columns:repeat(2,1fr)}}
.stat-card{background:var(--surface);border-radius:var(--radius);padding:16px 18px;border:1px solid var(--border);box-shadow:var(--shadow-sm);transition:var(--tr);position:relative;overflow:hidden}
.stat-card::after{content:'';position:absolute;bottom:0;left:0;right:0;height:3px;border-radius:0 0 var(--radius) var(--radius)}
.stat-card:hover{transform:translateY(-3px);box-shadow:var(--shadow-md)}
.s-total::after{background:var(--primary)}.s-active::after{background:var(--success)}
.s-feat::after{background:var(--purple)}.s-low::after{background:var(--warning)}
.s-out::after{background:var(--danger)}.s-sales::after{background:var(--teal)}
.stat-icon{width:38px;height:38px;border-radius:var(--radius-sm);display:flex;align-items:center;justify-content:center;font-size:22px;margin-bottom:10px}
.s-total .stat-icon{background:#EFF6FF;color:var(--primary)}.s-active .stat-icon{background:var(--success-l);color:var(--success)}
.s-feat  .stat-icon{background:var(--purple-l);color:var(--purple)}.s-low   .stat-icon{background:var(--warning-l);color:var(--warning)}
.s-out   .stat-icon{background:var(--danger-l);color:var(--danger)}.s-sales .stat-icon{background:var(--teal-l);color:var(--teal)}
.stat-value{font-size:26px;font-weight:900;color:var(--text);line-height:1;margin-bottom:3px;letter-spacing:-0.5px}
.stat-label{font-size:11px;color:var(--text-3);font-weight:700;text-transform:uppercase;letter-spacing:0.5px}

.filters-bar{background:var(--surface);border-radius:var(--radius);padding:14px 18px;border:1px solid var(--border);box-shadow:var(--shadow-sm);margin-bottom:18px;animation:fadeUp 0.4s ease 0.1s both}
.filters-form{display:flex;flex-wrap:wrap;gap:10px;align-items:center}
.filter-search{display:flex;border-radius:var(--radius-sm);overflow:hidden;border:1.5px solid var(--border);transition:var(--tr);flex:1;min-width:200px}
.filter-search:focus-within{border-color:var(--primary-l);box-shadow:0 0 0 3px rgba(59,130,246,0.12)}
.filter-search input{flex:1;padding:9px 13px;border:none;outline:none;font-size:13px;color:var(--text);font-family:'Tajawal',sans-serif}
.filter-search button{padding:0 14px;background:var(--primary);color:white;border:none;cursor:pointer;font-size:13px;transition:var(--tr);display:flex;align-items:center;gap:5px}
.filter-search button:hover{background:var(--primary-d)}
.filter-select{padding:9px 13px;border:1.5px solid var(--border);border-radius:var(--radius-sm);font-size:13px;color:var(--text);font-family:'Tajawal',sans-serif;background:white;cursor:pointer;transition:var(--tr);outline:none}
.filter-select:focus{border-color:var(--primary-l);box-shadow:0 0 0 3px rgba(59,130,246,0.12)}
.filters-count{font-size:12px;color:var(--text-3);font-weight:700;margin-right:auto}

.card{background:var(--surface);border-radius:var(--radius);box-shadow:var(--shadow-sm);border:1px solid var(--border);overflow:hidden;animation:fadeUp 0.4s ease 0.15s both}
.table-wrap{overflow-x:auto}
table{width:100%;border-collapse:collapse;font-size:13px}
th{background:linear-gradient(135deg,var(--primary),var(--primary-d));color:white;padding:13px 14px;text-align:right;font-weight:700;font-size:12px;white-space:nowrap}
td{padding:11px 14px;border-bottom:1px solid #F1F5F9;color:var(--text-2);vertical-align:middle}
tr:last-child td{border-bottom:none}
tr{transition:var(--tr)}
tr:hover td{background:#F8FAFC}

.prod-img{width:52px;height:52px;object-fit:cover;border-radius:var(--radius-sm);border:1px solid var(--border)}
.prod-img-placeholder{width:52px;height:52px;background:var(--surface-2);border-radius:var(--radius-sm);border:1px solid var(--border);display:flex;align-items:center;justify-content:center;color:var(--text-3);font-size:22px}

.badge{padding:4px 10px;border-radius:20px;font-size:11px;font-weight:800;display:inline-flex;align-items:center;gap:4px;white-space:nowrap}
.b-active{background:var(--success-l);color:var(--success);border:1px solid #A7F3D0}
.b-inactive{background:var(--danger-l);color:var(--danger);border:1px solid #FECACA}
.b-info{background:var(--info-l);color:var(--info);border:1px solid #BAE6FD}

/* شارة نوع المنتج */
.b-simple{background:#F0FDF4;color:#15803D;border:1px solid #86EFAC;font-size:10px;padding:2px 7px;border-radius:20px;font-weight:700}
.b-variant{background:var(--purple-l);color:var(--purple);border:1px solid #DDD6FE;font-size:10px;padding:2px 7px;border-radius:20px;font-weight:700}

.badge-best{background:linear-gradient(135deg,#FEF3C7,#FDE68A);color:#92400E;border:1px solid #FCD34D;font-size:10px;font-weight:900;padding:3px 8px;border-radius:20px;display:inline-flex;align-items:center;gap:3px;animation:glow 2s infinite}
.badge-worst{background:var(--rose-l);color:var(--rose);border:1px solid #FECDD3;font-size:10px;font-weight:900;padding:3px 8px;border-radius:20px;display:inline-flex;align-items:center;gap:3px}
@keyframes glow{0%,100%{box-shadow:0 0 0 0 rgba(251,191,36,0)}50%{box-shadow:0 0 8px 2px rgba(251,191,36,0.45)}}

.sales-cell{min-width:130px}
.sales-top-row{display:flex;align-items:baseline;gap:6px}
.sales-num{font-weight:900;font-size:16px;color:var(--text);line-height:1}
.sales-of{font-size:11px;color:var(--text-3)}
.sales-bar-wrap{height:5px;background:#E2E8F0;border-radius:10px;margin-top:6px;overflow:hidden}
.sales-bar{height:100%;border-radius:10px;transition:width 1s cubic-bezier(0.4,0,0.2,1);background:linear-gradient(90deg,var(--teal),var(--primary-l))}
.sales-pct{font-size:10px;color:var(--text-3);margin-top:3px}
.sales-badges{display:flex;flex-wrap:wrap;gap:3px;margin-top:5px}

.stock-cell{min-width:100px}
.stock-ok {color:var(--success);font-weight:800}
.stock-low{color:var(--warning);font-weight:800}
.stock-out{color:var(--danger);font-weight:800;animation:pulse 1.5s infinite}
@keyframes pulse{0%,100%{opacity:1}50%{opacity:0.5}}
.stock-bar-wrap{height:5px;background:#E2E8F0;border-radius:10px;margin-top:5px;overflow:hidden}
.stock-bar-ok {height:100%;background:linear-gradient(90deg,var(--success),#34D399);border-radius:10px}
.stock-bar-low{height:100%;background:linear-gradient(90deg,var(--warning),#FCD34D);border-radius:10px;animation:pulse-bar 1.5s infinite}
@keyframes pulse-bar{0%,100%{opacity:1}50%{opacity:0.6}}

.variants-cell{max-width:160px}
.variant-tag{display:inline-block;font-size:11px;font-weight:700;padding:3px 8px;border-radius:20px;margin:2px 2px 2px 0;background:var(--purple-l);color:var(--purple);border:1px solid #DDD6FE;white-space:nowrap}
.variant-tag.color-tag{background:var(--info-l);color:var(--info);border-color:#BAE6FD}
.variant-tag.size-tag {background:var(--gold-l);color:var(--gold);border-color:#FCD34D}
.no-variants{font-size:11px;color:var(--text-3)}

.delivery-tag{font-size:11px;color:var(--text-3);display:flex;align-items:center;gap:4px}

.btn{padding:8px 13px;border-radius:var(--radius-sm);font-weight:700;cursor:pointer;transition:var(--tr);text-decoration:none;display:inline-flex;align-items:center;gap:5px;font-size:12px;border:none}
.btn-primary{background:var(--primary);color:white}.btn-primary:hover{background:var(--primary-d);transform:translateY(-1px);box-shadow:0 4px 14px rgba(30,64,175,0.3)}
.btn-warning{background:var(--warning);color:white}.btn-warning:hover{background:#B45309;transform:translateY(-1px)}
.btn-danger {background:var(--danger);color:white}.btn-danger:hover{background:#B91C1C;transform:translateY(-1px)}
.btn-gray   {background:var(--surface-2);color:var(--text-2);border:1.5px solid var(--border)}.btn-gray:hover{background:var(--border)}
.btn-icon   {padding:7px 10px}
.btn-feat-on {background:var(--purple-l);color:var(--purple);border:1px solid #DDD6FE}.btn-feat-on:hover{background:var(--purple);color:white}
.btn-feat-off{background:var(--surface-2);color:var(--text-3);border:1.5px solid var(--border)}.btn-feat-off:hover{background:var(--purple-l);color:var(--purple)}
.action-btns{display:flex;gap:4px;flex-wrap:nowrap}

.empty{text-align:center;padding:50px 20px;color:var(--text-3)}
.empty .empty-icon{font-size:48px;margin-bottom:12px;display:block}
.empty p{font-size:14px}

@media(max-width:768px){
    body{padding:12px}.header{flex-direction:column;align-items:flex-start;gap:12px}
    .filters-form{flex-direction:column}.filter-search{min-width:100%}
    th,td{padding:10px 8px;font-size:11px}
}
</style>
</head>
<body>

<button onclick="toggleSidebar()" style="position:fixed;top:15px;right:15px;z-index:900;background:var(--primary);color:white;border:none;padding:10px 13px;border-radius:var(--radius-sm);cursor:pointer;display:flex;align-items:center">
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round"><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/></svg>
</button>
<div class="sidebar-overlay" onclick="toggleSidebar()"></div>
<?php include 'sidebar.php'; ?>

<div class="container">

    <!-- HEADER -->
    <div class="header">
        <h1>
            <span class="icon-wrap">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2"><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>
            </span>
            إدارة المنتجات
        </h1>
        <a href="add_product.php" class="btn btn-primary">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
            إضافة منتج جديد
        </a>
    </div>

    <!-- MESSAGES -->
    <?php if (isset($_SESSION['message'])): ?>
        <div class="msg msg-success">✅ <?= htmlspecialchars($_SESSION['message']) ?></div>
        <?php unset($_SESSION['message']); ?>
    <?php endif; ?>
    <?php if (isset($_SESSION['error'])): ?>
        <div class="msg msg-error">❌ <?= htmlspecialchars($_SESSION['error']) ?></div>
        <?php unset($_SESSION['error']); ?>
    <?php endif; ?>

    <!-- STATS -->
    <div class="stats-grid">
        <div class="stat-card s-total">
            <div class="stat-icon"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><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"/></svg></div>
            <div class="stat-value"><?= $total ?></div>
            <div class="stat-label">إجمالي المنتجات</div>
        </div>
        <div class="stat-card s-active">
            <div class="stat-icon">✅</div>
            <div class="stat-value"><?= $active ?></div>
            <div class="stat-label">منتجات نشطة</div>
        </div>
        <div class="stat-card s-feat">
            <div class="stat-icon">⭐</div>
            <div class="stat-value"><?= $featured ?></div>
            <div class="stat-label">منتجات مميزة</div>
        </div>
        <div class="stat-card s-low">
            <div class="stat-icon">⚠️</div>
            <div class="stat-value"><?= $low_stock ?></div>
            <div class="stat-label">مخزون منخفض</div>
        </div>
        <div class="stat-card s-out">
            <div class="stat-icon">❌</div>
            <div class="stat-value"><?= $out_stock ?></div>
            <div class="stat-label">نفد المخزون</div>
        </div>
        <div class="stat-card s-sales">
            <div class="stat-icon">📦</div>
            <div class="stat-value"><?= number_format($total_sales) ?></div>
            <div class="stat-label">إجمالي المبيعات</div>
        </div>
    </div>

    <!-- FILTERS -->
    <div class="filters-bar">
        <form method="GET" class="filters-form">
            <div class="filter-search">
                <input type="text" name="search" placeholder="ابحث باسم المنتج أو الفئة..." value="<?= htmlspecialchars($search) ?>">
                <button type="submit">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
                    بحث
                </button>
            </div>
            <select name="filter_cat" class="filter-select" onchange="this.form.submit()">
                <option value="0">كل الفئات</option>
                <?php foreach ($categories as $cat): ?>
                    <option value="<?= $cat['id'] ?>" <?= $filter_cat==$cat['id']?'selected':'' ?>><?= htmlspecialchars($cat['name']) ?></option>
                <?php endforeach; ?>
            </select>
            <select name="filter_stat" class="filter-select" onchange="this.form.submit()">
                <option value="all"      <?= $filter_stat==='all'     ?'selected':'' ?>>كل الحالات</option>
                <option value="active"   <?= $filter_stat==='active'  ?'selected':'' ?>>نشط فقط</option>
                <option value="inactive" <?= $filter_stat==='inactive'?'selected':'' ?>>غير نشط فقط</option>
            </select>
            <select name="sort" class="filter-select" onchange="this.form.submit()">
                <option value="newest"     <?= $sort==='newest'    ?'selected':'' ?>>الأحدث أولاً</option>
                <option value="price_asc"  <?= $sort==='price_asc' ?'selected':'' ?>>السعر: الأقل</option>
                <option value="price_desc" <?= $sort==='price_desc'?'selected':'' ?>>السعر: الأعلى</option>
                <option value="stock_asc"  <?= $sort==='stock_asc' ?'selected':'' ?>>المخزون: الأقل</option>
                <option value="sales_desc" <?= $sort==='sales_desc'?'selected':'' ?>>🔥 الأكثر مبيعاً</option>
                <option value="sales_asc"  <?= $sort==='sales_asc' ?'selected':'' ?>>📉 الأقل مبيعاً</option>
            </select>
            <?php if (!empty($search) || $filter_cat || $filter_stat !== 'all' || $sort !== 'newest'): ?>
                <a href="index.php" class="btn btn-gray">
                    <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                    مسح
                </a>
            <?php endif; ?>
            <span class="filters-count"><?= $total ?> منتج</span>
        </form>
    </div>

    <!-- TABLE -->
    <div class="card">
        <div class="table-wrap">
            <table>
                <thead>
                    <tr>
                        <th>#</th>
                        <th>الصورة</th>
                        <th>الاسم</th>
                        <th>الفئة</th>
                        <th>النوع</th>
                        <th>الخصائص</th>
                        <th>السعر</th>
                        <th>المخزون</th>
                        <th>المبيعات</th>
                        <th>الحالة</th>
                        <th>مميز</th>
                        <th>التوصيل</th>
                        <th>الإجراءات</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (empty($products)): ?>
                    <tr><td colspan="13">
                        <div class="empty">
                            <span class="empty-icon">📦</span>
                            <p>لا توجد منتجات<?= !empty($search) ? ' تطابق البحث' : '' ?></p>
                        </div>
                    </td></tr>
                <?php else: ?>
                <?php foreach ($products as $p):
                    $hasVariants = intval($p['variant_count']) > 0;
                    $stock       = intval($p['calculated_stock']);
                    $initial     = intval($p['total_initial']);
                    $sold        = intval($p['total_sold']);

                    $stockClass  = $stock == 0 ? 'stock-out' : ($stock <= 3 ? 'stock-low' : 'stock-ok');
                    $stockIcon   = $stock == 0 ? '❌' : ($stock <= 3 ? '⚠️' : '✔');
                    $stockBarW   = $initial > 0 ? min(100, intval(($stock / $initial) * 100)) : ($stock > 0 ? 100 : 0);
                    $stockBarCl  = $stock <= 3 ? 'stock-bar-low' : 'stock-bar-ok';

                    $salesPct    = $max_sold > 0 ? intval(($sold / $max_sold) * 100) : 0;
                    $isBest      = ($sold === $max_sold && $sold > 0);
                    $isWorst     = ($sold === $min_sold && $total > 1 && $sold < $max_sold);

                    $variantLines = $variants_map[$p['id']] ?? [];
                ?>
                <tr>
                    <td style="font-weight:800;color:var(--text)">#<?= $p['id'] ?></td>

                    <td>
                        <?php if (!empty($p['image'])): ?>
                            <img src="<?= htmlspecialchars($p['image']) ?>" class="prod-img" alt=""
                                 onerror="this.outerHTML='<div class=\'prod-img-placeholder\'>🖼️</div>'">
                        <?php else: ?>
                            <div class="prod-img-placeholder">🖼️</div>
                        <?php endif; ?>
                    </td>

                    <td style="font-weight:700;color:var(--text);max-width:180px"><?= htmlspecialchars($p['name']) ?></td>

                    <td><span class="badge b-info"><?= htmlspecialchars($p['category_name'] ?? '--') ?></span></td>

                    <!-- نوع المنتج: بسيط أم متغيرات -->
                    <td>
                        <?php if ($hasVariants): ?>
                            <span class="b-variant">🎨 متغيرات</span>
                        <?php else: ?>
                            <span class="b-simple">📦 بسيط</span>
                        <?php endif; ?>
                    </td>

                    <!-- الخصائص -->
                    <td class="variants-cell">
                        <?php if (!empty($variantLines)): ?>
                            <?php foreach ($variantLines as $line):
                                $parts    = explode(':', $line, 2);
                                $attrName = trim($parts[0] ?? '');
                                $attrVals = trim($parts[1] ?? '');
                                $lower    = mb_strtolower($attrName);
                                $tagClass = 'variant-tag';
                                if (str_contains($lower,'لون')||str_contains($lower,'color')) $tagClass .= ' color-tag';
                                elseif (str_contains($lower,'مقاس')||str_contains($lower,'حجم')||str_contains($lower,'size')) $tagClass .= ' size-tag';
                            ?>
                                <div style="margin-bottom:3px">
                                    <span style="font-size:10px;color:var(--text-3);font-weight:700"><?= htmlspecialchars($attrName) ?>:</span>
                                    <?php foreach (explode(' | ', $attrVals) as $val): ?>
                                        <span class="<?= $tagClass ?>"><?= htmlspecialchars(trim($val)) ?></span>
                                    <?php endforeach; ?>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <span class="no-variants">—</span>
                        <?php endif; ?>
                    </td>

                    <!-- السعر -->
                    <td style="font-weight:800;color:var(--primary);white-space:nowrap">
                        <?php if (!empty($p['discounted_price']) && $p['discounted_price'] < $p['price']): ?>
                            <div><?= number_format($p['discounted_price'],2) ?> دج</div>
                            <div style="text-decoration:line-through;font-size:11px;color:var(--text-3);font-weight:400"><?= number_format($p['price'],2) ?></div>
                        <?php else: ?>
                            <?= number_format($p['price'],2) ?> دج
                        <?php endif; ?>
                    </td>

                    <!-- المخزون -->
                    <td class="stock-cell">
                        <span class="<?= $stockClass ?>"><?= $stockIcon ?> <?= $stock ?></span>
                        <?php if ($stock > 0 && $initial > 0): ?>
                            <div class="stock-bar-wrap">
                                <div class="<?= $stockBarCl ?>" style="width:<?= $stockBarW ?>%"></div>
                            </div>
                            <div style="font-size:10px;color:var(--text-3);margin-top:2px">من <?= $initial ?></div>
                        <?php endif; ?>
                    </td>

                    <!-- المبيعات -->
                    <td class="sales-cell">
                        <div class="sales-top-row">
                            <span class="sales-num"><?= number_format($sold) ?></span>
                            <?php if ($initial > 0): ?>
                                <span class="sales-of">من <?= $initial ?></span>
                            <?php endif; ?>
                        </div>
                        <?php if ($max_sold > 0): ?>
                            <div class="sales-bar-wrap">
                                <div class="sales-bar" style="width:<?= $salesPct ?>%"></div>
                            </div>
                            <div class="sales-pct"><?= $salesPct ?>% من الأعلى</div>
                        <?php endif; ?>
                        <div class="sales-badges">
                            <?php if ($isBest): ?>
                                <span class="badge-best">🏆 الأكثر مبيعاً</span>
                            <?php endif; ?>
                            <?php if ($isWorst && $sold == 0): ?>
                                <span class="badge-worst">📦 لا مبيعات</span>
                            <?php elseif ($isWorst): ?>
                                <span class="badge-worst">📉 الأقل مبيعاً</span>
                            <?php endif; ?>
                        </div>
                    </td>

                    <!-- الحالة -->
                    <td>
                        <form method="POST" style="display:inline">
                            <input type="hidden" name="product_id" value="<?= $p['id'] ?>">
                            <button type="submit" name="toggle_active"
                                class="badge <?= $p['is_active'] ? 'b-active' : 'b-inactive' ?>"
                                style="border:none;cursor:pointer;font-family:'Tajawal',sans-serif">
                                <?= $p['is_active'] ? '✅ نشط' : '⛔ معطّل' ?>
                            </button>
                        </form>
                    </td>

                    <!-- مميز -->
                    <td>
                        <form method="POST" style="display:inline">
                            <input type="hidden" name="product_id" value="<?= $p['id'] ?>">
                            <button type="submit" name="toggle_featured"
                                class="btn btn-icon <?= $p['is_featured'] ? 'btn-feat-on' : 'btn-feat-off' ?>">
                                <?= $p['is_featured'] ? '⭐' : '☆' ?>
                            </button>
                        </form>
                    </td>

                    <!-- التوصيل -->
                    <td>
                        <?php if (!empty($p['delivery_companies'])): ?>
                            <div class="delivery-tag">
                                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="1" y="3" width="15" height="13"/><path d="M16 8h4l3 3v5h-7V8z"/><circle cx="5.5" cy="18.5" r="2.5"/><circle cx="18.5" cy="18.5" r="2.5"/></svg>
                                <?= htmlspecialchars($p['delivery_companies']) ?>
                            </div>
                        <?php else: ?>
                            <span style="color:var(--text-3);font-size:12px">--</span>
                        <?php endif; ?>
                    </td>

                    <!-- الإجراءات -->
                    <td>
                        <div class="action-btns">
                            <a href="edit_product.php?id=<?= $p['id'] ?>" class="btn btn-warning btn-icon" title="تعديل">
                                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M11 4H4a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 013 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
                            </a>
                            <a href="delete_product.php?id=<?= $p['id'] ?>"
                               class="btn btn-danger btn-icon" title="حذف"
                               onclick="return confirm('حذف المنتج «<?= htmlspecialchars($p['name'], ENT_QUOTES) ?>»؟')">
                                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 01-2 2H8a2 2 0 01-2-2L5 6"/><path d="M10 11v6M14 11v6"/><path d="M9 6V4a1 1 0 011-1h4a1 1 0 011 1v2"/></svg>
                            </a>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

</div>
</body>
</html>