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

$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();

function convertToBytes($value) {
    $unit   = strtoupper(substr($value, -1));
    $number = (int)$value;
    switch ($unit) {
        case 'G': return $number * 1024 * 1024 * 1024;
        case 'M': return $number * 1024 * 1024;
        case 'K': return $number * 1024;
        default:  return $number;
    }
}

function processImageFile($file, $upload_dir, $product_id, $variant_id = null) {
    $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
    if (!in_array($file['type'], $allowed_types)) {
        $_SESSION['error_message'] = "نوع الملف غير مدعوم: " . $file['name'];
        return false;
    }
    if ($file['size'] > 2 * 1024 * 1024) {
        $_SESSION['error_message'] = "حجم الملف كبير جداً (أكثر من 2MB): " . $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));
    $file_name = uniqid('img_') . '.' . $ext;
    $target    = $upload_dir . $file_name;
    if (!move_uploaded_file($file['tmp_name'], $target)) {
        $_SESSION['error_message'] = "فشل رفع الملف: " . $file['name'];
        return false;
    }
    chmod($target, 0644);
    $base = 'Uploads/products/';
    if ($variant_id) return $base . $product_id . '/variants/' . $variant_id . '/' . $file_name;
    return $base . $product_id . '/' . $file_name;
}

function uploadImages($files, $product_id, $variant_id = null) {
    $uploaded   = [];
    $base_path  = dirname(__FILE__) . '/Uploads/products/';
    $upload_dir = $base_path . $product_id . ($variant_id ? '/variants/' . $variant_id : '') . '/';
    if (!file_exists($upload_dir)) {
        if (!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'];
    $tmp_names = (array)$files['tmp_name'];
    $errors    = (array)$files['error'];
    $sizes     = (array)$files['size'];
    foreach ($names as $i => $name) {
        if (empty($name) || $errors[$i] !== UPLOAD_ERR_OK) continue;
        $file   = ['name'=>$name,'type'=>$types[$i],'tmp_name'=>$tmp_names[$i],'error'=>$errors[$i],'size'=>$sizes[$i]];
        $result = processImageFile($file, $upload_dir, $product_id, $variant_id);
        if ($result) $uploaded[] = ['path' => $result];
    }
    return $uploaded;
}

// ===== AJAX: Gemini API Proxy =====
// نستخدم PHP كـ proxy لتفادي مشكلة CORS
if (isset($_GET['action']) && $_GET['action'] === 'gemini_proxy') {
    header('Content-Type: application/json');
    $input = json_decode(file_get_contents('php://input'), true);
    $apiKey = trim($input['api_key'] ?? '');
    $prompt = trim($input['prompt'] ?? '');
    $imageBase64 = $input['image_base64'] ?? null;
    $imageMime   = $input['image_mime']   ?? 'image/jpeg';

    if (empty($apiKey) || empty($prompt)) {
        echo json_encode(['error' => 'api_key and prompt are required']);
        exit;
    }

    $parts = [['text' => $prompt]];
    if ($imageBase64) {
        $parts[] = [
            'inline_data' => [
                'mime_type' => $imageMime,
                'data'      => $imageBase64
            ]
        ];
    }

    $payload = json_encode([
        'contents' => [['parts' => $parts]],
        'generationConfig' => [
            'temperature'     => 0.7,
            'maxOutputTokens' => 1024,
        ]
    ]);
    $ch = curl_init("https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={$apiKey}");
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => $payload,
        CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
        CURLOPT_TIMEOUT        => 30,
    ]);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($response === false) {
        echo json_encode(['error' => 'cURL failed']);
        exit;
    }

    $data = json_decode($response, true);
    if ($httpCode !== 200) {
        echo json_encode(['error' => $data['error']['message'] ?? 'Gemini API error']);
        exit;
    }

    $text = $data['candidates'][0]['content']['parts'][0]['text'] ?? '';
    // نحاول parse JSON إذا كان الرد JSON
    $cleaned = preg_replace('/```json|```/i', '', $text);
    $parsed  = json_decode(trim($cleaned), true);
    if ($parsed) {
        echo json_encode(['success' => true, 'data' => $parsed, 'raw' => $text]);
    } else {
        echo json_encode(['success' => true, 'data' => null, 'raw' => $text]);
    }
    exit;
}

$new_product_id = null;

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;

        if (empty($name))     throw new Exception("اسم المنتج مطلوب");
        if ($base_price <= 0) throw new Exception("سعر البيع يجب أن يكون أكبر من 0");
        if ($purch_price > $base_price) throw new Exception("⚠️ سعر الشراء أكبر من سعر البيع! ستبيع بخسارة.");
        if (empty($_FILES['main_images']['name'][0])) throw new Exception("يجب اختيار صورة رئيسية واحدة على الأقل");

        $stmt = $pdo->prepare("INSERT INTO products (category_id, name, description, price, purchase_price, discounted_price, is_active) VALUES (:cat, :name, :desc, :price, :pprice, :dprice, :active)");
        $stmt->execute([':cat'=>$category_id,':name'=>$name,':desc'=>$description,':price'=>$base_price,':pprice'=>$purch_price,':dprice'=>$disc_price,':active'=>$is_active]);
        $product_id = $pdo->lastInsertId();

        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, intval($dc_id)]);
        }

        $main_images = uploadImages($_FILES['main_images'], $product_id);
        if (empty($main_images)) throw new Exception("فشل رفع صور المنتج الرئيسية.");

        $primary_idx = intval($_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['variants'])) {
            foreach ($_POST['variants'] as $idx => $variant) {
                $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 = intval($variant['stock'] ?? 0);
                $v_def   = isset($variant['is_default']) ? 1 : 0;
                $stmtV   = $pdo->prepare("INSERT INTO product_variants (product_id, sku, price, purchase_price, stock, is_default) VALUES (:pid,:sku,:price,:pprice,:stock,:def)");
                $stmtV->execute([':pid'=>$product_id,':sku'=>$v_sku,':price'=>$v_price,':pprice'=>$v_purch,':stock'=>$v_stock,':def'=>$v_def]);
                $variant_id = $pdo->lastInsertId();
                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([$variant_id, $attr_id, $attr_val]);
                    }
                }
                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, $variant_id);
                    if (!empty($v_images)) {
                        $v_primary_idx = intval($_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([$variant_id, $vimg['path'], $vi === $v_primary_idx ? 1 : 0]);
                    }
                }
            }
        }

        $pdo->commit();

        if (!empty($_POST['goto_landing']) && $_POST['goto_landing'] == '1') {
            $_SESSION['message'] = "✅ تمت إضافة المنتج «{$name}» بنجاح";
            header("Location: edit_product.php?id={$product_id}&open_landing=1"); exit;
        }

        $_SESSION['message'] = "✅ تمت إضافة المنتج «{$name}» بنجاح";
        header("Location: index.php"); exit;

    } catch (Exception $e) {
        $pdo->rollBack();
        $_SESSION['error_message'] = $e->getMessage();
        header("Location: add_product.php"); exit;
    }
}
?>
<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>إضافة منتج جديد</title>
<link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;700;800;900&display=swap" rel="stylesheet">
<?php include __DIR__ . '/pwa_head.php'; ?>
<style>
:root {
    --primary:    #1E40AF;
    --primary-l:  #3B82F6;
    --primary-d:  #1E3A8A;
    --success:    #059669;
    --success-l:  #D1FAE5;
    --danger:     #DC2626;
    --danger-l:   #FEE2E2;
    --warning:    #D97706;
    --warning-l:  #FEF3C7;
    --info:       #0284C7;
    --info-l:     #E0F2FE;
    --purple:     #7C3AED;
    --purple-l:   #EDE9FE;
    --gemini:     #1a73e8;
    --gemini-l:   #e8f0fe;
    --gemini-g1:  #4285f4;
    --gemini-g2:  #ea4335;
    --gemini-g3:  #fbbc04;
    --gemini-g4:  #34a853;
    --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(--primary);font-size:20px;font-weight:900;display:flex;align-items:center;gap:10px}
.icon-wrap{background:linear-gradient(135deg,var(--primary),var(--primary-l));color:white;width:38px;height:38px;border-radius:10px;display:flex;align-items:center;justify-content:center}

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

.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}
@keyframes fadeUp{from{opacity:0;transform:translateY(12px)}to{opacity:1;transform:translateY(0)}}
.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)}
.form-group label .req{color:var(--danger);margin-right:2px}
.form-group label .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}
@media(max-width:768px){.form-row{grid-template-columns:1fr}}
.form-row-2{display:grid;grid-template-columns:1fr 1fr;gap:16px}
@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:24px}
.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:5px}
.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:36px;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 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:12px;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;transition:var(--tr)}
.img-prev:not(.is-primary) .primary-lbl{background:rgba(0,0,0,0.4)}

/* ===== Gemini AI Section ===== */
.gemini-card{
    border:1.5px solid #c2d7ff;
    background:linear-gradient(135deg,#f0f4ff 0%,#fafbff 100%);
}
.gemini-card .card-title{border-bottom-color:#d4e3ff}
.gemini-icon-wrap{
    background:linear-gradient(135deg,#4285f4,#1a73e8);
    color:white;width:32px;height:32px;border-radius:var(--radius-sm);
    display:flex;align-items:center;justify-content:center;flex-shrink:0;
}
.gemini-api-row{
    display:flex;gap:10px;align-items:flex-end;margin-bottom:20px;
}
.gemini-api-row .form-group{flex:1;margin-bottom:0}
.gemini-badge{
    display:inline-flex;align-items:center;gap:5px;
    background:white;border:1.5px solid #c2d7ff;
    border-radius:20px;padding:4px 12px;
    font-size:11px;font-weight:700;color:#1a73e8;
    margin-right:8px;
}
.gemini-status{
    display:inline-flex;align-items:center;gap:6px;
    font-size:12px;font-weight:700;padding:6px 12px;
    border-radius:20px;margin-top:8px;
    transition:var(--tr);
}
.gemini-status.idle   {background:#f0f4ff;color:#1a73e8;border:1px solid #c2d7ff}
.gemini-status.loading{background:#fff8e1;color:#f59e0b;border:1px solid #fde68a}
.gemini-status.success{background:var(--success-l);color:var(--success);border:1px solid #A7F3D0}
.gemini-status.error  {background:var(--danger-l);color:var(--danger);border:1px solid #FECACA}

/* زر Gemini */
.btn-gemini{
    background:linear-gradient(135deg,#4285f4,#1a73e8);
    color:white;border:none;padding:9px 16px;border-radius:var(--radius-sm);
    font-weight:700;font-size:13px;cursor:pointer;
    display:inline-flex;align-items:center;gap:7px;
    transition:var(--tr);font-family:'Tajawal',sans-serif;
    white-space:nowrap;
}
.btn-gemini:hover{background:linear-gradient(135deg,#1a73e8,#1557b0);transform:translateY(-1px);box-shadow:0 4px 14px rgba(66,133,244,0.35)}
.btn-gemini:disabled{opacity:0.6;cursor:not-allowed;transform:none}
.btn-gemini .spinner{width:14px;height:14px;border:2px solid rgba(255,255,255,0.3);border-top-color:white;border-radius:50%;animation:spin 0.7s linear infinite}
@keyframes spin{to{transform:rotate(360deg)}}

/* قسم توليد الاسم والوصف */
.ai-generate-section{
    background:white;border:1.5px solid #d4e3ff;border-radius:var(--radius-sm);
    padding:16px;margin-bottom:16px;
}
.ai-generate-section h4{
    font-size:13px;font-weight:800;color:#1a73e8;
    margin-bottom:12px;display:flex;align-items:center;gap:7px;
}
.ai-suggestion-box{
    background:#f8fbff;border:1.5px solid #c2d7ff;border-radius:var(--radius-sm);
    padding:14px;margin-top:12px;display:none;
    animation:slideIn 0.3s ease;
}
.ai-suggestion-box.show{display:block}
.ai-suggestion-box .sug-label{font-size:11px;font-weight:800;color:#1a73e8;margin-bottom:4px}
.ai-suggestion-box .sug-value{font-size:14px;color:var(--text);margin-bottom:10px;line-height:1.6}
.ai-apply-btn{
    font-size:12px;font-weight:700;color:var(--success);
    cursor:pointer;display:inline-flex;align-items:center;gap:4px;
    border:1px solid #A7F3D0;border-radius:6px;padding:4px 10px;
    background:var(--success-l);transition:var(--tr);margin-left:8px;
}
.ai-apply-btn:hover{background:#A7F3D0}

/* قسم المتغيرات الذكية */
.smart-variant-section{
    background:white;border:1.5px solid #d4e3ff;border-radius:var(--radius-sm);
    padding:16px;margin-bottom:0;
}
.smart-variant-section h4{
    font-size:13px;font-weight:800;color:#1a73e8;
    margin-bottom:4px;display:flex;align-items:center;gap:7px;
}
.smart-variant-section p{font-size:12px;color:var(--text-3);margin-bottom:12px}

.smart-variant-upload{
    border:2px dashed #c2d7ff;border-radius:var(--radius-sm);
    padding:20px;text-align:center;cursor:pointer;
    transition:var(--tr);background:#f8fbff;
}
.smart-variant-upload:hover{border-color:#4285f4;background:#f0f4ff}
.smart-variant-upload .svu-icon{font-size:28px;margin-bottom:6px}
.smart-variant-upload .svu-text{font-size:13px;font-weight:600;color:#1a73e8}
.smart-variant-upload .svu-hint{font-size:11px;color:var(--text-3);margin-top:3px}

/* بطاقة متغير ذكي */
.smart-variant-item{
    display:flex;align-items:center;gap:12px;
    background:#f8fbff;border:1.5px solid #c2d7ff;
    border-radius:var(--radius-sm);padding:12px;
    margin-top:10px;animation:slideIn 0.3s ease;
    position:relative;
}
.smart-variant-item .svi-img{
    width:60px;height:60px;border-radius:6px;
    object-fit:cover;border:2px solid #d4e3ff;flex-shrink:0;
}
.smart-variant-item .svi-info{flex:1}
.smart-variant-item .svi-analyzing{
    font-size:12px;color:#f59e0b;font-weight:700;
    display:flex;align-items:center;gap:6px;
}
.smart-variant-item .svi-result{display:none}
.smart-variant-item .svi-result.show{display:block}
.svi-attr-badge{
    display:inline-flex;align-items:center;gap:5px;
    background:white;border:1.5px solid #c2d7ff;
    border-radius:20px;padding:4px 10px;
    font-size:12px;font-weight:700;color:#1a73e8;
    margin:3px;
}
.svi-add-btn{
    background:linear-gradient(135deg,#34a853,#2d9249);
    color:white;border:none;padding:7px 14px;
    border-radius:var(--radius-sm);font-weight:700;
    font-size:12px;cursor:pointer;
    display:inline-flex;align-items:center;gap:5px;
    transition:var(--tr);font-family:'Tajawal',sans-serif;
    margin-top:8px;
}
.svi-add-btn:hover{transform:translateY(-1px);box-shadow:0 3px 10px rgba(52,168,83,0.3)}
.svi-remove{
    position:absolute;top:8px;left:8px;
    width:22px;height:22px;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:11px;font-weight:900;
    transition:var(--tr);
}
.svi-remove:hover{background:var(--danger);color:white}

/* متغيرات عادية */
.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:8px}
.btn-remove-variant{width:30px;height:30px;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:14px;transition:var(--tr)}
.btn-remove-variant:hover{background:var(--danger);color:white}

.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:14px;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-primary      {background:var(--primary);color:white}
.btn-primary:hover{background:var(--primary-d);transform:translateY(-1px);box-shadow:0 4px 14px rgba(30,64,175,0.3)}
.btn-success      {background:var(--success);color:white}
.btn-success:hover{background:#047857;transform:translateY(-1px)}
.btn-info         {background:var(--info);color:white}
.btn-info:hover   {background:#0369A1;transform:translateY(-1px)}
.btn-purple       {background:var(--purple);color:white}
.btn-purple:hover {background:#6D28D9;transform:translateY(-1px);box-shadow:0 4px 14px rgba(124,58,237,0.3)}
.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);flex-wrap:wrap}

/* بطاقة صفحة الهبوط */
.ai-card{border:1.5px solid #C4B5FD;background:linear-gradient(135deg,#FAF5FF,#F5F3FF)}
.ai-card .card-title{border-bottom-color:#DDD6FE}
.ai-note{background:#EDE9FE;border:1px solid #C4B5FD;border-radius:var(--radius-sm);padding:10px 14px;font-size:12px;color:#5B21B6;font-weight:600;margin-bottom:16px;display:flex;align-items:center;gap:8px}

@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}
    .gemini-api-row{flex-direction:column}
}

/* ===== Pulse animation for analyzing ===== */
@keyframes pulse{0%,100%{opacity:1}50%{opacity:0.5}}
.pulse{animation:pulse 1.2s ease infinite}

/* ===== Shimmer for loading ===== */
@keyframes shimmer{
    0%{background-position:-200% 0}
    100%{background-position:200% 0}
}
.shimmer{
    background:linear-gradient(90deg,#f0f4ff 25%,#dbeafe 50%,#f0f4ff 75%);
    background-size:200% 100%;
    animation:shimmer 1.5s infinite;
    border-radius:4px;height:14px;
}
</style>
<?php include __DIR__ . '/darkmode.php'; ?>
</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" title="القائمة">
    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round">
        <line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/>
    </svg>
</button>
<div class="sidebar-overlay" onclick="toggleSidebar()"></div>
<?php include 'sidebar.php'; ?>

<div class="container">

    <!-- HEADER -->
    <div class="header">
        <h1>
            <span class="icon-wrap">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
            </span>
            إضافة منتج جديد
        </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; ?>
    <?php if (isset($_SESSION['success_message'])): ?>
        <div class="msg msg-success">✅ <?= htmlspecialchars($_SESSION['success_message']) ?></div>
        <?php unset($_SESSION['success_message']); ?>
    <?php endif; ?>

    <!-- ===== بطاقة Gemini API Key (في الأعلى ودائمة الظهور) ===== -->
    <div class="card gemini-card" style="animation-delay:0s">
        <div class="card-title">
            <span class="gemini-icon-wrap">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2">
                    <path d="M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20z"/>
                    <path d="M12 6v6l4 2"/>
                </svg>
            </span>
            <span>مساعد Gemini AI</span>
            <span class="gemini-badge">✨ مدعوم بالذكاء الاصطناعي</span>
        </div>

        <div class="gemini-api-row">
            <div class="form-group">
                <label>مفتاح Gemini API <span class="opt">(مطلوب لتفعيل المساعد)</span></label>
                <input type="text" id="geminiApiKey" placeholder="AIza..." style="font-family:monospace;font-size:13px" oninput="checkApiKey()">
            </div>
            <button type="button" class="btn-gemini" id="testApiBtn" onclick="testApiKey()" disabled>
                <svg width="14" height="14" 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>
                اختبار المفتاح
            </button>
        </div>
        <div id="geminiKeyStatus" class="gemini-status idle">🔑 أدخل مفتاح API لتفعيل مساعد الذكاء الاصطناعي</div>
    </div>

    <form method="POST" enctype="multipart/form-data" id="productForm">
        <input type="hidden" name="goto_landing" id="gotoLanding" value="0">

        <!-- ===== المعلومات الأساسية ===== -->
        <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>
                    <div style="display:flex;gap:8px">
                        <input type="text" name="name" id="productName" required placeholder="مثال: هاتف سامسونج A55" style="flex:1">
                        <button type="button" class="btn-gemini" id="btnGenerateName" onclick="generateNameDesc()" disabled title="توليد اسم ذكي">
                            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>
                            AI
                        </button>
                    </div>
                </div>
                <div class="form-group">
                    <label>الفئة <span class="opt">(اختياري)</span></label>
                    <select name="category_id" id="productCategory">
                        <option value="">— اختر الفئة —</option>
                        <?php foreach ($categories as $cat): ?>
                            <option value="<?= $cat['id'] ?>"><?= htmlspecialchars($cat['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <div class="form-group">
                <label>وصف المنتج <span class="opt">(اختياري)</span></label>
                <div style="position:relative">
                    <textarea name="description" id="productDesc" placeholder="وصف تفصيلي للمنتج..."></textarea>
                    <button type="button" class="btn-gemini btn-sm" id="btnGenerateDesc"
                        onclick="generateDesc()" disabled
                        style="position:absolute;bottom:10px;left:10px;font-size:11px;padding:6px 10px">
                        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>
                        توليد وصف بـ AI
                    </button>
                </div>
            </div>

            <!-- صندوق اقتراحات AI -->
            <div class="ai-suggestion-box" id="aiSuggestionBox">
                <div class="sug-label">💡 اقتراح الاسم:</div>
                <div class="sug-value" id="sugName">—</div>
                <span class="ai-apply-btn" onclick="applyName()">✓ تطبيق الاسم</span>
                <hr style="border:none;border-top:1px solid #d4e3ff;margin:10px 0">
                <div class="sug-label">📝 اقتراح الوصف:</div>
                <div class="sug-value" id="sugDesc">—</div>
                <span class="ai-apply-btn" onclick="applyDesc()">✓ تطبيق الوصف</span>
            </div>

            <div id="nameDescStatus" class="gemini-status idle" style="display:none">جاري التوليد...</div>

            <div class="form-group" style="margin-top:10px">
                <label class="toggle-wrap" for="is_active">
                    <input type="checkbox" id="is_active" name="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="0" oninput="updateProfitMeter()">
                    </div>
                    <small style="font-size:11px;color:var(--text-3);margin-top:4px;display:block">المبلغ الذي اشتريت به من المورد</small>
                </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 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" 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>

        <!-- ===== شركات التوصيل ===== -->
        <div class="card" style="animation-delay:0.15s">
            <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">
                    <label for="dc_<?= $dc['id'] ?>"><?= htmlspecialchars($dc['name']) ?></label>
                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- ===== الصور الرئيسية ===== -->
        <div class="card" style="animation-delay:0.2s">
            <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>
                صور المنتج الرئيسية
                <span style="color:var(--danger);font-size:12px;font-weight:700">* مطلوبة</span>
            </div>
            <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)" required>
            </div>
            <input type="hidden" name="primary_main_image" id="primaryMainImage" value="0">
            <div class="img-preview-wrap" id="mainImagesPreview"></div>
        </div>

        <!-- ===== المتغيرات ===== -->
        <div class="card" style="animation-delay:0.25s">
            <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>

            <!-- ===== قسم المتغيرات الذكية بـ Gemini ===== -->
            <div class="smart-variant-section" style="margin-bottom:16px">
                <h4>
                    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#1a73e8" stroke-width="2.5"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>
                    كشف المتغيرات تلقائياً بـ Gemini AI
                </h4>
                <p>ارفع صورة لكل متغير (لون، مقاس...) وسيكتشف Gemini الخصائص تلقائياً ويضيف المتغير فوراً</p>

                <div class="smart-variant-upload" onclick="document.getElementById('smartVariantInput').click()">
                    <div class="svu-icon">🤖</div>
                    <div class="svu-text">رفع صورة متغير للتحليل بـ AI</div>
                    <div class="svu-hint">كل صورة ترفعها = متغير جديد يُحلَّل تلقائياً</div>
                    <input type="file" id="smartVariantInput" accept="image/*" multiple style="display:none" onchange="handleSmartVariantImages(this)">
                </div>

                <div id="smartVariantsList"></div>
            </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"></div>
        </div>

        <!-- ===== بطاقة صفحة الهبوط بالذكاء الاصطناعي ===== -->
        <div class="card ai-card" style="animation-delay:0.3s">
            <div class="card-title">
                <span class="ct-icon" style="background:linear-gradient(135deg,#7C3AED,#A78BFA)">
                    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2">
                        <polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/>
                    </svg>
                </span>
                صفحة الهبوط بالذكاء الاصطناعي
                <span style="color:var(--purple);font-size:11px;font-weight:600">✨ مميزة</span>
            </div>
            <div class="ai-note">
                💡 بعد حفظ المنتج ستنتقل تلقائياً لصفحة التعديل حيث يمكنك إنشاء صفحة الهبوط بـ Gemini AI
            </div>
            <div style="display:flex;gap:10px;flex-wrap:wrap">
                <label class="toggle-wrap" style="flex:1;min-width:200px">
                    <input type="checkbox" id="createLandingAfterSave" onchange="toggleLandingMode(this)">
                    <span>إنشاء صفحة هبوط تلقائياً بعد الحفظ</span>
                </label>
            </div>
        </div>

        <!-- ===== أزرار الحفظ ===== -->
        <div class="form-actions">
            <a href="index.php" class="btn btn-gray">
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                إلغاء
            </a>
            <button type="submit" class="btn btn-success" id="btnSave">
                <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>
            <button type="submit" class="btn btn-purple" id="btnSaveAndLanding" style="display:none" onclick="document.getElementById('gotoLanding').value='1'">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></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="15" height="15" 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)" title="حذف المتغير">✕</button>
        </div>
        <div class="form-row">
            <div class="form-group">
                <label>كود SKU <span style="color:var(--text-3);font-size:11px;font-weight:400">(تلقائي إن تُرك)</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>الكمية المتاحة</label>
                <input type="number" name="variants[{vi}][stock]" min="0" value="0">
            </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 style="color:var(--text-3);font-size:11px;font-weight:400">(اختياري)</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[{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 style="color:var(--text-3);font-weight:400">(اختياري)</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()" title="حذف">✕</button>
    </div>
</template>

<script>
let vc = 0;
const attrsData = <?= json_encode($attributes) ?>;
const mainDT = new DataTransfer();
const varDT  = {};

// ============================================================
// Gemini API Key Management
// ============================================================
function getApiKey() {
    return document.getElementById('geminiApiKey').value.trim();
}

function checkApiKey() {
    const key = getApiKey();
    const hasKey = key.length > 10;
    document.getElementById('testApiBtn').disabled = !hasKey;
    document.getElementById('btnGenerateName').disabled = !hasKey;
    document.getElementById('btnGenerateDesc').disabled = !hasKey;
}

async function testApiKey() {
    const key = getApiKey();
    if (!key) return;
    setKeyStatus('loading', '⏳ جاري التحقق من المفتاح...');
    document.getElementById('testApiBtn').disabled = true;

    try {
        const result = await callGemini('قل كلمة "مرحباً" فقط', null, null);
        if (result.success) {
            setKeyStatus('success', '✅ المفتاح صالح — الذكاء الاصطناعي جاهز!');
        } else {
            setKeyStatus('error', '❌ ' + (result.error || 'مفتاح غير صالح'));
        }
    } catch(e) {
        setKeyStatus('error', '❌ خطأ في الاتصال');
    }
    document.getElementById('testApiBtn').disabled = false;
}

function setKeyStatus(type, msg) {
    const el = document.getElementById('geminiKeyStatus');
    el.className = 'gemini-status ' + type;
    el.textContent = msg;
}

// ============================================================
// Core Gemini Caller (via PHP proxy)
// ============================================================
async function callGemini(prompt, imageBase64, imageMime) {
    const key = getApiKey();
    if (!key) throw new Error('لا يوجد API Key');

    const parts = [{ text: prompt }];
    if (imageBase64) {
        parts.push({ inline_data: { mime_type: imageMime, data: imageBase64 } });
    }

    const resp = await fetch(
        `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${key}`,
        {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                contents: [{ parts }],
                generationConfig: { temperature: 0.7, maxOutputTokens: 1024 }
            })
        }
    );

    const data = await resp.json();
    if (!resp.ok) return { error: data.error?.message || 'Gemini error' };

    const text = data.candidates?.[0]?.content?.parts?.[0]?.text || '';
    const cleaned = text.replace(/```json|```/gi, '').trim();
    try {
        return { success: true, data: JSON.parse(cleaned), raw: text };
    } catch {
        return { success: true, data: null, raw: text };
    }
}
// Helper: convert File to base64
function fileToBase64(file) {
    return new Promise((res, rej) => {
        const r = new FileReader();
        r.onload = () => res(r.result.split(',')[1]);
        r.onerror = rej;
        r.readAsDataURL(file);
    });
}

// ============================================================
// توليد الاسم والوصف
// ============================================================
async function generateNameDesc() {
    const currentName = document.getElementById('productName').value.trim();
    const category    = document.getElementById('productCategory').options[document.getElementById('productCategory').selectedIndex]?.text || '';

    if (!currentName) {
        alert('أدخل اسماً أولياً للمنتج لمساعدة Gemini على الاقتراح');
        return;
    }

    setNameDescStatus('loading', '⏳ Gemini يفكر في أفضل اسم ووصف...');
    document.getElementById('btnGenerateName').disabled = true;

    const prompt = `أنت مساعد تسويقي لمتجر إلكتروني جزائري.
المنتج: "${currentName}"
الفئة: "${category || 'غير محددة'}"

أعطني JSON فقط بدون أي نص إضافي، بالشكل التالي:
{
  "name": "اسم تسويقي جذاب للمنتج باللغة العربية (لا يزيد عن 60 حرف)",
  "description": "وصف تسويقي مقنع للمنتج باللغة العربية (3-5 جمل، يذكر المميزات والفوائد)"
}`;

    try {
        const result = await callGemini(prompt, null, null);
        if (result.success && result.data) {
            document.getElementById('sugName').textContent = result.data.name || '—';
            document.getElementById('sugDesc').textContent = result.data.description || '—';
            document.getElementById('aiSuggestionBox').classList.add('show');
            setNameDescStatus('success', '✅ تم التوليد — راجع الاقتراحات أدناه');
        } else {
            setNameDescStatus('error', '❌ ' + (result.error || 'فشل التوليد'));
        }
    } catch(e) {
        setNameDescStatus('error', '❌ خطأ في الاتصال بـ Gemini');
    }
    document.getElementById('btnGenerateName').disabled = false;
}

async function generateDesc() {
    const name = document.getElementById('productName').value.trim();
    if (!name) { alert('أدخل اسم المنتج أولاً'); return; }

    setNameDescStatus('loading', '⏳ Gemini يكتب الوصف...');
    document.getElementById('btnGenerateDesc').disabled = true;

    const prompt = `اكتب وصفاً تسويقياً احترافياً باللغة العربية للمنتج: "${name}"
أعطني JSON فقط:
{
  "name": "${name}",
  "description": "وصف تسويقي مقنع (4-6 جمل، يذكر المميزات والفوائد والجودة)"
}`;

    try {
        const result = await callGemini(prompt, null, null);
        if (result.success && result.data) {
            document.getElementById('sugDesc').textContent = result.data.description || '—';
            document.getElementById('sugName').textContent = result.data.name || name;
            document.getElementById('aiSuggestionBox').classList.add('show');
            setNameDescStatus('success', '✅ تم كتابة الوصف');
        } else {
            setNameDescStatus('error', '❌ ' + (result.error || 'فشل'));
        }
    } catch(e) {
        setNameDescStatus('error', '❌ خطأ');
    }
    document.getElementById('btnGenerateDesc').disabled = false;
}

function setNameDescStatus(type, msg) {
    const el = document.getElementById('nameDescStatus');
    el.style.display = 'inline-flex';
    el.className = 'gemini-status ' + type;
    el.textContent = msg;
}

function applyName() {
    const v = document.getElementById('sugName').textContent;
    if (v && v !== '—') document.getElementById('productName').value = v;
}
function applyDesc() {
    const v = document.getElementById('sugDesc').textContent;
    if (v && v !== '—') document.getElementById('productDesc').value = v;
}

// ============================================================
// كشف المتغيرات الذكية من الصور
// ============================================================
async function handleSmartVariantImages(input) {
    const files = Array.from(input.files);
    if (!files.length) return;

    const key = getApiKey();
    if (!key) {
        alert('يرجى إدخال مفتاح Gemini API أولاً لتفعيل الكشف الذكي');
        input.value = '';
        return;
    }

    for (const file of files) {
        if (file.size > 2 * 1024 * 1024) {
            alert('حجم الصورة كبير جداً: ' + file.name);
            continue;
        }
        await addSmartVariantItem(file);
    }
    input.value = ''; // reset لأنه ممكن يرفع نفس الصورة مرة ثانية
}

async function addSmartVariantItem(file) {
    const list = document.getElementById('smartVariantsList');
    const imgUrl = URL.createObjectURL(file);
    const itemId = 'svi_' + Date.now() + '_' + Math.random().toString(36).substr(2,5);

    // إنشاء بطاقة المتغير الذكي
    const item = document.createElement('div');
    item.className = 'smart-variant-item';
    item.id = itemId;
    item.innerHTML = `
        <img src="${imgUrl}" class="svi-img" alt="صورة المتغير">
        <div class="svi-info">
            <div class="svi-analyzing pulse">
                <div class="spinner" style="width:12px;height:12px;border:2px solid rgba(245,158,11,0.3);border-top-color:#f59e0b;border-radius:50%;animation:spin 0.7s linear infinite;display:inline-block"></div>
                Gemini يحلل الصورة...
            </div>
            <div class="svi-result" id="${itemId}_result"></div>
        </div>
        <div class="svi-remove" onclick="removeSmartVariant('${itemId}')">✕</div>
    `;
    list.appendChild(item);

    try {
        const base64 = await fileToBase64(file);
        const mime   = file.type;

        const prompt = `أنت محلل منتجات لمتجر جزائري. انظر لهذه الصورة واستنتج خصائص المنتج.
أعطني JSON فقط بدون أي نص إضافي:
{
  "attributes": [
    {"name": "اسم الخاصية بالعربية مثل اللون أو المقاس", "value": "قيمة الخاصية بالعربية"}
  ],
  "description": "وصف مختصر لما تراه في الصورة (جملة واحدة)"
}
مثال: إذا كانت الصورة لقميص أزرق: {"attributes":[{"name":"اللون","value":"أزرق"}],"description":"قميص بلون أزرق سماوي"}
أعط 1-3 خصائص فقط الأكثر وضوحاً.`;

        const result = await callGemini(prompt, base64, mime);

        const analyzing = item.querySelector('.svi-analyzing');
        const resultDiv = item.querySelector('.svi-result');

        if (result.success && result.data && result.data.attributes) {
            analyzing.style.display = 'none';
            resultDiv.classList.add('show');

            const attrs = result.data.attributes;
            const desc  = result.data.description || '';

            let html = `<div style="font-size:11px;color:var(--text-3);margin-bottom:5px">${desc}</div>`;
            html += '<div>';
            attrs.forEach(a => {
                html += `<span class="svi-attr-badge">📌 ${a.name}: <strong>${a.value}</strong></span>`;
            });
            html += '</div>';
            html += `<button type="button" class="svi-add-btn" onclick="addSmartVariantToForm('${itemId}', ${JSON.stringify(attrs).replace(/'/g,"&#39;")}, '${imgUrl}', '${file.name}')">
                ➕ إضافة كمتغير للمنتج
            </button>`;

            resultDiv.innerHTML = html;

            // حفظ الملف في data attribute
            item.dataset.file = itemId;
            item._file = file; // حفظ مباشر على العنصر
        } else {
            analyzing.innerHTML = '❌ تعذر التحليل — ' + (result.error || 'حاول مرة أخرى');
            analyzing.classList.remove('pulse');
            analyzing.style.color = 'var(--danger)';
        }
    } catch(e) {
        const analyzing = item.querySelector('.svi-analyzing');
        analyzing.innerHTML = '❌ خطأ في الاتصال';
        analyzing.classList.remove('pulse');
        analyzing.style.color = 'var(--danger)';
    }
}

function removeSmartVariant(itemId) {
    const el = document.getElementById(itemId);
    if (el) el.remove();
}

function addSmartVariantToForm(itemId, attrs, imgUrl, fileName) {
    // إضافة متغير عادي
    const addBtn = document.getElementById('addVariantBtn');
    addBtn.click();

    // الانتظار قليلاً ثم ملء الخصائص
    setTimeout(() => {
        const cards = document.querySelectorAll('.variant-card');
        const lastCard = cards[cards.length - 1];
        if (!lastCard) return;

        const idx = lastCard.dataset.variantIndex;

        // إضافة صف خاصية لكل attribute
        attrs.forEach(attr => {
            const addAttrBtn = lastCard.querySelector('.btn.btn-gray.btn-sm');
            addAttrBtn.click();

            setTimeout(() => {
                const rows = lastCard.querySelectorAll('.attr-row');
                const lastRow = rows[rows.length - 1];
                if (!lastRow) return;

                const attrSel = lastRow.querySelector('.attr-select');
                const valSel  = lastRow.querySelector('.attr-value-select');

                // ابحث عن الخاصية في القائمة
                const matchAttr = attrsData.find(a =>
                    a.name === attr.name ||
                    a.name.includes(attr.name) ||
                    attr.name.includes(a.name)
                );

                if (matchAttr) {
                    attrSel.value = matchAttr.id;
                    updateAttrValues(attrSel);
                    setTimeout(() => {
                        // حاول إيجاد القيمة في القائمة
                        const opts = Array.from(valSel.options);
                        const matchOpt = opts.find(o =>
                            o.value === attr.value ||
                            o.value.includes(attr.value) ||
                            attr.value.includes(o.value)
                        );
                        if (matchOpt) {
                            valSel.value = matchOpt.value;
                        } else {
                            // إضافة كخيار جديد إذا لم يوجد
                            const newOpt = document.createElement('option');
                            newOpt.value = attr.value;
                            newOpt.textContent = attr.value;
                            newOpt.selected = true;
                            valSel.appendChild(newOpt);
                            valSel.disabled = false;
                            valSel.name = `variants[${idx}][attributes][${matchAttr.id}]`;
                        }
                    }, 100);
                } else {
                    // إذا لم نجد الخاصية، نضع القيمة كنص في الـ select
                    const freeOpt = document.createElement('option');
                    freeOpt.value = attr.value;
                    freeOpt.textContent = attr.name + ': ' + attr.value;
                    freeOpt.selected = true;
                    valSel.appendChild(freeOpt);
                    valSel.disabled = false;
                }
            }, 50);
        });

        // إضافة الصورة للمتغير
        const smartItem = document.getElementById(itemId);
        if (smartItem && smartItem._file) {
            const fileInput = lastCard.querySelector('input[type=file]');
            if (fileInput) {
                const dt = new DataTransfer();
                dt.items.add(smartItem._file);
                fileInput.files = dt.files;
                handleVariantImages(fileInput);
                if (!varDT[idx]) varDT[idx] = new DataTransfer();
                varDT[idx].items.add(smartItem._file);
            }
        }

        // إزالة البطاقة الذكية بعد الإضافة
        if (smartItem) {
            smartItem.style.opacity = '0.5';
            smartItem.querySelector('.svi-add-btn').textContent = '✅ تمت الإضافة';
            smartItem.querySelector('.svi-add-btn').disabled = true;
        }

        // scroll للمتغير الجديد
        lastCard.scrollIntoView({ behavior: 'smooth', block: 'center' });

    }, 100);
}

// ============================================================
// Original Functions (unchanged)
// ============================================================
function toggleLandingMode(cb) {
    const btnLanding = document.getElementById('btnSaveAndLanding');
    const btnSave    = document.getElementById('btnSave');
    if (cb.checked) {
        btnLanding.style.display = 'inline-flex';
        btnSave.style.display    = 'none';
    } else {
        btnLanding.style.display = 'none';
        btnSave.style.display    = 'inline-flex';
    }
}

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 = 'أدخل الأسعار أعلاه';
        meter.querySelector('.pm-icon').textContent = '💰';
        return;
    }
    const profit = sell - buy;
    const pct    = sell > 0 ? ((profit / sell) * 100).toFixed(1) : 0;
    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 toggleAllDC() {
    const cbs = document.querySelectorAll('.dc-checkbox');
    const anyUnchecked = Array.from(cbs).some(c => !c.checked);
    cbs.forEach(c => c.checked = anyUnchecked);
}

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 card   = sel.closest('.variant-card');
    const idx    = 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}]`;
}

function handleMainImages(input) {
    mainDT.items.clear();
    Array.from(input.files).forEach(f => {
        if (f.size > 2*1024*1024) { alert('حجم الصورة كبير جداً: ' + f.name); return; }
        if (!f.type.startsWith('image/')) { alert('ملف غير مدعوم: ' + f.name); return; }
        mainDT.items.add(f);
    });
    input.files = mainDT.files;
    renderPreviews(mainDT.files, 'mainImagesPreview', '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; }
        if (!f.type.startsWith('image/')) { 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' : '');
            div.dataset.index = i;
            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') {
                    mainDT.items.remove(i);
                    document.getElementById('mainImages').files = mainDT.files;
                    renderPreviews(mainDT.files, 'mainImagesPreview', '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 hiddenInput = type === 'main'
                    ? document.getElementById('primaryMainImage')
                    : document.querySelector(`.variant-card[data-variant-index="${type.split('-')[1]}"] .primary-variant-image`);
                if (hiddenInput) hiddenInput.value = i;
            };
            div.appendChild(img);
            div.appendChild(rm);
            div.appendChild(lbl);
            wrap.appendChild(div);
        };
        reader.readAsDataURL(file);
    });
}

document.getElementById('productForm').addEventListener('submit', function(e) {
    if (mainDT.files.length === 0) {
        e.preventDefault();
        alert('⚠️ يجب رفع صورة رئيسية واحدة على الأقل!');
        return;
    }
    const buy  = parseFloat(document.getElementById('purchasePrice').value) || 0;
    const sell = parseFloat(document.getElementById('basePrice').value)     || 0;
    if (buy > sell) {
        if (!confirm('⚠️ سعر الشراء أكبر من سعر البيع — ستبيع بخسارة!\nهل تريد المتابعة؟')) {
            e.preventDefault();
        }
    }
});
</script>
</body>
</html>