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

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

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

$products = $pdo->query("
    SELECT
        p.id, p.name, p.price, p.created_at, p.is_active, p.category_id,
        c.name AS category_name,
        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 COALESCE(p.stock_quantity,0) END AS current_stock,
        CASE WHEN COUNT(DISTINCT pv.id)>0 THEN COALESCE(SUM(DISTINCT pv.initial_stock),0) ELSE COALESCE(p.initial_stock_quantity,0) END AS initial_stock,
        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(COALESCE(p.initial_stock_quantity,0)-COALESCE(p.stock_quantity,0),0)
        END AS total_sold
    FROM products p
    LEFT JOIN categories c ON p.category_id=c.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
    GROUP BY p.id ORDER BY total_sold DESC
")->fetchAll();

$product_ids   = array_column($products,'id');
$monthly_sales = [];
$weekly_sales  = [];

if (!empty($product_ids)) {
    $in = implode(',', array_map('intval', $product_ids));
    $rows = $pdo->query("
        SELECT p.id AS product_id,
               DATE_FORMAT(o.order_date,'%Y-%m') AS month_key,
               DATE_FORMAT(o.order_date,'%Y-%u') AS week_key,
               SUM(oi.quantity) AS qty
        FROM order_items oi
        INNER JOIN orders o ON oi.order_id=o.id
        INNER JOIN product_variants pv ON oi.product_variant_id=pv.id
        INNER JOIN products p ON pv.product_id=p.id
        WHERE o.status_id IN (2,3) AND p.id IN ($in)
        GROUP BY p.id, month_key, week_key
    ")->fetchAll();
    foreach ($rows as $r) {
        $pid = $r['product_id'];
        $monthly_sales[$pid][$r['month_key']] = ($monthly_sales[$pid][$r['month_key']] ?? 0) + $r['qty'];
        $weekly_sales[$pid][$r['week_key']]   = ($weekly_sales[$pid][$r['week_key']]   ?? 0) + $r['qty'];
    }
}

function analyzeProduct($p, $monthly, $weekly) {
    $sold    = intval($p['total_sold']);
    $initial = intval($p['initial_stock']);
    $current = intval($p['current_stock']);
    $price   = floatval($p['price']);

    $created  = $p['created_at'] ? new DateTime($p['created_at']) : new DateTime('-30 days');
    $now      = new DateTime();
    $days     = max(1, $created->diff($now)->days);

    $daily_rate   = $sold / $days;
    $weekly_rate  = $daily_rate * 7;
    $monthly_rate = $daily_rate * 30;
    $days_left    = $daily_rate > 0 ? intval($current / $daily_rate) : null;

    $best_month     = null;
    $best_month_qty = 0;
    if (!empty($monthly)) {
        arsort($monthly);
        $bk = array_key_first($monthly);
        $best_month_qty = $monthly[$bk];
        $dt = DateTime::createFromFormat('Y-m', $bk);
        $best_month = $dt ? $dt->format('M Y') : $bk;
    }

    $last30_key   = date('Y-m');
    $prev30_key   = date('Y-m', strtotime('-1 month'));
    $last30_sales = $monthly[$last30_key] ?? 0;
    $prev30_sales = $monthly[$prev30_key] ?? 0;

    $change = 0;
    $trend  = 'stable';
    if ($prev30_sales > 0) {
        $change = (($last30_sales - $prev30_sales) / $prev30_sales) * 100;
        if ($change >= 20)      $trend = 'rising';
        elseif ($change <= -20) $trend = 'falling';
    } elseif ($last30_sales > 0) {
        $trend = 'rising';
    }

    $sell_pct = $initial > 0 ? ($sold / $initial) * 100 : 0;

    if ($current == 0)                                    $recommendation = 'restock';
    elseif ($current <= 3 && $daily_rate > 0.2)           $recommendation = 'urgent';
    elseif ($trend === 'rising' && $sell_pct > 40)        $recommendation = 'buy_now';
    elseif ($trend === 'falling' || ($sold==0 && $days>14)) $recommendation = 'stagnant';
    elseif ($days_left !== null && $days_left < 14)       $recommendation = 'restock_soon';
    else                                                   $recommendation = 'good';

    // اقتراحات ذكية
    $smart_tips = [];
    if ($price > 10000)
        $smart_tips[] = ['tip-amber',  '💎', 'منتج فاخر - ركز على جودة الصور والوصف'];
    elseif ($price < 3000)
        $smart_tips[] = ['tip-green',  '🏷️', 'سعر تنافسي - مناسب للحملات الترويجية'];

    if ($daily_rate >= 1)
        $smart_tips[] = ['tip-blue',   '🔥', 'طلب يومي مرتفع - حافظ على مخزون كافٍ'];
    elseif ($daily_rate >= 0.3)
        $smart_tips[] = ['tip-teal',   '📦', 'بيع منتظم - اطلب مخزوناً كل شهر'];
    elseif ($daily_rate > 0 && $daily_rate < 0.1)
        $smart_tips[] = ['tip-purple', '📢', 'بيع بطيء - فكر في تخفيض أو إعلان مدفوع'];

    if ($sell_pct >= 70)
        $smart_tips[] = ['tip-green',  '⭐', 'أداء ممتاز - من أفضل منتجاتك'];
    elseif ($sell_pct >= 40)
        $smart_tips[] = ['tip-blue',   '📈', 'أداء جيد - استمر في هذا المنتج'];
    elseif ($sold == 0 && $days > 30)
        $smart_tips[] = ['tip-red',    '⚠️', 'لا مبيعات منذ ' . $days . ' يوم - راجع الإستراتيجية'];

    if ($current <= 3 && $current > 0)
        $smart_tips[] = ['tip-red',    '🔴', 'مخزون حرج - اطلب الآن قبل النفاد'];
    elseif ($current > 50)
        $smart_tips[] = ['tip-purple', '🏭', 'مخزون وفير - لا حاجة للطلب قريباً'];

    if ($best_month && $best_month_qty > 0)
        $smart_tips[] = ['tip-amber',  '📅', 'أفضل فترة للبيع تاريخياً: ' . $best_month];

    if ($days <= 30)
        $smart_tips[] = ['tip-teal',   '🆕', 'منتج جديد - راقب أداءه بدقة في الأسابيع القادمة'];

    return compact(
        'daily_rate','weekly_rate','monthly_rate','days_left',
        'best_month','best_month_qty','trend','recommendation',
        'sell_pct','change','last30_sales','prev30_sales','smart_tips','days'
    );
}

$total_products  = count($products);
$total_sold_all  = array_sum(array_column($products,'total_sold'));
$active_count    = count(array_filter($products, fn($p)=>$p['is_active']));
$out_stock_count = count(array_filter($products, fn($p)=>$p['current_stock']==0));

$month_ar = [
    'Jan'=>'يناير','Feb'=>'فبراير','Mar'=>'مارس','Apr'=>'أبريل',
    'May'=>'مايو','Jun'=>'يونيو','Jul'=>'يوليو','Aug'=>'أغسطس',
    'Sep'=>'سبتمبر','Oct'=>'أكتوبر','Nov'=>'نوفمبر','Dec'=>'ديسمبر'
];
function toArMonth($en, $map) {
    $p = explode(' ',$en,2);
    return ($map[$p[0]] ?? $p[0]) . (isset($p[1])?' '.$p[1]:'');
}
?>
<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
    <?php include __DIR__ . '/darkmode.php'; ?>
<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">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;600&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
:root{
    --ink:#0A0F1E;--ink-2:#1E2840;--ink-3:#3D4F6E;--muted:#8896B0;
    --border:#E4EAF4;--bg:#F4F7FD;--surface:#FFF;--surface-2:#F8FAFF;
    --blue:#1D4ED8;--blue-l:#EFF6FF;--blue-sat:#3B82F6;
    --green:#047857;--green-l:#ECFDF5;--green-sat:#10B981;
    --amber:#B45309;--amber-l:#FFFBEB;--amber-sat:#F59E0B;
    --red:#B91C1C;--red-l:#FFF1F1;--red-sat:#EF4444;
    --purple:#5B21B6;--purple-l:#F5F3FF;--purple-sat:#8B5CF6;
    --teal:#0F766E;--teal-l:#F0FDFA;--teal-sat:#14B8A6;
    --radius:16px;--radius-sm:10px;
    --shadow:0 2px 12px rgba(10,15,30,0.07);
    --shadow-md:0 8px 32px rgba(10,15,30,0.10);
    --tr:all 0.2s cubic-bezier(0.4,0,0.2,1);
}
*,*::before,*::after{margin:0;padding:0;box-sizing:border-box}
body{font-family:'Tajawal',sans-serif;background:var(--bg);color:var(--ink);min-height:100vh;padding:24px 20px}
::-webkit-scrollbar{width:5px;height:5px}
::-webkit-scrollbar-track{background:var(--bg)}
::-webkit-scrollbar-thumb{background:var(--blue-sat);border-radius:10px}
.container{max-width:1600px;margin:0 auto}

.page-header{
    background:linear-gradient(135deg,var(--ink) 0%,var(--ink-2) 60%,#1E3A8A 100%);
    border-radius:var(--radius);padding:26px 32px;margin-bottom:22px;
    display:flex;justify-content:space-between;align-items:center;
    position:relative;overflow:hidden;animation:fadeDown .5s ease;
}
.page-header::before{content:'';position:absolute;top:-60px;left:-60px;width:220px;height:220px;border-radius:50%;background:rgba(59,130,246,.1);pointer-events:none}
.page-header::after{content:'';position:absolute;bottom:-40px;right:8%;width:170px;height:170px;border-radius:50%;background:rgba(139,92,246,.09);pointer-events:none}
@keyframes fadeDown{from{opacity:0;transform:translateY(-14px)}to{opacity:1;transform:translateY(0)}}
@keyframes fadeUp{from{opacity:0;transform:translateY(14px)}to{opacity:1;transform:translateY(0)}}
.header-left h1{font-size:24px;font-weight:900;color:#fff;display:flex;align-items:center;gap:12px;margin-bottom:5px}
.pulse-dot{width:9px;height:9px;border-radius:50%;background:#34D399;display:inline-block;animation:ping 1.5s ease-in-out infinite;flex-shrink:0}
@keyframes ping{0%{box-shadow:0 0 0 0 rgba(52,211,153,.5)}70%{box-shadow:0 0 0 8px rgba(52,211,153,0)}100%{box-shadow:0 0 0 0 rgba(52,211,153,0)}}
.header-left p{color:rgba(255,255,255,.55);font-size:13px}
.header-right{display:flex;gap:10px;position:relative;z-index:2}

.kpi-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:14px;margin-bottom:20px;animation:fadeUp .5s ease .08s both}
@media(max-width:900px){.kpi-grid{grid-template-columns:repeat(2,1fr)}}
.kpi{background:var(--surface);border-radius:var(--radius);padding:18px 20px;border:1px solid var(--border);box-shadow:var(--shadow);transition:var(--tr);position:relative;overflow:hidden}
.kpi:hover{transform:translateY(-3px);box-shadow:var(--shadow-md)}
.kpi-accent{position:absolute;top:0;right:0;width:4px;height:100%;border-radius:0 var(--radius) var(--radius) 0}
.kpi-icon{font-size:26px;margin-bottom:8px}
.kpi-val{font-size:30px;font-weight:900;color:var(--ink);letter-spacing:-1px;line-height:1}
.kpi-lbl{font-size:11px;color:var(--muted);font-weight:700;text-transform:uppercase;letter-spacing:.4px;margin-top:3px}

.filter-bar{
    background:var(--surface);border-radius:var(--radius);padding:12px 16px;
    border:1px solid var(--border);margin-bottom:18px;
    display:flex;gap:10px;flex-wrap:wrap;align-items:center;animation:fadeUp .5s ease .12s both;
}
.filter-bar select,.filter-bar input{
    padding:9px 13px;border:1.5px solid var(--border);border-radius:var(--radius-sm);
    font-family:'Tajawal',sans-serif;font-size:13px;color:var(--ink);
    background:var(--surface-2);outline:none;transition:var(--tr);
}
.filter-bar select:focus,.filter-bar input:focus{border-color:var(--blue-sat);box-shadow:0 0 0 3px rgba(59,130,246,.1)}
.filter-bar input{flex:1;min-width:160px}

.products-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(350px,1fr));gap:16px;animation:fadeUp .5s ease .16s both}
@media(max-width:780px){.products-grid{grid-template-columns:1fr}}

.prod-card{background:var(--surface);border-radius:var(--radius);border:1px solid var(--border);box-shadow:var(--shadow);overflow:hidden;transition:var(--tr)}
.prod-card:hover{transform:translateY(-3px);box-shadow:var(--shadow-md);border-color:var(--blue-sat)}

.card-top{display:flex;gap:12px;padding:15px 15px 11px;align-items:flex-start}
.prod-thumb{width:56px;height:56px;border-radius:10px;object-fit:cover;border:1px solid var(--border);flex-shrink:0}
.prod-thumb-ph{width:56px;height:56px;border-radius:10px;background:var(--surface-2);border:1px solid var(--border);display:flex;align-items:center;justify-content:center;font-size:22px;flex-shrink:0}
.card-info{flex:1;min-width:0}
.prod-name{font-size:14px;font-weight:800;color:var(--ink);margin-bottom:5px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.prod-meta{display:flex;gap:4px;flex-wrap:wrap;align-items:center}
.tag{padding:2px 7px;border-radius:20px;font-size:11px;font-weight:700}
.tag-cat  {background:var(--blue-l);color:var(--blue)}
.tag-price{background:var(--teal-l);color:var(--teal);font-family:'IBM Plex Mono',monospace}
.tag-on   {background:var(--green-l);color:var(--green)}
.tag-off  {background:var(--red-l);color:var(--red)}
.age-badge{font-size:10px;color:var(--muted);font-weight:600;padding:2px 6px;border-radius:20px;background:var(--surface-2);border:1px solid var(--border)}

.rec-banner{margin:0 12px 11px;border-radius:var(--radius-sm);padding:8px 12px;display:flex;align-items:center;gap:9px;font-size:13px;font-weight:700}
.rec-restock    {background:#FFF1F1;color:var(--red);border:1px solid #FECACA}
.rec-urgent     {background:#FFF7ED;color:#C2410C;border:1px solid #FED7AA;animation:flash 1.2s infinite}
@keyframes flash{0%,100%{opacity:1}50%{opacity:.75}}
.rec-buy_now    {background:var(--green-l);color:var(--green);border:1px solid #A7F3D0}
.rec-stagnant   {background:var(--purple-l);color:var(--purple);border:1px solid #DDD6FE}
.rec-restock_soon{background:var(--amber-l);color:var(--amber);border:1px solid #FDE68A}
.rec-good       {background:var(--teal-l);color:var(--teal);border:1px solid #99F6E4}
.rec-icon{font-size:17px}
.rec-text b{display:block;font-size:13px}
.rec-text small{font-weight:400;font-size:11px;opacity:.8}

.card-stats{padding:0 12px 11px;display:grid;grid-template-columns:1fr 1fr;gap:9px}
.stat-box{background:var(--surface-2);border-radius:var(--radius-sm);padding:9px 11px;border:1px solid var(--border)}
.stat-box-label{font-size:10px;color:var(--muted);font-weight:700;text-transform:uppercase;letter-spacing:.3px;margin-bottom:3px}
.stat-box-val{font-size:18px;font-weight:900;color:var(--ink);font-family:'IBM Plex Mono',monospace}
.stat-box-sub{font-size:10px;color:var(--muted);margin-top:2px}
.prog-wrap{height:5px;background:var(--border);border-radius:10px;overflow:hidden;margin-top:5px}
.prog-fill{height:100%;border-radius:10px;transition:width 1s cubic-bezier(.4,0,.2,1)}
.prog-green{background:linear-gradient(90deg,var(--green-sat),#34D399)}
.prog-amber{background:linear-gradient(90deg,var(--amber-sat),#FCD34D)}
.prog-red  {background:linear-gradient(90deg,var(--red-sat),#FC8181)}
.prog-blue {background:linear-gradient(90deg,var(--blue-sat),#93C5FD)}

/* ── الرسم البياني صغير جداً ── */
.mini-chart-wrap{padding:0 12px 9px}
.mini-chart-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:4px}
.mini-chart-lbl{font-size:10px;color:var(--muted);font-weight:700;text-transform:uppercase;letter-spacing:.3px}
.mini-chart-total{font-size:10px;color:var(--muted)}
/* ارتفاع ثابت 44px */
.mini-chart-canvas{display:block;height:44px !important;max-height:44px !important;width:100% !important}

.trend-row{padding:0 12px 9px;display:flex;gap:6px;align-items:center;flex-wrap:wrap}
.trend-chip{padding:4px 9px;border-radius:20px;font-size:11px;font-weight:700;display:inline-flex;align-items:center;gap:4px}
.tc-rising {background:var(--green-l);color:var(--green)}
.tc-falling{background:var(--red-l);color:var(--red)}
.tc-stable {background:var(--blue-l);color:var(--blue)}
.rate-chip{padding:4px 8px;border-radius:20px;background:var(--ink);color:#fff;font-size:10px;font-weight:700;font-family:'IBM Plex Mono',monospace}

.peak-row{padding:0 12px 9px}
.peak-title{font-size:10px;color:var(--muted);font-weight:700;text-transform:uppercase;margin-bottom:5px}
.peak-months{display:flex;gap:4px;flex-wrap:wrap}
.peak-m{padding:3px 8px;border-radius:7px;font-size:10px;font-weight:700;border:1px solid var(--border);background:var(--surface-2);color:var(--ink-3)}
.peak-m.top{background:linear-gradient(135deg,#FEF3C7,#FDE68A);color:#92400E;border-color:#FCD34D}
.peak-m.med{background:var(--green-l);color:var(--green);border-color:#A7F3D0}
.peak-m.low{background:var(--red-l);color:var(--red);border-color:#FECACA}

.smart-tips-wrap{padding:0 12px 9px}
.smart-tips-title{font-size:10px;color:var(--muted);font-weight:700;text-transform:uppercase;margin-bottom:5px}
.smart-tips{display:flex;flex-wrap:wrap;gap:4px}
.tip-chip{padding:3px 8px;border-radius:20px;font-size:11px;font-weight:700;display:inline-flex;align-items:center;gap:3px;border:1px solid}
.tip-blue  {background:var(--blue-l);  color:var(--blue);  border-color:#BFDBFE}
.tip-green {background:var(--green-l); color:var(--green); border-color:#A7F3D0}
.tip-amber {background:var(--amber-l); color:var(--amber); border-color:#FDE68A}
.tip-purple{background:var(--purple-l);color:var(--purple);border-color:#DDD6FE}
.tip-red   {background:var(--red-l);   color:var(--red);   border-color:#FECACA}
.tip-teal  {background:var(--teal-l);  color:var(--teal);  border-color:#99F6E4}

.days-left-row{margin:0 12px 12px;background:var(--ink);border-radius:var(--radius-sm);padding:9px 12px;display:flex;align-items:center;justify-content:space-between}
.dl-lbl{font-size:11px;color:rgba(255,255,255,.5);font-weight:600}
.dl-val{font-size:20px;font-weight:900;color:#fff;font-family:'IBM Plex Mono',monospace}
.dl-unit{font-size:11px;color:rgba(255,255,255,.5)}

.card-footer{padding:10px 12px;border-top:1px solid var(--border);display:flex;gap:7px}
.btn{padding:7px 12px;border-radius:var(--radius-sm);font-family:'Tajawal',sans-serif;font-weight:700;font-size:12px;cursor:pointer;border:none;transition:var(--tr);text-decoration:none;display:inline-flex;align-items:center;gap:4px}
.btn-primary{background:var(--blue);color:#fff}.btn-primary:hover{background:var(--ink-2);transform:translateY(-1px)}
.btn-outline{background:transparent;color:var(--ink-3);border:1.5px solid var(--border)}.btn-outline:hover{border-color:var(--blue-sat);color:var(--blue)}

.empty-state{text-align:center;padding:60px 20px;color:var(--muted);grid-column:1/-1}
.empty-state .ei{font-size:50px;margin-bottom:12px;display:block}

@media(max-width:600px){
    body{padding:14px 10px}
    .page-header{flex-direction:column;gap:12px;padding:18px}
    .header-left h1{font-size:18px}
}
</style>
</head>
<body>

<button onclick="toggleSidebar()" style="position:fixed;top:15px;right:15px;z-index:900;background:var(--ink);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">

<div class="page-header">
    <div class="header-left">
        <h1><span class="pulse-dot"></span> 📊 تحليل ذكي للمنتجات</h1>
        <p>معدلات البيع · التوصيات · أفضل فترات البيع · توقعات المخزون</p>
    </div>
    <div class="header-right">
        <a href="index.php" class="btn btn-outline" style="color:#fff;border-color:rgba(255,255,255,.2)">← المنتجات</a>
        <a href="profit_loss.php" class="btn btn-primary" style="background:rgba(255,255,255,.15)">📈 الأرباح</a>
    </div>
</div>

<div class="kpi-grid">
    <div class="kpi"><div class="kpi-accent" style="background:var(--blue-sat)"></div><div class="kpi-icon">📦</div><div class="kpi-val"><?= $total_products ?></div><div class="kpi-lbl">إجمالي المنتجات</div></div>
    <div class="kpi"><div class="kpi-accent" style="background:var(--green-sat)"></div><div class="kpi-icon">✅</div><div class="kpi-val"><?= $active_count ?></div><div class="kpi-lbl">منتجات نشطة</div></div>
    <div class="kpi"><div class="kpi-accent" style="background:var(--teal-sat)"></div><div class="kpi-icon">🛒</div><div class="kpi-val"><?= number_format($total_sold_all) ?></div><div class="kpi-lbl">إجمالي المبيعات</div></div>
    <div class="kpi"><div class="kpi-accent" style="background:var(--red-sat)"></div><div class="kpi-icon">⚠️</div><div class="kpi-val"><?= $out_stock_count ?></div><div class="kpi-lbl">نفد المخزون</div></div>
</div>

<div class="filter-bar">
    <input type="text" id="searchInput" placeholder="🔍 ابحث عن منتج..." oninput="filterCards()">
    <select id="recFilter" onchange="filterCards()">
        <option value="all">كل التوصيات</option>
        <option value="restock">🔴 نفد المخزون</option>
        <option value="urgent">🟠 عاجل</option>
        <option value="buy_now">🟢 اشترِ الآن</option>
        <option value="restock_soon">🟡 جدد قريباً</option>
        <option value="stagnant">🔵 ركود</option>
        <option value="good">✅ جيد</option>
    </select>
    <select id="trendFilter" onchange="filterCards()">
        <option value="all">كل الاتجاهات</option>
        <option value="rising">📈 في ارتفاع</option>
        <option value="falling">📉 في انخفاض</option>
        <option value="stable">➡️ مستقر</option>
    </select>
    <select id="sortFilter" onchange="sortCards()">
        <option value="sold_desc">الأكثر مبيعاً</option>
        <option value="sold_asc">الأقل مبيعاً</option>
        <option value="stock_asc">مخزون: الأقل</option>
        <option value="days_asc">سينفد أولاً</option>
    </select>
</div>

<div class="products-grid" id="productsGrid">

<?php
$rec_labels = [
    'restock'      => ['🔴','نفد المخزون تماماً','أعد الطلب فوراً!'],
    'urgent'       => ['🔥','مخزون حرج + بيع نشط','أعد الطلب بشكل عاجل'],
    'buy_now'      => ['🚀','طلب متزايد','الوقت المثالي للشراء الآن'],
    'restock_soon' => ['⏳','المخزون سينفد قريباً','خطط لإعادة الطلب'],
    'stagnant'     => ['😴','فترة ركود','راجع السعر أو استراتيجية التسويق'],
    'good'         => ['✅','حالة جيدة','المنتج يسير بشكل طبيعي'],
];
$trend_labels = [
    'rising'  => ['📈','في ارتفاع','tc-rising'],
    'falling' => ['📉','في انخفاض','tc-falling'],
    'stable'  => ['➡️','مستقر','tc-stable'],
];

foreach ($products as $p):
    $an    = analyzeProduct($p, $monthly_sales[$p['id']] ?? [], $weekly_sales[$p['id']] ?? []);
    $rec   = $an['recommendation'];
    $trend = $an['trend'];

    $current   = intval($p['current_stock']);
    $initial   = intval($p['initial_stock']);
    $sold      = intval($p['total_sold']);
    $stock_pct = $initial>0 ? min(100,intval(($current/$initial)*100)) : ($current>0?100:0);
    $sell_pct  = intval($an['sell_pct']);
    $prog_cl   = $current==0 ? 'prog-red' : ($current<=3 ? 'prog-amber' : 'prog-green');

    // عمر المنتج
    $cr_dt   = $p['created_at'] ? new DateTime($p['created_at']) : new DateTime('-30 days');
    $age_d   = max(1,$cr_dt->diff(new DateTime())->days);
    $age_lbl = $age_d<30 ? 'منذ '.$age_d.' يوم' : ($age_d<365 ? 'منذ '.intval($age_d/30).' شهر' : 'منذ '.intval($age_d/365).' سنة');

    // رسم بياني آخر 6 أشهر
    $c_labels=[]; $c_data=[];
    for($i=5;$i>=0;$i--){
        $mk=date('Y-m',strtotime("-$i months"));
        $c_labels[]=date('M',strtotime("-$i months"));
        $c_data[]=$monthly_sales[$p['id']][$mk] ?? 0;
    }
    $has_chart = array_sum($c_data)>0;
    $cid = 'c'.$p['id'];

    // ألوان أعمدة الرسم البياني - الأعلى يكون ذهبي
    $c_max = $has_chart ? max($c_data) : 0;
    $c_colors = array_map(fn($v)=>($v==$c_max&&$v>0)?'rgba(245,158,11,0.85)':'rgba(59,130,246,0.6)', $c_data);

    // أفضل فترات البيع
    $peak_data = $monthly_sales[$p['id']] ?? [];
    arsort($peak_data);
    $peak_max_val = !empty($peak_data) ? reset($peak_data) : 0;

    $tl = $trend_labels[$trend]  ?? $trend_labels['stable'];
    $rl = $rec_labels[$rec]      ?? $rec_labels['good'];
?>
<div class="prod-card"
     data-rec="<?=$rec?>"
     data-trend="<?=$trend?>"
     data-sold="<?=$sold?>"
     data-stock="<?=$current?>"
     data-days="<?=$an['days_left']??9999?>"
     data-name="<?=htmlspecialchars(strtolower($p['name']))?>">

    <div class="card-top">
        <?php if(!empty($p['image'])): ?>
            <img src="<?=htmlspecialchars($p['image'])?>" class="prod-thumb" alt=""
                 onerror="this.outerHTML='<div class=&quot;prod-thumb-ph&quot;>🖼️</div>'">
        <?php else: ?><div class="prod-thumb-ph">🖼️</div><?php endif; ?>
        <div class="card-info">
            <div class="prod-name" title="<?=htmlspecialchars($p['name'])?>"><?=htmlspecialchars($p['name'])?></div>
            <div class="prod-meta">
                <span class="tag tag-cat"><?=htmlspecialchars($p['category_name']??'--')?></span>
                <span class="tag tag-price"><?=number_format($p['price'],0)?> دج</span>
                <span class="tag <?=$p['is_active']?'tag-on':'tag-off'?>"><?=$p['is_active']?'● نشط':'● معطل'?></span>
                <span class="age-badge">🕐 <?=$age_lbl?></span>
            </div>
        </div>
    </div>

    <div class="rec-banner rec-<?=$rec?>">
        <span class="rec-icon"><?=$rl[0]?></span>
        <div class="rec-text"><b><?=$rl[1]?></b><small><?=$rl[2]?></small></div>
    </div>

    <div class="card-stats">
        <div class="stat-box">
            <div class="stat-box-label">المخزون</div>
            <div class="stat-box-val"><?=$current?> <span style="font-size:12px;color:var(--muted)">/ <?=$initial?></span></div>
            <div class="prog-wrap"><div class="prog-fill <?=$prog_cl?>" style="width:<?=$stock_pct?>%"></div></div>
            <div class="stat-box-sub"><?=$stock_pct?>% متبقي</div>
        </div>
        <div class="stat-box">
            <div class="stat-box-label">المبيعات</div>
            <div class="stat-box-val"><?=number_format($sold)?></div>
            <div class="prog-wrap"><div class="prog-fill prog-blue" style="width:<?=$sell_pct?>%"></div></div>
            <div class="stat-box-sub"><?=$sell_pct?>% من المخزون الأولي</div>
        </div>
    </div>

    <?php if($has_chart): ?>
    <div class="mini-chart-wrap">
        <div class="mini-chart-header">
            <span class="mini-chart-lbl">📅 آخر 6 أشهر</span>
            <span class="mini-chart-total">إجمالي: <?=array_sum($c_data)?> وحدة</span>
        </div>
        <canvas class="mini-chart-canvas" id="<?=$cid?>"></canvas>
    </div>
    <?php endif; ?>

    <div class="trend-row">
        <span class="trend-chip <?=$tl[2]?>"><?=$tl[0]?> <?=$tl[1]?></span>
        <?php if($an['daily_rate']>0): ?>
            <span class="rate-chip"><?=number_format($an['daily_rate'],1)?>/يوم</span>
            <span class="rate-chip"><?=number_format($an['weekly_rate'],0)?>/أسبوع</span>
        <?php else: ?>
            <span class="rate-chip" style="background:var(--muted)">لا مبيعات</span>
        <?php endif; ?>
    </div>

    <?php if(!empty($peak_data)): ?>
    <div class="peak-row">
        <div class="peak-title">🏆 أفضل فترات البيع التاريخية</div>
        <div class="peak-months">
        <?php $sh=0; foreach($peak_data as $mk=>$qty): if($sh>=4)break;
            $dt2=DateTime::createFromFormat('Y-m',$mk);
            $lbl=$dt2?toArMonth($dt2->format('M Y'),$month_ar):$mk;
            $cls=($qty==$peak_max_val)?'top':(($qty>=$peak_max_val*.5)?'med':'low');
        ?>
            <span class="peak-m <?=$cls?>"><?=$lbl?> (<?=$qty?>)</span>
        <?php $sh++; endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <?php if(!empty($an['smart_tips'])): ?>
    <div class="smart-tips-wrap">
        <div class="smart-tips-title">💡 اقتراحات ذكية</div>
        <div class="smart-tips">
            <?php foreach($an['smart_tips'] as $tip): ?>
                <span class="tip-chip <?=$tip[0]?>"><?=$tip[1]?> <?=$tip[2]?></span>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <?php if($an['days_left']!==null && $current>0 && $an['daily_rate']>0): ?>
    <div class="days-left-row">
        <div>
            <div class="dl-lbl">ينفد المخزون خلال</div>
            <div style="display:flex;align-items:baseline;gap:4px">
                <span class="dl-val"><?=$an['days_left']?></span>
                <span class="dl-unit">يوم</span>
            </div>
        </div>
        <div style="font-size:26px"><?=$an['days_left']<7?'🔴':($an['days_left']<30?'🟡':'🟢')?></div>
    </div>
    <?php endif; ?>

    <div class="card-footer">
        <a href="edit_product.php?id=<?=$p['id']?>" class="btn btn-primary">✏️ تعديل</a>
        <a href="index.php?search=<?=urlencode($p['name'])?>" class="btn btn-outline">عرض في القائمة</a>
    </div>
</div>

<?php if($has_chart): ?>
<script>
(function(){
    var ctx=document.getElementById('<?=$cid?>');
    if(!ctx)return;
    new Chart(ctx,{
        type:'bar',
        data:{
            labels:<?=json_encode($c_labels)?>,
            datasets:[{
                data:<?=json_encode($c_data)?>,
                backgroundColor:<?=json_encode($c_colors)?>,
                borderRadius:4,
                borderSkipped:false
            }]
        },
        options:{
            responsive:true,
            maintainAspectRatio:false,
            animation:{duration:500},
            plugins:{
                legend:{display:false},
                tooltip:{rtl:true,callbacks:{label:c=>c.parsed.y+' وحدة'},titleFont:{family:'Tajawal'},bodyFont:{family:'Tajawal'}}
            },
            scales:{
                x:{ticks:{font:{family:'Tajawal',size:9},color:'#94A3B8',maxRotation:0},grid:{display:false},border:{display:false}},
                y:{display:false,beginAtZero:true}
            }
        }
    });
})();
</script>
<?php endif; ?>

<?php endforeach; ?>

<?php if(empty($products)): ?>
<div class="empty-state"><span class="ei">📦</span><p>لا توجد منتجات</p></div>
<?php endif; ?>

</div>
</div>

<script>
function filterCards(){
    const s=document.getElementById('searchInput').value.toLowerCase();
    const r=document.getElementById('recFilter').value;
    const t=document.getElementById('trendFilter').value;
    document.querySelectorAll('.prod-card').forEach(c=>{
        c.style.display=(c.dataset.name.includes(s)&&(r==='all'||c.dataset.rec===r)&&(t==='all'||c.dataset.trend===t))?'':'none';
    });
}
function sortCards(){
    const by=document.getElementById('sortFilter').value;
    const grid=document.getElementById('productsGrid');
    const cards=[...grid.querySelectorAll('.prod-card')];
    cards.sort((a,b)=>{
        if(by==='sold_desc') return +b.dataset.sold - +a.dataset.sold;
        if(by==='sold_asc')  return +a.dataset.sold - +b.dataset.sold;
        if(by==='stock_asc') return +a.dataset.stock - +b.dataset.stock;
        if(by==='days_asc')  return +a.dataset.days  - +b.dataset.days;
        return 0;
    });
    cards.forEach(c=>grid.appendChild(c));
}
</script>
</body>
</html>