<?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';

if (!isset($_GET['id'])) {
    $_SESSION['error_message'] = "لم يتم تحديد معرف المنتج!";
    header("Location: index.php"); exit;
}
$product_id = (int)$_GET['id'];

$stmt = $pdo->prepare("SELECT * FROM products WHERE id = ?");
$stmt->execute([$product_id]);
$product = $stmt->fetch();
if (!$product) {
    $_SESSION['error_message'] = "المنتج غير موجود!";
    header("Location: index.php"); exit;
}

$categories         = $pdo->query("SELECT * FROM categories ORDER BY name")->fetchAll();
$attributes         = $pdo->query("SELECT * FROM attributes ORDER BY name")->fetchAll();
$delivery_companies = $pdo->query("SELECT * FROM delivery_companies ORDER BY name")->fetchAll();

$stmt = $pdo->prepare("SELECT delivery_company_id FROM product_delivery_companies WHERE product_id = ?");
$stmt->execute([$product_id]);
$product_dc = $stmt->fetchAll(PDO::FETCH_COLUMN);

$stmt = $pdo->prepare("SELECT * FROM product_images WHERE product_id = ? ORDER BY is_primary DESC");
$stmt->execute([$product_id]);
$product_images = $stmt->fetchAll();

$stmt = $pdo->prepare("SELECT * FROM product_variants WHERE product_id = ? ORDER BY id");
$stmt->execute([$product_id]);
$variants = $stmt->fetchAll();

foreach ($variants as &$variant) {
    $s = $pdo->prepare("SELECT * FROM variant_images WHERE variant_id = ?");
    $s->execute([$variant['id']]);
    $variant['images'] = $s->fetchAll();

    $s = $pdo->prepare("SELECT * FROM variant_attributes WHERE variant_id = ?");
    $s->execute([$variant['id']]);
    $variant['attributes'] = $s->fetchAll();
}
unset($variant);

/* ── دوال الرفع ── */
function processImageFile($file, $upload_dir, $product_id, $variant_id = null) {
    $allowed = ['image/jpeg','image/png','image/gif','image/webp'];
    if (!in_array($file['type'], $allowed))       { $_SESSION['error_message'] = "نوع غير مدعوم: ".$file['name']; return false; }
    if ($file['size'] > 2*1024*1024)              { $_SESSION['error_message'] = "حجم كبير جداً: ".$file['name']; return false; }
    if (!is_uploaded_file($file['tmp_name']))      { $_SESSION['error_message'] = "ملف غير صالح: ".$file['name']; return false; }
    $ext  = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    $name = uniqid('img_').'.'.$ext;
    if (!move_uploaded_file($file['tmp_name'], $upload_dir.$name)) { $_SESSION['error_message'] = "فشل الرفع: ".$file['name']; return false; }
    chmod($upload_dir.$name, 0644);
    $base = 'Uploads/products/';
    return $variant_id ? $base.$product_id.'/variants/'.$variant_id.'/'.$name : $base.$product_id.'/'.$name;
}

function uploadImages($files, $product_id, $variant_id = null) {
    $uploaded   = [];
    $upload_dir = dirname(__FILE__).'/Uploads/products/'.$product_id.($variant_id ? '/variants/'.$variant_id : '').'/';
    if (!file_exists($upload_dir) && !mkdir($upload_dir, 0755, true)) { $_SESSION['error_message'] = "تعذر إنشاء مجلد الرفع"; return $uploaded; }
    if (!is_writable($upload_dir)) { $_SESSION['error_message'] = "المجلد غير قابل للكتابة"; return $uploaded; }
    if (!isset($files['name']) || empty($files['name'][0])) return $uploaded;
    $names = (array)$files['name']; $types = (array)$files['type'];
    $tmps  = (array)$files['tmp_name']; $errs = (array)$files['error']; $sizes = (array)$files['size'];
    foreach ($names as $i => $n) {
        if (empty($n) || $errs[$i] !== UPLOAD_ERR_OK) continue;
        $r = processImageFile(['name'=>$n,'type'=>$types[$i],'tmp_name'=>$tmps[$i],'error'=>$errs[$i],'size'=>$sizes[$i]], $upload_dir, $product_id, $variant_id);
        if ($r) $uploaded[] = ['path'=>$r];
    }
    return $uploaded;
}

/* ══════════════════════════════════════════
   معالجة POST
══════════════════════════════════════════ */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $pdo->beginTransaction();

        $name        = trim($_POST['name'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $base_price  = floatval($_POST['base_price']     ?? 0);
        $purch_price = floatval($_POST['purchase_price'] ?? 0);
        $disc_price  = !empty($_POST['discounted_price']) ? floatval($_POST['discounted_price']) : null;
        $category_id = intval($_POST['category_id'] ?? 0) ?: null;
        $is_active   = isset($_POST['is_active']) ? 1 : 0;

        // ── المخزون المباشر (للمنتجات البسيطة) ──
        $direct_stock = intval($_POST['direct_stock'] ?? 0);

        // ── هل تغيّر المخزون المباشر؟ إن نعم نحدّث initial إن كان أكبر ──
        // القاعدة: initial_stock_quantity يُحدَّث فقط إن أضاف المستخدم كمية جديدة (أكبر من الحالية)
        $old_stock   = intval($product['stock_quantity'] ?? 0);
        $old_initial = intval($product['initial_stock_quantity'] ?? 0);
        $stock_added = max(0, $direct_stock - $old_stock);  // الكمية المضافة
        $new_initial = $old_initial + $stock_added;          // نضيفها للـ initial

        if (empty($name))     throw new Exception("اسم المنتج مطلوب");
        if ($base_price <= 0) throw new Exception("سعر البيع يجب أن يكون أكبر من 0");

        // 1. تحديث المنتج
        $pdo->prepare("
            UPDATE products SET
                category_id=:cat, name=:name, description=:desc,
                price=:price, purchase_price=:pprice, discounted_price=:dprice,
                stock_quantity=:stock, initial_stock_quantity=:initial,
                is_active=:active
            WHERE id=:id
        ")->execute([
            ':cat'     => $category_id,
            ':name'    => $name,
            ':desc'    => $description,
            ':price'   => $base_price,
            ':pprice'  => $purch_price,
            ':dprice'  => $disc_price,
            ':stock'   => $direct_stock,
            ':initial' => $new_initial,
            ':active'  => $is_active,
            ':id'      => $product_id,
        ]);

        // 2. شركات التوصيل
        $pdo->prepare("DELETE FROM product_delivery_companies WHERE product_id=?")->execute([$product_id]);
        if (!empty($_POST['delivery_companies'])) {
            $stmtDc = $pdo->prepare("INSERT INTO product_delivery_companies (product_id, delivery_company_id) VALUES (?,?)");
            foreach ($_POST['delivery_companies'] as $dc_id) $stmtDc->execute([$product_id, (int)$dc_id]);
        }

        // 3. حذف صور محددة
        if (!empty($_POST['delete_images'])) {
            foreach ($_POST['delete_images'] as $img_id) {
                $row = $pdo->prepare("SELECT image_url FROM product_images WHERE id=?");
                $row->execute([$img_id]);
                $img = $row->fetchColumn();
                if ($img && file_exists($img)) @unlink($img);
                $pdo->prepare("DELETE FROM product_images WHERE id=?")->execute([$img_id]);
            }
        }

        // 4. رفع صور رئيسية جديدة
        if (!empty($_FILES['main_images']['name'][0])) {
            $main_images = uploadImages($_FILES['main_images'], $product_id);
            $primary_idx = (int)($_POST['primary_main_image'] ?? 0);
            $stmtImg = $pdo->prepare("INSERT INTO product_images (product_id, image_url, is_primary) VALUES (?,?,?)");
            foreach ($main_images as $i => $img) $stmtImg->execute([$product_id, $img['path'], $i===$primary_idx ? 1 : 0]);
        }

        // تعيين صورة رئيسية من الموجودة
        if (!empty($_POST['primary_image'])) {
            $pdo->prepare("UPDATE product_images SET is_primary=0 WHERE product_id=?")->execute([$product_id]);
            $pdo->prepare("UPDATE product_images SET is_primary=1 WHERE id=?")->execute([$_POST['primary_image']]);
        }

        // 5. المتغيرات
        $existing_variant_ids  = array_column($variants, 'id');
        $submitted_variant_ids = [];

        if (!empty($_POST['variants'])) {
            foreach ($_POST['variants'] as $idx => $variant) {
                $vid       = !empty($variant['id']) ? (int)$variant['id'] : null;
                $v_price   = !empty($variant['price'])          ? floatval($variant['price'])          : $base_price;
                $v_purch   = !empty($variant['purchase_price']) ? floatval($variant['purchase_price'])  : $purch_price;
                $v_sku     = !empty($variant['sku'])            ? trim($variant['sku'])                 : 'SKU-'.$product_id.'-'.uniqid();
                $v_stock   = (int)($variant['stock'] ?? 0);
                $v_default = isset($variant['is_default']) ? 1 : 0;

                if ($vid) {
                    /* ── متغير موجود: نحسب إن أُضيفت كمية جديدة ── */
                    $oldV = $pdo->prepare("SELECT stock, initial_stock FROM product_variants WHERE id=?");
                    $oldV->execute([$vid]);
                    $oldVRow = $oldV->fetch();

                    $v_old_stock   = intval($oldVRow['stock']         ?? 0);
                    $v_old_initial = intval($oldVRow['initial_stock']  ?? 0);
                    $v_added       = max(0, $v_stock - $v_old_stock);
                    $v_new_initial = $v_old_initial + $v_added;

                    $pdo->prepare("
                        UPDATE product_variants SET
                            sku=:sku, price=:price, purchase_price=:pprice,
                            stock=:stock, initial_stock=:initial, is_default=:def
                        WHERE id=:id
                    ")->execute([
                        ':sku'     => $v_sku,
                        ':price'   => $v_price,
                        ':pprice'  => $v_purch,
                        ':stock'   => $v_stock,
                        ':initial' => $v_new_initial,
                        ':def'     => $v_default,
                        ':id'      => $vid,
                    ]);
                    $submitted_variant_ids[] = $vid;

                } else {
                    /* ── متغير جديد: initial = stock عند الإنشاء ── */
                    $pdo->prepare("
                        INSERT INTO product_variants
                            (product_id, sku, price, purchase_price, stock, initial_stock, is_default)
                        VALUES
                            (:pid, :sku, :price, :pprice, :stock, :initial, :def)
                    ")->execute([
                        ':pid'     => $product_id,
                        ':sku'     => $v_sku,
                        ':price'   => $v_price,
                        ':pprice'  => $v_purch,
                        ':stock'   => $v_stock,
                        ':initial' => $v_stock,
                        ':def'     => $v_default,
                    ]);
                    $vid = $pdo->lastInsertId();
                    $submitted_variant_ids[] = $vid;
                }

                // خصائص المتغير
                $pdo->prepare("DELETE FROM variant_attributes WHERE variant_id=?")->execute([$vid]);
                if (!empty($variant['attributes'])) {
                    $stmtA = $pdo->prepare("INSERT INTO variant_attributes (variant_id,attribute_id,attribute_value) VALUES (?,?,?)");
                    foreach ($variant['attributes'] as $attr_id => $attr_val)
                        if (!empty($attr_val)) $stmtA->execute([$vid, $attr_id, $attr_val]);
                }

                // حذف صور متغير
                if (!empty($_POST['delete_variant_images'][$idx])) {
                    foreach ($_POST['delete_variant_images'][$idx] as $img_id) {
                        $row = $pdo->prepare("SELECT image_url FROM variant_images WHERE id=?");
                        $row->execute([$img_id]);
                        $img = $row->fetchColumn();
                        if ($img && file_exists($img)) @unlink($img);
                        $pdo->prepare("DELETE FROM variant_images WHERE id=?")->execute([$img_id]);
                    }
                }

                // رفع صور متغير جديدة
                if (!empty($_FILES['variant_images']['name'][$idx][0])) {
                    $v_files = [
                        'name'     => $_FILES['variant_images']['name'][$idx],
                        'type'     => $_FILES['variant_images']['type'][$idx],
                        'tmp_name' => $_FILES['variant_images']['tmp_name'][$idx],
                        'error'    => $_FILES['variant_images']['error'][$idx],
                        'size'     => $_FILES['variant_images']['size'][$idx],
                    ];
                    $v_images = uploadImages($v_files, $product_id, $vid);
                    if (!empty($v_images)) {
                        $v_pri  = (int)($_POST['primary_variant_image'][$idx] ?? 0);
                        $stmtVI = $pdo->prepare("INSERT INTO variant_images (variant_id,image_url,is_primary) VALUES (?,?,?)");
                        foreach ($v_images as $vi => $vimg) $stmtVI->execute([$vid, $vimg['path'], $vi===$v_pri ? 1 : 0]);
                    }
                }

                // الصورة الرئيسية الموجودة للمتغير
                if (!empty($_POST['primary_variant_image_existing'][$idx])) {
                    $pdo->prepare("UPDATE variant_images SET is_primary=0 WHERE variant_id=?")->execute([$vid]);
                    $pdo->prepare("UPDATE variant_images SET is_primary=1 WHERE id=?")->execute([$_POST['primary_variant_image_existing'][$idx]]);
                }
            }
        }

        // حذف المتغيرات المحذوفة من الفورم
        foreach (array_diff($existing_variant_ids, $submitted_variant_ids) as $del_vid) {
            $imgs = $pdo->prepare("SELECT image_url FROM variant_images WHERE variant_id=?");
            $imgs->execute([$del_vid]);
            foreach ($imgs->fetchAll() as $img) if (file_exists($img['image_url'])) @unlink($img['image_url']);
            $pdo->prepare("DELETE FROM variant_images WHERE variant_id=?")->execute([$del_vid]);
            $pdo->prepare("DELETE FROM variant_attributes WHERE variant_id=?")->execute([$del_vid]);
            $pdo->prepare("DELETE FROM product_variants WHERE id=?")->execute([$del_vid]);
        }

        $pdo->commit();
        $_SESSION['message'] = "✅ تم تحديث المنتج «{$name}» بنجاح";
        header("Location: index.php"); exit;

    } catch (Exception $e) {
        $pdo->rollBack();
        $_SESSION['error_message'] = $e->getMessage();
        header("Location: edit_product.php?id=$product_id"); exit;
    }
}

/* ── حساب المبيعات للعرض في الصفحة ── */
$has_variants  = count($variants) > 0;
if ($has_variants) {
    $curr_stock = array_sum(array_column($variants, 'stock'));
    $init_stock = array_sum(array_column($variants, 'initial_stock'));
} else {
    $curr_stock = intval($product['stock_quantity']         ?? 0);
    $init_stock = intval($product['initial_stock_quantity'] ?? 0);
}
$sold_count = max(0, $init_stock - $curr_stock);
$sold_pct   = $init_stock > 0 ? round(($sold_count / $init_stock) * 100) : 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>تعديل المنتج - <?= htmlspecialchars($product['name']) ?></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;
    --teal:      #0D9488; --teal-l:    #CCFBF1;
    --purple:    #7C3AED; --purple-l:  #EDE9FE;
    --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:1100px;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:22px;animation:fadeDown 0.4s ease}
@keyframes fadeDown{from{opacity:0;transform:translateY(-12px)}to{opacity:1;transform:translateY(0)}}
.header h1{color:var(--warning);font-size:20px;font-weight:900;display:flex;align-items:center;gap:10px}
.icon-wrap{background:linear-gradient(135deg,var(--warning),#F59E0B);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}

/* ── بطاقة إحصاءات المبيعات ── */
.sales-stat-card{
    display:grid;grid-template-columns:repeat(3,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)}}
.ss-item{background:var(--surface);border-radius:var(--radius);padding:16px 18px;border:1px solid var(--border);box-shadow:var(--shadow-sm);position:relative;overflow:hidden;transition:var(--tr)}
.ss-item:hover{transform:translateY(-2px);box-shadow:var(--shadow-md)}
.ss-item::after{content:'';position:absolute;bottom:0;left:0;right:0;height:3px;border-radius:0 0 var(--radius) var(--radius)}
.ss-stock::after{background:var(--success)}.ss-sold::after{background:var(--teal)}.ss-pct::after{background:var(--purple)}
.ss-icon{font-size:24px;margin-bottom:8px}
.ss-value{font-size:24px;font-weight:900;color:var(--text);line-height:1;margin-bottom:3px}
.ss-label{font-size:11px;color:var(--text-3);font-weight:700;text-transform:uppercase;letter-spacing:0.5px}
.ss-bar{height:5px;background:#E2E8F0;border-radius:10px;margin-top:10px;overflow:hidden}
.ss-bar-fill{height:100%;border-radius:10px;background:linear-gradient(90deg,var(--teal),var(--primary-l));transition:width 1s ease}

/* ── تنبيه مخزون ── */
.stock-add-hint{background:var(--teal-l);border:1.5px solid #5EEAD4;border-radius:var(--radius-sm);padding:10px 14px;font-size:12px;color:#0F766E;font-weight:700;display:flex;align-items:center;gap:8px;margin-top:8px}

.card{background:var(--surface);border-radius:var(--radius);box-shadow:var(--shadow-sm);border:1px solid var(--border);padding:24px;margin-bottom:20px;animation:fadeUp 0.4s ease both}
.card-title{font-size:15px;font-weight:900;color:var(--primary);margin-bottom:20px;display:flex;align-items:center;gap:10px;padding-bottom:14px;border-bottom:1.5px solid var(--border)}
.card-title .ct-icon{background:linear-gradient(135deg,var(--primary),var(--primary-l));color:white;width:32px;height:32px;border-radius:var(--radius-sm);display:flex;align-items:center;justify-content:center;flex-shrink:0}

.form-group{margin-bottom:18px}
.form-group label{display:block;margin-bottom:7px;font-weight:700;font-size:13px;color:var(--text)}
.req{color:var(--danger);margin-right:2px}
.opt{color:var(--text-3);font-weight:400;font-size:11px}
input[type=text],input[type=number],select,textarea{width:100%;padding:11px 14px;border:1.5px solid var(--border);border-radius:var(--radius-sm);font-size:14px;transition:var(--tr);font-family:'Tajawal',sans-serif;color:var(--text);background:white}
input:focus,select:focus,textarea:focus{border-color:var(--primary-l);outline:none;box-shadow:0 0 0 3px rgba(59,130,246,0.12)}
textarea{min-height:110px;resize:vertical}
.form-row  {display:grid;grid-template-columns:repeat(3,1fr);gap:16px}
.form-row-2{display:grid;grid-template-columns:1fr 1fr;gap:16px}
@media(max-width:768px){.form-row{grid-template-columns:1fr}}
@media(max-width:600px){.form-row-2{grid-template-columns:1fr}}

.price-wrap{display:flex;align-items:center;border:1.5px solid var(--border);border-radius:var(--radius-sm);overflow:hidden;transition:var(--tr)}
.price-wrap:focus-within{border-color:var(--primary-l);box-shadow:0 0 0 3px rgba(59,130,246,0.12)}
.price-wrap input{border:none!important;box-shadow:none!important;flex:1;padding:11px 14px}
.price-currency{padding:0 12px;background:var(--surface-2);color:var(--text-3);font-weight:700;font-size:13px;border-right:1.5px solid var(--border);white-space:nowrap}

.profit-meter{background:var(--surface-2);border:1.5px solid var(--border);border-radius:var(--radius-sm);padding:14px;margin-top:12px;display:flex;align-items:center;gap:12px;transition:var(--tr)}
.profit-meter.good{border-color:#A7F3D0;background:var(--success-l)}
.profit-meter.bad {border-color:#FECACA;background:var(--danger-l)}
.profit-meter .pm-icon{font-size:22px}
.profit-meter .pm-text{font-size:13px;font-weight:700;color:var(--text-2)}
.profit-meter .pm-value{font-size:18px;font-weight:900;margin-top:2px}
.profit-meter.good .pm-value{color:var(--success)}
.profit-meter.bad  .pm-value{color:var(--danger)}
.profit-meter .pm-pct{font-size:12px;color:var(--text-3)}

.toggle-wrap{display:flex;align-items:center;gap:12px;padding:12px 16px;background:var(--surface-2);border-radius:var(--radius-sm);border:1.5px solid var(--border);cursor:pointer;transition:var(--tr);user-select:none}
.toggle-wrap:hover{border-color:var(--primary-l)}
.toggle-wrap input[type=checkbox]{width:18px;height:18px;accent-color:var(--primary);cursor:pointer}
.toggle-wrap span{font-size:14px;font-weight:600;color:var(--text)}

.dc-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(160px,1fr));gap:8px;margin-top:4px}
.dc-item{display:flex;align-items:center;gap:8px;padding:10px 13px;background:var(--surface-2);border-radius:var(--radius-sm);border:1.5px solid var(--border);cursor:pointer;transition:var(--tr)}
.dc-item:hover{border-color:var(--primary-l);background:#EFF6FF}
.dc-item input{width:16px;height:16px;accent-color:var(--primary);cursor:pointer}
.dc-item label{font-size:13px;font-weight:600;cursor:pointer;color:var(--text)}
.dc-select-all{font-size:12px;color:var(--primary-l);cursor:pointer;font-weight:700;margin-bottom:8px;display:inline-flex;align-items:center;gap:4px}
.dc-select-all:hover{text-decoration:underline}

.upload-box{border:2px dashed var(--border);border-radius:var(--radius-sm);padding:24px;text-align:center;cursor:pointer;transition:var(--tr);background:var(--surface-2)}
.upload-box:hover{border-color:var(--primary-l);background:#EFF6FF}
.upload-box .ub-icon{font-size:32px;color:var(--primary-l);margin-bottom:8px}
.upload-box .ub-text{font-size:14px;font-weight:600;color:var(--text-2);margin-bottom:4px}
.upload-box .ub-hint{font-size:12px;color:var(--text-3)}
.img-preview-wrap{display:flex;flex-wrap:wrap;gap:10px;margin-top:12px}
.img-prev{position:relative;width:90px;height:90px;border-radius:var(--radius-sm);overflow:hidden;border:2px solid var(--border);transition:var(--tr)}
.img-prev.is-primary{border-color:var(--success);box-shadow:0 0 0 3px rgba(5,150,105,0.2)}
.img-prev.marked-delete{opacity:0.4;border-color:var(--danger)}
.img-prev img{width:100%;height:100%;object-fit:cover}
.img-prev .remove-img{position:absolute;top:4px;right:4px;width:20px;height:20px;background:var(--danger);color:white;border-radius:50%;display:flex;align-items:center;justify-content:center;cursor:pointer;font-size:10px;font-weight:900;transition:var(--tr)}
.img-prev .remove-img:hover{transform:scale(1.2)}
.img-prev .primary-lbl{position:absolute;bottom:0;left:0;right:0;background:rgba(5,150,105,0.85);color:white;font-size:10px;font-weight:800;text-align:center;padding:3px;cursor:pointer}
.img-prev:not(.is-primary) .primary-lbl{background:rgba(0,0,0,0.4)}
.existing-badge{position:absolute;top:4px;left:4px;background:rgba(30,64,175,0.8);color:white;font-size:9px;font-weight:800;padding:2px 5px;border-radius:4px}

.variant-card{border:1.5px solid var(--border);border-radius:var(--radius-sm);padding:18px;margin-bottom:16px;background:var(--surface-2);animation:fadeUp 0.3s ease}
.variant-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;padding-bottom:12px;border-bottom:1px solid var(--border)}
.variant-title{font-weight:800;color:var(--primary);font-size:14px;display:flex;align-items:center;gap:6px}
.btn-remove-variant{width:28px;height:28px;background:var(--danger-l);color:var(--danger);border:1px solid #FECACA;border-radius:50%;display:flex;align-items:center;justify-content:center;cursor:pointer;font-size:12px;font-weight:900;transition:var(--tr)}
.btn-remove-variant:hover{background:var(--danger);color:white}

/* شريط مبيعات المتغير */
.variant-sales-row{display:flex;align-items:center;gap:10px;padding:8px 12px;background:#F0FDF4;border:1px solid #BBF7D0;border-radius:var(--radius-sm);margin-bottom:12px;font-size:12px;color:#15803D;font-weight:700}
.variant-sales-bar{flex:1;height:6px;background:#E2E8F0;border-radius:10px;overflow:hidden}
.variant-sales-fill{height:100%;background:linear-gradient(90deg,var(--teal),#34D399);border-radius:10px}

.attr-row{display:grid;grid-template-columns:1fr 1fr auto;gap:8px;align-items:center;margin-bottom:8px}
.btn-remove-attr{width:30px;height:30px;background:var(--danger-l);color:var(--danger);border:1px solid #FECACA;border-radius:var(--radius-sm);display:flex;align-items:center;justify-content:center;cursor:pointer;font-size:12px;font-weight:900;transition:var(--tr);flex-shrink:0}
.btn-remove-attr:hover{background:var(--danger);color:white}

.btn{padding:10px 18px;border-radius:var(--radius-sm);font-weight:700;cursor:pointer;transition:var(--tr);text-decoration:none;display:inline-flex;align-items:center;gap:6px;font-size:13px;border:none}
.btn-warning      {background:var(--warning);color:white}
.btn-warning:hover{background:#B45309;transform:translateY(-1px)}
.btn-info         {background:var(--info);color:white}
.btn-info:hover   {background:#0369A1;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-sm           {padding:7px 12px;font-size:12px}
.form-actions{display:flex;justify-content:flex-end;gap:10px;margin-top:24px;padding-top:18px;border-top:1.5px solid var(--border)}

@media(max-width:600px){body{padding:12px}.header{flex-direction:column;align-items:flex-start;gap:12px}.form-actions{flex-direction:column}.btn{justify-content:center}}
@media(max-width:768px){.sales-stat-card{grid-template-columns:1fr}}
</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="16" height="16" viewBox="0 0 24 24" fill="none" stroke="white" 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>
            </span>
            تعديل: <?= htmlspecialchars($product['name']) ?>
        </h1>
        <a href="index.php" class="btn btn-gray">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="9 18 3 12 9 6"/><line x1="3" y1="12" x2="21" y2="12"/></svg>
            رجوع
        </a>
    </div>

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

    <!-- ══ إحصاءات المبيعات ══ -->
    <div class="sales-stat-card">
        <div class="ss-item ss-stock">
            <div class="ss-icon">📦</div>
            <div class="ss-value"><?= $curr_stock ?></div>
            <div class="ss-label">المخزون الحالي</div>
            <?php if ($init_stock > 0): ?>
                <div class="ss-bar"><div class="ss-bar-fill" style="width:<?= $init_stock > 0 ? round(($curr_stock/$init_stock)*100) : 0 ?>%;background:linear-gradient(90deg,var(--success),#34D399)"></div></div>
                <div style="font-size:10px;color:var(--text-3);margin-top:4px">من <?= $init_stock ?> أولي</div>
            <?php endif; ?>
        </div>
        <div class="ss-item ss-sold">
            <div class="ss-icon">🛒</div>
            <div class="ss-value"><?= $sold_count ?></div>
            <div class="ss-label">وحدة مباعة</div>
            <?php if ($init_stock > 0): ?>
                <div class="ss-bar"><div class="ss-bar-fill" style="width:<?= $sold_pct ?>%"></div></div>
                <div style="font-size:10px;color:var(--text-3);margin-top:4px"><?= $sold_pct ?>% من المخزون الأولي</div>
            <?php endif; ?>
        </div>
        <div class="ss-item ss-pct">
            <div class="ss-icon"><?= $sold_pct >= 75 ? '🔥' : ($sold_pct >= 40 ? '📈' : '📊') ?></div>
            <div class="ss-value"><?= $sold_pct ?>%</div>
            <div class="ss-label">نسبة المبيعات</div>
            <div style="margin-top:8px;font-size:11px;color:var(--text-3)">
                <?php if ($sold_pct >= 75): ?>
                    <span style="color:#D97706;font-weight:800">مبيعات ممتازة 🏆</span>
                <?php elseif ($sold_pct >= 40): ?>
                    <span style="color:var(--teal);font-weight:800">أداء جيد 👍</span>
                <?php elseif ($sold_pct > 0): ?>
                    <span style="color:var(--text-2);font-weight:700">يحتاج تسويق</span>
                <?php else: ?>
                    <span style="color:var(--text-3)">لا مبيعات بعد</span>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <form method="POST" enctype="multipart/form-data" id="productForm">

        <!-- ══ المعلومات الأساسية ══ -->
        <div class="card" style="animation-delay:0.05s">
            <div class="card-title">
                <span class="ct-icon"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg></span>
                المعلومات الأساسية
            </div>
            <div class="form-row-2">
                <div class="form-group">
                    <label>اسم المنتج <span class="req">*</span></label>
                    <input type="text" name="name" required value="<?= htmlspecialchars($product['name']) ?>">
                </div>
                <div class="form-group">
                    <label>الفئة <span class="opt">(اختياري)</span></label>
                    <select name="category_id">
                        <option value="">— اختر الفئة —</option>
                        <?php foreach ($categories as $cat): ?>
                            <option value="<?= $cat['id'] ?>" <?= $cat['id'] == $product['category_id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($cat['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label>وصف المنتج <span class="opt">(اختياري)</span></label>
                <textarea name="description"><?= htmlspecialchars($product['description'] ?? '') ?></textarea>
            </div>
            <div class="form-group">
                <label class="toggle-wrap" for="is_active">
                    <input type="checkbox" id="is_active" name="is_active" <?= $product['is_active'] ? 'checked' : '' ?>>
                    <span>المنتج نشط — يظهر للعملاء في المتجر</span>
                </label>
            </div>
        </div>

        <!-- ══ الأسعار ══ -->
        <div class="card" style="animation-delay:0.1s">
            <div class="card-title">
                <span class="ct-icon"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5"><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></span>
                الأسعار
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>سعر الشراء <span class="req">*</span></label>
                    <div class="price-wrap">
                        <span class="price-currency">دج</span>
                        <input type="number" name="purchase_price" id="purchasePrice" step="0.01" min="0" value="<?= $product['purchase_price'] ?? 0 ?>" oninput="updateProfitMeter()">
                    </div>
                </div>
                <div class="form-group">
                    <label>سعر البيع <span class="req">*</span></label>
                    <div class="price-wrap">
                        <span class="price-currency">دج</span>
                        <input type="number" name="base_price" id="basePrice" step="0.01" min="0" required value="<?= $product['price'] ?>" oninput="updateProfitMeter()">
                    </div>
                </div>
                <div class="form-group">
                    <label>السعر بعد الخصم <span class="opt">(اختياري)</span></label>
                    <div class="price-wrap">
                        <span class="price-currency">دج</span>
                        <input type="number" name="discounted_price" step="0.01" min="0" value="<?= $product['discounted_price'] ?? '' ?>" placeholder="0">
                    </div>
                </div>
            </div>
            <div class="profit-meter" id="profitMeter">
                <div class="pm-icon">💰</div>
                <div>
                    <div class="pm-text">الربح المتوقع لكل وحدة</div>
                    <div class="pm-value" id="profitValue">—</div>
                    <div class="pm-pct" id="profitPct">جاري الحساب...</div>
                </div>
            </div>
        </div>

        <!-- ══ المخزون المباشر (للمنتجات البسيطة) ══ -->
        <?php if (!$has_variants): ?>
        <div class="card" style="animation-delay:0.13s">
            <div class="card-title">
                <span class="ct-icon"><svg width="15" height="15" 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"/></svg></span>
                الكمية المتاحة
                <span style="color:var(--text-3);font-size:11px;font-weight:400">(منتج بسيط بدون متغيرات)</span>
            </div>

            <div class="form-row-2">
                <div class="form-group">
                    <label>الكمية في المخزن</label>
                    <input type="number" name="direct_stock" id="directStock" min="0" value="<?= $product['stock_quantity'] ?? 0 ?>" oninput="previewStockChange(this.value)">
                    <div class="stock-add-hint" id="stockAddHint" style="display:none">
                        💡 أنت تضيف <strong id="stockAddedNum">0</strong> وحدة جديدة — سيُضاف للمخزون الأولي تلقائياً
                    </div>
                </div>
                <div class="form-group">
                    <label>المخزون الأولي (للمعلومية)</label>
                    <input type="number" value="<?= $product['initial_stock_quantity'] ?? 0 ?>" disabled style="background:#F8FAFC;color:var(--text-3);cursor:not-allowed">
                    <small style="font-size:11px;color:var(--text-3);margin-top:4px;display:block">يُحدَّث تلقائياً عند إضافة كميات جديدة</small>
                </div>
            </div>
        </div>
        <?php else: ?>
        <div style="background:var(--warning-l);border:1px solid #FCD34D;border-radius:var(--radius-sm);padding:11px 15px;font-size:12px;color:var(--warning);font-weight:700;margin-bottom:18px;display:flex;align-items:center;gap:8px">
            ⚠️ هذا المنتج له متغيرات — الكمية تُدار من كل متغير على حدة في الأسفل
        </div>
        <?php endif; ?>

        <!-- ══ شركات التوصيل ══ -->
        <div class="card" style="animation-delay:0.16s">
            <div class="card-title">
                <span class="ct-icon"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="white" 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></span>
                شركات التوصيل المتاحة
            </div>
            <span class="dc-select-all" onclick="toggleAllDC()">
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="9 11 12 14 22 4"/><path d="M21 12v7a2 2 0 01-2 2H5a2 2 0 01-2-2V5a2 2 0 012-2h11"/></svg>
                تحديد الكل / إلغاء
            </span>
            <div class="dc-grid">
                <?php foreach ($delivery_companies as $dc): ?>
                <div class="dc-item">
                    <input type="checkbox" id="dc_<?= $dc['id'] ?>" name="delivery_companies[]" value="<?= $dc['id'] ?>" class="dc-checkbox" <?= in_array($dc['id'], $product_dc) ? 'checked' : '' ?>>
                    <label for="dc_<?= $dc['id'] ?>"><?= htmlspecialchars($dc['name']) ?></label>
                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- ══ الصور الرئيسية ══ -->
        <div class="card" style="animation-delay:0.19s">
            <div class="card-title">
                <span class="ct-icon"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg></span>
                صور المنتج الرئيسية
            </div>

            <?php if (!empty($product_images)): ?>
            <div style="margin-bottom:14px">
                <p style="font-size:12px;font-weight:700;color:var(--text-3);margin-bottom:8px;text-transform:uppercase;letter-spacing:0.5px">الصور الحالية</p>
                <div class="img-preview-wrap" id="existingMainImages">
                    <?php foreach ($product_images as $img): ?>
                    <div class="img-prev <?= $img['is_primary'] ? 'is-primary' : '' ?>" id="existing_img_<?= $img['id'] ?>">
                        <img src="<?= htmlspecialchars($img['image_url']) ?>" alt="">
                        <span class="existing-badge">موجودة</span>
                        <div class="remove-img" onclick="markDeleteImage(<?= $img['id'] ?>, this)" title="حذف">✕</div>
                        <div class="primary-lbl" onclick="setPrimaryExisting(<?= $img['id'] ?>)"><?= $img['is_primary'] ? '✓ رئيسية' : 'تعيين رئيسية' ?></div>
                        <input type="checkbox" name="delete_images[]" value="<?= $img['id'] ?>" id="del_img_<?= $img['id'] ?>" style="display:none">
                        <input type="radio"    name="primary_image"   value="<?= $img['id'] ?>" <?= $img['is_primary'] ? 'checked' : '' ?> style="display:none">
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>

            <div class="upload-box" onclick="document.getElementById('mainImages').click()">
                <div class="ub-icon">📤</div>
                <p class="ub-text">إضافة صور جديدة</p>
                <p class="ub-hint">JPG، PNG، GIF، WebP — 2MB حد أقصى</p>
                <input type="file" id="mainImages" name="main_images[]" multiple accept="image/*" style="display:none" onchange="handleMainImages(this)">
            </div>
            <input type="hidden" name="primary_main_image" id="primaryMainImage" value="0">
            <div class="img-preview-wrap" id="newMainImagesPreview"></div>
        </div>

        <!-- ══ المتغيرات ══ -->
        <div class="card" style="animation-delay:0.22s">
            <div class="card-title">
                <span class="ct-icon"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg></span>
                متغيرات المنتج
                <span style="color:var(--text-3);font-size:11px;font-weight:400">(اختياري)</span>
            </div>

            <button type="button" class="btn btn-info btn-sm" id="addVariantBtn" style="margin-bottom:16px">
                <svg width="13" height="13" 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>
                إضافة متغير جديد
            </button>

            <div id="variantsContainer">
                <?php foreach ($variants as $idx => $variant):
                    $v_sold = max(0, intval($variant['initial_stock'] ?? 0) - intval($variant['stock']));
                    $v_init = intval($variant['initial_stock'] ?? 0);
                    $v_pct  = $v_init > 0 ? round(($v_sold / $v_init) * 100) : 0;
                ?>
                <div class="variant-card" data-variant-index="<?= $idx ?>">
                    <div class="variant-header">
                        <span class="variant-title">
                            <svg width="14" height="14" 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>
                            متغير #<?= $idx + 1 ?>
                        </span>
                        <button type="button" class="btn-remove-variant" onclick="removeVariant(this)">✕</button>
                    </div>
                    <input type="hidden" name="variants[<?= $idx ?>][id]" value="<?= $variant['id'] ?>">

                    <!-- شريط مبيعات المتغير -->
                    <?php if ($v_init > 0): ?>
                    <div class="variant-sales-row">
                        <span>🛒 مباع: <strong><?= $v_sold ?></strong> / <?= $v_init ?></span>
                        <div class="variant-sales-bar">
                            <div class="variant-sales-fill" style="width:<?= $v_pct ?>%"></div>
                        </div>
                        <span><?= $v_pct ?>%</span>
                    </div>
                    <?php endif; ?>

                    <div class="form-row">
                        <div class="form-group">
                            <label>كود SKU <span class="opt">(تلقائي)</span></label>
                            <input type="text" name="variants[<?= $idx ?>][sku]" value="<?= htmlspecialchars($variant['sku']) ?>">
                        </div>
                        <div class="form-group">
                            <label>سعر الشراء (دج)</label>
                            <div class="price-wrap">
                                <span class="price-currency">دج</span>
                                <input type="number" name="variants[<?= $idx ?>][purchase_price]" step="0.01" min="0" value="<?= $variant['purchase_price'] ?? 0 ?>">
                            </div>
                        </div>
                        <div class="form-group">
                            <label>سعر البيع (دج)</label>
                            <div class="price-wrap">
                                <span class="price-currency">دج</span>
                                <input type="number" name="variants[<?= $idx ?>][price]" step="0.01" min="0" value="<?= $variant['price'] ?>">
                            </div>
                        </div>
                    </div>

                    <div class="form-row-2">
                        <div class="form-group">
                            <label>الكمية الحالية</label>
                            <input type="number" name="variants[<?= $idx ?>][stock]" min="0" value="<?= $variant['stock'] ?>"
                                   oninput="previewVariantStockChange(this, <?= intval($variant['stock']) ?>, <?= intval($variant['initial_stock'] ?? 0) ?>)">
                            <small style="font-size:11px;color:var(--text-3);margin-top:4px;display:block">
                                المخزون الأولي: <strong><?= $variant['initial_stock'] ?? 0 ?></strong> وحدة
                            </small>
                            <div class="stock-add-hint variant-stock-hint-<?= $idx ?>" style="display:none;margin-top:6px">
                                💡 تضيف <strong class="v-add-num">0</strong> وحدة — ستُضاف للمخزون الأولي
                            </div>
                        </div>
                        <div class="form-group" style="display:flex;align-items:flex-end">
                            <label class="toggle-wrap" style="width:100%">
                                <input type="checkbox" name="variants[<?= $idx ?>][is_default]" <?= $variant['is_default'] ? 'checked' : '' ?>>
                                <span>المتغير الافتراضي</span>
                            </label>
                        </div>
                    </div>

                    <!-- صور المتغير الموجودة -->
                    <?php if (!empty($variant['images'])): ?>
                    <div style="margin-bottom:10px">
                        <p style="font-size:12px;font-weight:700;color:var(--text-3);margin-bottom:8px">الصور الحالية للمتغير</p>
                        <div class="img-preview-wrap">
                            <?php foreach ($variant['images'] as $vimg): ?>
                            <div class="img-prev <?= $vimg['is_primary'] ? 'is-primary' : '' ?>" id="existing_vimg_<?= $vimg['id'] ?>">
                                <img src="<?= htmlspecialchars($vimg['image_url']) ?>" alt="">
                                <span class="existing-badge">موجودة</span>
                                <div class="remove-img" onclick="markDeleteVariantImage(<?= $vimg['id'] ?>, <?= $idx ?>, this)">✕</div>
                                <div class="primary-lbl" onclick="setPrimaryVariantExisting(<?= $vimg['id'] ?>, <?= $idx ?>)"><?= $vimg['is_primary'] ? '✓ رئيسية' : 'تعيين رئيسية' ?></div>
                                <input type="checkbox" name="delete_variant_images[<?= $idx ?>][]" value="<?= $vimg['id'] ?>" id="del_vimg_<?= $vimg['id'] ?>" style="display:none">
                                <input type="radio"    name="primary_variant_image_existing[<?= $idx ?>]" value="<?= $vimg['id'] ?>" <?= $vimg['is_primary'] ? 'checked' : '' ?> style="display:none">
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    <?php endif; ?>

                    <div class="form-group">
                        <label>إضافة صور جديدة للمتغير <span class="opt">(اختياري)</span></label>
                        <div class="upload-box" onclick="this.querySelector('input[type=file]').click()">
                            <div class="ub-icon">🖼️</div>
                            <p class="ub-text">رفع صور المتغير</p>
                            <p class="ub-hint">JPG، PNG، GIF — 2MB</p>
                            <input type="file" name="variant_images[<?= $idx ?>][]" multiple accept="image/*" style="display:none" onchange="handleVariantImages(this)">
                        </div>
                        <input type="hidden" name="primary_variant_image[<?= $idx ?>]" class="primary-variant-image" value="0">
                        <div class="img-preview-wrap variant-images-preview"></div>
                    </div>

                    <!-- خصائص المتغير -->
                    <div>
                        <div style="font-size:13px;font-weight:700;color:var(--text);margin-bottom:10px">الخصائص</div>
                        <div class="attr-rows">
                            <?php foreach ($variant['attributes'] as $attr): ?>
                            <div class="attr-row">
                                <select class="attr-select" onchange="updateAttrValues(this)">
                                    <option value="">— اختر خاصية —</option>
                                    <?php foreach ($attributes as $a): ?>
                                        <option value="<?= $a['id'] ?>" <?= $a['id'] == $attr['attribute_id'] ? 'selected' : '' ?>><?= htmlspecialchars($a['name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <select class="attr-value-select" name="variants[<?= $idx ?>][attributes][<?= $attr['attribute_id'] ?>]">
                                    <?php
                                    $found = null;
                                    foreach ($attributes as $a) { if ($a['id'] == $attr['attribute_id']) { $found = $a; break; } }
                                    if ($found && $found['values_list']) {
                                        foreach (array_map('trim', explode(',', $found['values_list'])) as $v) {
                                            echo '<option value="'.htmlspecialchars($v).'"'.($v == $attr['attribute_value'] ? ' selected' : '').'>'.htmlspecialchars($v).'</option>';
                                        }
                                    }
                                    ?>
                                </select>
                                <button type="button" class="btn-remove-attr" onclick="this.closest('.attr-row').remove()">✕</button>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <button type="button" class="btn btn-gray btn-sm" onclick="addAttrRow(this)">
                            <svg width="12" height="12" 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>
                            إضافة خاصية
                        </button>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- ══ حفظ ══ -->
        <div class="form-actions">
            <a href="index.php" class="btn btn-gray">إلغاء</a>
            <button type="submit" class="btn btn-warning">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M19 21H5a2 2 0 01-2-2V5a2 2 0 012-2h11l5 5v11a2 2 0 01-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>
                حفظ التعديلات
            </button>
        </div>
    </form>
</div>

<!-- VARIANT TEMPLATE للمتغيرات الجديدة -->
<template id="variantTemplate">
    <div class="variant-card" data-variant-index="">
        <div class="variant-header">
            <span class="variant-title">
                <svg width="14" height="14" 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>
                متغير جديد #<span class="v-num"></span>
            </span>
            <button type="button" class="btn-remove-variant" onclick="removeVariant(this)">✕</button>
        </div>
        <div class="form-row">
            <div class="form-group">
                <label>كود SKU <span class="opt">(تلقائي)</span></label>
                <input type="text" name="variants[{vi}][sku]" placeholder="SKU-001">
            </div>
            <div class="form-group">
                <label>سعر الشراء (دج)</label>
                <div class="price-wrap"><span class="price-currency">دج</span><input type="number" name="variants[{vi}][purchase_price]" step="0.01" min="0" value="0"></div>
            </div>
            <div class="form-group">
                <label>سعر البيع (دج)</label>
                <div class="price-wrap"><span class="price-currency">دج</span><input type="number" name="variants[{vi}][price]" step="0.01" min="0" placeholder="السعر الأساسي"></div>
            </div>
        </div>
        <div class="form-row-2">
            <div class="form-group">
                <label>الكمية (المخزون الأولي) <span style="color:var(--danger)">*</span></label>
                <input type="number" name="variants[{vi}][stock]" min="0" value="0">
                <small style="font-size:11px;color:var(--text-3);margin-top:4px;display:block">💡 ستُحفظ كمخزون أولي</small>
            </div>
            <div class="form-group" style="display:flex;align-items:flex-end">
                <label class="toggle-wrap" style="width:100%">
                    <input type="checkbox" name="variants[{vi}][is_default]">
                    <span>المتغير الافتراضي</span>
                </label>
            </div>
        </div>
        <div class="form-group">
            <label>صور المتغير <span class="opt">(اختياري)</span></label>
            <div class="upload-box" onclick="this.querySelector('input[type=file]').click()">
                <div class="ub-icon">🖼️</div><p class="ub-text">رفع الصور</p><p class="ub-hint">2MB حد أقصى</p>
                <input type="file" name="variant_images[{vi}][]" multiple accept="image/*" style="display:none" onchange="handleVariantImages(this)">
            </div>
            <input type="hidden" name="primary_variant_image[{vi}]" class="primary-variant-image" value="0">
            <div class="img-preview-wrap variant-images-preview"></div>
        </div>
        <div>
            <div style="font-size:13px;font-weight:700;color:var(--text);margin-bottom:10px">الخصائص <span class="opt">(اختياري)</span></div>
            <div class="attr-rows"></div>
            <button type="button" class="btn btn-gray btn-sm" onclick="addAttrRow(this)">
                <svg width="12" height="12" 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>
                إضافة خاصية
            </button>
        </div>
    </div>
</template>

<template id="attrRowTemplate">
    <div class="attr-row">
        <select class="attr-select" onchange="updateAttrValues(this)">
            <option value="">— اختر خاصية —</option>
            <?php foreach ($attributes as $attr): ?>
                <option value="<?= $attr['id'] ?>"><?= htmlspecialchars($attr['name']) ?></option>
            <?php endforeach; ?>
        </select>
        <select class="attr-value-select" name="" disabled>
            <option value="">اختر خاصية أولاً</option>
        </select>
        <button type="button" class="btn-remove-attr" onclick="this.closest('.attr-row').remove()">✕</button>
    </div>
</template>

<script>
let vc = <?= count($variants) ?>;
const attrsData   = <?= json_encode($attributes) ?>;
const oldDirectStock = <?= intval($product['stock_quantity'] ?? 0) ?>;
const newMainDT   = new DataTransfer();
const varDT       = {};

/* ── مؤشر الربح ── */
function updateProfitMeter() {
    const buy  = parseFloat(document.getElementById('purchasePrice').value) || 0;
    const sell = parseFloat(document.getElementById('basePrice').value)     || 0;
    const meter = document.getElementById('profitMeter');
    const valEl = document.getElementById('profitValue');
    const pctEl = document.getElementById('profitPct');
    if (sell === 0) { meter.className='profit-meter'; valEl.textContent='—'; pctEl.textContent='أدخل الأسعار أعلاه'; return; }
    const profit = sell - buy;
    const pct    = ((profit / sell) * 100).toFixed(1);
    valEl.textContent = (profit >= 0 ? '+' : '') + profit.toLocaleString('ar-DZ') + ' دج';
    pctEl.textContent = 'هامش الربح: ' + pct + '%';
    meter.className   = 'profit-meter ' + (profit >= 0 ? 'good' : 'bad');
    meter.querySelector('.pm-icon').textContent = profit >= 0 ? '💰' : '⚠️';
}

/* ── تنبيه إضافة مخزون مباشر ── */
function previewStockChange(newVal) {
    const added = parseInt(newVal) - oldDirectStock;
    const hint  = document.getElementById('stockAddHint');
    const num   = document.getElementById('stockAddedNum');
    if (added > 0) {
        num.textContent = added;
        hint.style.display = 'flex';
    } else {
        hint.style.display = 'none';
    }
}

/* ── تنبيه إضافة مخزون متغير ── */
function previewVariantStockChange(input, oldStock, oldInitial) {
    const idx   = input.closest('.variant-card').dataset.variantIndex;
    const added = parseInt(input.value) - oldStock;
    const hint  = document.querySelector('.variant-stock-hint-' + idx);
    if (!hint) return;
    if (added > 0) {
        hint.querySelector('.v-add-num').textContent = added;
        hint.style.display = 'flex';
    } else {
        hint.style.display = 'none';
    }
}

/* ── شركات التوصيل ── */
function toggleAllDC() {
    const cbs = document.querySelectorAll('.dc-checkbox');
    const any = Array.from(cbs).some(c => !c.checked);
    cbs.forEach(c => c.checked = any);
}

/* ── صور موجودة ── */
function markDeleteImage(imgId, btn) {
    const wrap = document.getElementById('existing_img_' + imgId);
    const cb   = document.getElementById('del_img_' + imgId);
    cb.checked = !cb.checked;
    wrap.classList.toggle('marked-delete', cb.checked);
    btn.textContent = cb.checked ? '↩' : '✕';
}

function setPrimaryExisting(imgId) {
    document.querySelectorAll('#existingMainImages .img-prev').forEach(p => {
        p.classList.remove('is-primary');
        p.querySelector('.primary-lbl').textContent = 'تعيين رئيسية';
        const r = p.querySelector('input[type=radio]'); if (r) r.checked = false;
    });
    const wrap = document.getElementById('existing_img_' + imgId);
    wrap.classList.add('is-primary');
    wrap.querySelector('.primary-lbl').textContent = '✓ رئيسية';
    wrap.querySelector('input[type=radio]').checked = true;
}

function markDeleteVariantImage(imgId, varIdx, btn) {
    const wrap = document.getElementById('existing_vimg_' + imgId);
    const cb   = document.getElementById('del_vimg_' + imgId);
    cb.checked = !cb.checked;
    wrap.classList.toggle('marked-delete', cb.checked);
    btn.textContent = cb.checked ? '↩' : '✕';
}

function setPrimaryVariantExisting(imgId, varIdx) {
    const card = document.querySelector('.variant-card[data-variant-index="'+varIdx+'"]');
    card.querySelectorAll('.img-preview-wrap .img-prev').forEach(p => {
        p.classList.remove('is-primary');
        p.querySelector('.primary-lbl').textContent = 'تعيين رئيسية';
        const r = p.querySelector('input[type=radio]'); if (r) r.checked = false;
    });
    const wrap = document.getElementById('existing_vimg_' + imgId);
    wrap.classList.add('is-primary');
    wrap.querySelector('.primary-lbl').textContent = '✓ رئيسية';
    wrap.querySelector('input[type=radio]').checked = true;
}

/* ── رفع صور جديدة ── */
function handleMainImages(input) {
    newMainDT.items.clear();
    Array.from(input.files).forEach(f => {
        if (f.size > 2*1024*1024) { alert('حجم كبير: '+f.name); return; }
        newMainDT.items.add(f);
    });
    input.files = newMainDT.files;
    renderPreviews(newMainDT.files, 'newMainImagesPreview', 'main');
}

function handleVariantImages(input) {
    const idx = input.closest('.variant-card').dataset.variantIndex;
    if (!varDT[idx]) varDT[idx] = new DataTransfer();
    varDT[idx].items.clear();
    Array.from(input.files).forEach(f => {
        if (f.size > 2*1024*1024) { alert('حجم كبير: '+f.name); return; }
        varDT[idx].items.add(f);
    });
    input.files = varDT[idx].files;
    const wrap = input.closest('.form-group').querySelector('.variant-images-preview');
    renderPreviews(varDT[idx].files, null, 'variant-'+idx, wrap);
}

function renderPreviews(files, containerId, type, containerEl=null) {
    const wrap = containerEl || document.getElementById(containerId);
    wrap.innerHTML = '';
    Array.from(files).forEach((file, i) => {
        const reader = new FileReader();
        reader.onload = e => {
            const div = document.createElement('div');
            div.className = 'img-prev' + (i===0 ? ' is-primary' : '');
            const img = document.createElement('img'); img.src = e.target.result;
            const rm  = document.createElement('div'); rm.className='remove-img'; rm.textContent='✕';
            rm.onclick = () => {
                if (type==='main') {
                    newMainDT.items.remove(i);
                    document.getElementById('mainImages').files = newMainDT.files;
                    renderPreviews(newMainDT.files,'newMainImagesPreview','main');
                } else {
                    const vi = type.split('-')[1];
                    varDT[vi].items.remove(i);
                    const inp = document.querySelector('.variant-card[data-variant-index="'+vi+'"] input[type=file]');
                    inp.files = varDT[vi].files;
                    renderPreviews(varDT[vi].files, null, type, wrap);
                }
            };
            const lbl = document.createElement('div'); lbl.className='primary-lbl';
            lbl.textContent = i===0 ? '✓ رئيسية' : 'تعيين رئيسية';
            lbl.onclick = () => {
                wrap.querySelectorAll('.img-prev').forEach(p => {
                    p.classList.remove('is-primary');
                    p.querySelector('.primary-lbl').textContent='تعيين رئيسية';
                });
                div.classList.add('is-primary'); lbl.textContent='✓ رئيسية';
                const h = type==='main' ? document.getElementById('primaryMainImage')
                    : document.querySelector('.variant-card[data-variant-index="'+type.split('-')[1]+'"] .primary-variant-image');
                if (h) h.value = i;
            };
            div.appendChild(img); div.appendChild(rm); div.appendChild(lbl);
            wrap.appendChild(div);
        };
        reader.readAsDataURL(file);
    });
}

/* ── متغيرات ── */
document.getElementById('addVariantBtn').addEventListener('click', () => {
    const tpl  = document.getElementById('variantTemplate').content.cloneNode(true);
    const card = tpl.querySelector('.variant-card');
    const idx  = vc++;
    card.dataset.variantIndex = idx;
    card.querySelector('.v-num').textContent = idx + 1;
    card.querySelectorAll('[name]').forEach(el => el.name = el.name.replace('{vi}', idx));
    document.getElementById('variantsContainer').appendChild(card);
});

function removeVariant(btn) {
    if (!confirm('حذف هذا المتغير؟')) return;
    const idx = btn.closest('.variant-card').dataset.variantIndex;
    delete varDT[idx];
    btn.closest('.variant-card').remove();
}

function addAttrRow(btn) {
    const card = btn.closest('.variant-card');
    const idx  = card.dataset.variantIndex;
    const tpl  = document.getElementById('attrRowTemplate').content.cloneNode(true);
    const row  = tpl.querySelector('.attr-row');
    row.querySelector('.attr-value-select').name = 'variants['+idx+'][attributes][]';
    card.querySelector('.attr-rows').appendChild(row);
}

function updateAttrValues(sel) {
    const row    = sel.closest('.attr-row');
    const valSel = row.querySelector('.attr-value-select');
    const idx    = sel.closest('.variant-card').dataset.variantIndex;
    const attrId = sel.value;
    if (!attrId) { valSel.innerHTML='<option value="">اختر خاصية أولاً</option>'; valSel.disabled=true; valSel.name='variants['+idx+'][attributes][]'; return; }
    const attr = attrsData.find(a => a.id == attrId);
    if (!attr) return;
    const vals = attr.values_list ? attr.values_list.split(',').map(v=>v.trim()).filter(Boolean) : [];
    valSel.innerHTML = '<option value="">— اختر قيمة —</option>' + vals.map(v=>'<option value="'+v+'">'+v+'</option>').join('');
    valSel.disabled  = false;
    valSel.name      = 'variants['+idx+'][attributes]['+attrId+']';
}

window.addEventListener('DOMContentLoaded', () => { updateProfitMeter(); });
</script>
</body>
</html>