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

// إعدادات المتجر
$store_settings = $pdo->query("SELECT * FROM stores WHERE id=1")->fetch();

// صفحة الهبوط
$lp_stmt = $pdo->prepare("SELECT id, updated_at FROM landing_pages WHERE product_id = ? LIMIT 1");
$lp_stmt->execute([$product_id]);
$landing_page = $lp_stmt->fetch();

// الصورة الرئيسية
$main_image = !empty($product_images) ? $product_images[0] : null;

// كل صور المنتج
$all_product_images_urls = [];
foreach ($product_images as $img) {
    $all_product_images_urls[] = BASE_URL . 'admin/' . $img['image_url'];
}

// المتغيرات للـ prompt
$variants_for_prompt = [];
foreach ($variants as $v) {
    $vdata = ['id'=>$v['id'],'price'=>$v['price'],'stock'=>$v['stock'],'attrs'=>[],'images'=>[]];
    foreach ($v['attributes'] as $a) {
        $vdata['attrs'][] = ['name'=>$a['attribute_name'] ?? '','value'=>$a['attribute_value']];
    }
    foreach ($v['images'] as $vi) {
        $vdata['images'][] = BASE_URL . 'admin/' . $vi['image_url'];
    }
    $variants_for_prompt[] = $vdata;
}

// المنتجات المشابهة
$related_products = [];
try {
    $stmt = $pdo->prepare("SELECT p.*, pi.image_url AS image FROM products p LEFT JOIN product_images pi ON p.id = pi.product_id AND pi.is_primary = 1 WHERE p.category_id = ? AND p.id != ? AND p.is_active = 1 ORDER BY p.created_at DESC LIMIT 4");
    $stmt->execute([$product['category_id'], $product_id]);
    $related_products = $stmt->fetchAll();
} catch(PDOException $e) {}

// بيانات التوصيل للـ prompt
$delivery_info_for_prompt = [];
foreach ($delivery_companies as $dc) {
    if (in_array($dc['id'], $product_dc)) {
        $delivery_info_for_prompt[] = $dc['name'];
    }
}

// الثيم
$theme_settings = [];
if (!empty($store_settings['theme_settings'])) {
    $theme_settings = json_decode($store_settings['theme_settings'], true) ?? [];
}
$theme_defaults = ['primary_color'=>'#0F172A','accent_color'=>'#6C63FF','bg_color'=>'#F7F8FA','btn_radius'=>'rounded'];
$theme_settings = array_merge($theme_defaults, $theme_settings);
$radius_map = ['rounded'=>'14px','square'=>'4px','pill'=>'100px'];
$t_primary = preg_match('/^#[0-9A-Fa-f]{6}$/', $theme_settings['primary_color']) ? $theme_settings['primary_color'] : '#0F172A';
$t_accent  = preg_match('/^#[0-9A-Fa-f]{6}$/', $theme_settings['accent_color'])  ? $theme_settings['accent_color']  : '#6C63FF';
$t_bg      = preg_match('/^#[0-9A-Fa-f]{6}$/', $theme_settings['bg_color'])      ? $theme_settings['bg_color']      : '#F7F8FA';
$t_radius  = $radius_map[$theme_settings['btn_radius']] ?? '14px';

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'] = "حجم الملف كبير جداً: ".$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 = [];
    $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']; $tmp=(array)$files['tmp_name']; $errs=(array)$files['error']; $sizes=(array)$files['size'];
    foreach ($names as $i => $name) {
        if (empty($name) || $errs[$i] !== UPLOAD_ERR_OK) continue;
        $result = processImageFile(['name'=>$name,'type'=>$types[$i],'tmp_name'=>$tmp[$i],'error'=>$errs[$i],'size'=>$sizes[$i]], $upload_dir, $product_id, $variant_id);
        if ($result) $uploaded[] = ['path'=>$result];
    }
    return $uploaded;
}

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");
        $pdo->prepare("UPDATE products SET category_id=:cat,name=:name,description=:desc,price=:price,purchase_price=:pprice,discounted_price=:dprice,is_active=:active WHERE id=:id")
            ->execute([':cat'=>$category_id,':name'=>$name,':desc'=>$description,':price'=>$base_price,':pprice'=>$purch_price,':dprice'=>$disc_price,':active'=>$is_active,':id'=>$product_id]);
        $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]);
        }
        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]);
            }
        }
        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']]);
        }
$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) {
                    $pdo->prepare("UPDATE product_variants SET sku=:sku,price=:price,purchase_price=:pprice,stock=:stock,is_default=:def WHERE id=:id")
                        ->execute([':sku'=>$v_sku,':price'=>$v_price,':pprice'=>$v_purch,':stock'=>$v_stock,':def'=>$v_default,':id'=>$vid]);
                    $submitted_variant_ids[]=$vid;
                } else {
                    $pdo->prepare("INSERT INTO product_variants (product_id,sku,price,purchase_price,stock,is_default) VALUES (:pid,:sku,:price,:pprice,:stock,:def)")
                        ->execute([':pid'=>$product_id,':sku'=>$v_sku,':price'=>$v_price,':pprice'=>$v_purch,':stock'=>$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;
    }
}

$open_landing = isset($_GET['open_landing']) && $_GET['open_landing'] == '1';
?>
<!DOCTYPE html>
<html dir="rtl" lang="ar">
<head>
<?php include __DIR__ . '/darkmode.php'; ?>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>تعديل المنتج - <?= htmlspecialchars($product['name']) ?></title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<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;--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}
.header h1 .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;font-size:16px}
.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:8px;padding-bottom:14px;border-bottom:1.5px solid var(--border)}
.card-title i{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;font-size:14px}
.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: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;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;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:12px;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-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-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-success{background:var(--success);color:white}.btn-success:hover{background:#047857;transform:translateY(-1px)}
.btn-danger{background:var(--danger);color:white}.btn-danger:hover{background:#B91C1C;transform:translateY(-1px)}
.btn-gray{background:var(--surface-2);color:var(--text-2);border:1.5px solid var(--border)}.btn-gray:hover{background:var(--border)}
.btn-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 ===== */
.ai-card{border:1.5px solid #C4B5FD;background:linear-gradient(135deg,#FAF5FF,#F5F3FF)}
.ai-card .card-title{border-bottom-color:#DDD6FE;color:var(--purple)}
.ai-card .card-title i{background:linear-gradient(135deg,#7C3AED,#A78BFA)}
.lp-exists-banner{background:linear-gradient(135deg,#059669,#10B981);color:white;border-radius:var(--radius-sm);padding:12px 16px;display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;flex-wrap:wrap;gap:10px}
.lp-exists-banner .lp-info{font-size:13px;font-weight:700}.lp-exists-banner .lp-date{font-size:11px;opacity:0.85;margin-top:2px}
.lp-key-wrap{position:relative}.lp-key-wrap input{padding-left:40px!important}
.lp-key-wrap .eye-btn{position:absolute;left:12px;top:50%;transform:translateY(-50%);background:none;border:none;cursor:pointer;color:var(--text-3);font-size:15px;padding:0}
.lp-status{margin-top:14px;display:none}
.lp-preview-wrap{margin-top:16px;border:2px solid #DDD6FE;border-radius:var(--radius-sm);overflow:hidden;display:none}
.lp-preview-header{background:#EDE9FE;padding:8px 14px;font-size:12px;font-weight:700;color:var(--purple);border-bottom:1px solid #DDD6FE;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px}

/* ===== CHAT REFINEMENT ===== */
.chat-wrap{margin-top:16px;border:1.5px solid #DDD6FE;border-radius:var(--radius-sm);overflow:hidden;display:none}
.chat-header{background:#EDE9FE;padding:10px 14px;font-size:13px;font-weight:700;color:var(--purple);display:flex;align-items:center;gap:8px;border-bottom:1px solid #DDD6FE}
.chat-messages{max-height:280px;overflow-y:auto;padding:12px;display:flex;flex-direction:column;gap:10px;background:#FDFCFF}
.chat-msg{padding:10px 14px;border-radius:var(--radius-sm);font-size:13px;line-height:1.6;max-width:90%}
.chat-msg.user{background:var(--purple);color:white;align-self:flex-end;border-radius:var(--radius-sm) var(--radius-sm) 4px var(--radius-sm)}
.chat-msg.ai{background:white;color:var(--text);border:1px solid #DDD6FE;align-self:flex-start;border-radius:var(--radius-sm) var(--radius-sm) var(--radius-sm) 4px}
.chat-msg.ai.loading{color:var(--text-3);font-style:italic}
.chat-input-wrap{display:flex;gap:8px;padding:10px;background:#F5F3FF;border-top:1px solid #DDD6FE}
.chat-input-wrap input{flex:1;padding:9px 12px;border:1.5px solid #DDD6FE;border-radius:var(--radius-sm);font-size:13px;font-family:'Tajawal',sans-serif;outline:none;transition:var(--tr)}
.chat-input-wrap input:focus{border-color:var(--purple);box-shadow:0 0 0 3px rgba(124,58,237,0.1)}
.chat-examples{display:flex;flex-wrap:wrap;gap:6px;padding:8px 10px;background:#FAF5FF;border-top:1px solid #DDD6FE}
.chat-ex{font-size:11px;padding:4px 10px;background:white;border:1px solid #DDD6FE;border-radius:50px;cursor:pointer;color:var(--purple);font-weight:600;transition:var(--tr)}
.chat-ex:hover{background:var(--purple);color:white}

@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}}
</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;font-size:16px">
    <i class="fas fa-bars"></i>
</button>
<div class="sidebar-overlay" onclick="toggleSidebar()"></div>
<?php include 'sidebar.php'; ?>

<div class="container">

    <div class="header">
        <h1>
            <span class="icon-wrap"><i class="fas fa-edit"></i></span>
            تعديل: <?= htmlspecialchars($product['name']) ?>
        </h1>
        <a href="index.php" class="btn btn-gray"><i class="fas fa-arrow-right"></i> رجوع</a>
    </div>

    <?php if (isset($_SESSION['error_message'])): ?>
        <div class="msg msg-error"><i class="fas fa-exclamation-circle"></i> <?= htmlspecialchars($_SESSION['error_message']) ?></div>
        <?php unset($_SESSION['error_message']); ?>
    <?php endif; ?>
    <?php if (isset($_SESSION['message'])): ?>
        <div class="msg msg-success"><i class="fas fa-check-circle"></i> <?= htmlspecialchars($_SESSION['message']) ?></div>
        <?php unset($_SESSION['message']); ?>
    <?php endif; ?>

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

        <div class="card" style="animation-delay:0.05s">
            <div class="card-title"><i class="fas fa-info-circle"></i> المعلومات الأساسية</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"><i class="fas fa-tags"></i> الأسعار</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>

        <div class="card" style="animation-delay:0.15s">
            <div class="card-title"><i class="fas fa-truck"></i> شركات التوصيل</div>
            <span class="dc-select-all" onclick="toggleAllDC()"><i class="fas fa-check-square"></i> تحديد الكل / إلغاء</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.2s">
            <div class="card-title"><i class="fas fa-images"></i> صور المنتج الرئيسية</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">الصور الحالية</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)"><i class="fas fa-trash"></i></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"><i class="fas fa-cloud-upload-alt"></i></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.25s">
            <div class="card-title"><i class="fas fa-layer-group"></i> متغيرات المنتج <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"><i class="fas fa-plus"></i> إضافة متغير جديد</button>
            <div id="variantsContainer">
                <?php foreach ($variants as $idx => $variant): ?>
                <div class="variant-card" data-variant-index="<?= $idx ?>">
                    <div class="variant-header">
                        <span class="variant-title"><i class="fas fa-cube"></i> متغير #<?= $idx + 1 ?></span>
                        <button type="button" class="btn-remove-variant" onclick="removeVariant(this)"><i class="fas fa-times"></i></button>
                    </div>
                    <input type="hidden" name="variants[<?= $idx ?>][id]" value="<?= $variant['id'] ?>">
                    <div class="form-row">
                        <div class="form-group"><label>كود SKU</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'] ?>"></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)"><i class="fas fa-trash"></i></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>إضافة صور جديدة للمتغير</label>
                        <div class="upload-box" onclick="this.querySelector('input[type=file]').click()">
                            <div class="ub-icon"><i class="fas fa-images"></i></div><p class="ub-text">رفع صور</p><p class="ub-hint">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()"><i class="fas fa-times"></i></button>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <button type="button" class="btn btn-gray btn-sm" onclick="addAttrRow(this)"><i class="fas fa-plus"></i> إضافة خاصية</button>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="form-actions">
            <a href="index.php" class="btn btn-gray"><i class="fas fa-times"></i> إلغاء</a>
            <button type="submit" class="btn btn-warning"><i class="fas fa-save"></i> حفظ التعديلات</button>
        </div>
    </form>

    <!-- ===== بطاقة الذكاء الاصطناعي ===== -->
    <div class="card ai-card" style="animation-delay:0.35s" id="aiLandingCard">
        <div class="card-title">
            <i class="fas fa-bolt"></i>
            صفحة الهبوط بالذكاء الاصطناعي
            <span style="font-size:11px;font-weight:600;color:var(--purple);margin-right:auto">✨ Gemini AI</span>
        </div>

        <?php if ($landing_page): ?>
        <div class="lp-exists-banner">
            <div>
                <div class="lp-info">✅ صفحة الهبوط موجودة ومنشورة</div>
                <div class="lp-date">آخر تحديث: <?= date('Y/m/d H:i', strtotime($landing_page['updated_at'])) ?></div>
            </div>
            <div style="display:flex;gap:8px;flex-wrap:wrap">
                <a href="landing.php?id=<?= $product_id ?>" target="_blank" class="btn btn-success btn-sm"><i class="fas fa-external-link-alt"></i> عرض الصفحة</a>
                <button type="button" class="btn btn-gray btn-sm" onclick="previewExistingLanding()"><i class="fas fa-eye"></i> معاينة</button>
            </div>
        </div>
        <?php endif; ?>

        <div class="form-group">
            <label>Gemini API Key <span style="color:var(--text-3);font-size:11px">(لن يُحفظ)</span></label>
            <div class="lp-key-wrap">
                <input type="password" id="geminiApiKey" placeholder="AIzaSy..." style="font-family:monospace;font-size:13px">
                <button type="button" class="eye-btn" onclick="toggleKeyVisibility()"><i class="fas fa-eye" id="eyeIcon"></i></button>
            </div>
            <small style="font-size:11px;color:var(--text-3);margin-top:4px;display:block">احصل على مفتاحك مجاناً من <a href="https://aistudio.google.com/app/apikey" target="_blank" style="color:var(--purple)">Google AI Studio</a></small>
        </div>

        <div style="display:flex;gap:10px;flex-wrap:wrap;align-items:center">
            <button type="button" class="btn btn-purple" id="generateBtn" onclick="generateLandingPage()">
                <i class="fas fa-magic"></i> <?= $landing_page ? 'إعادة توليد الصفحة' : 'أنشئ صفحة هبوط' ?>
            </button>
            <?php if ($landing_page): ?>
            <a href="landing.php?id=<?= $product_id ?>" target="_blank" class="btn btn-gray btn-sm"><i class="fas fa-link"></i> <?= BASE_URL ?>landing.php?id=<?= $product_id ?></a>
            <?php endif; ?>
        </div>

        <div class="lp-status" id="lpStatus"></div>

        <!-- منطقة المعاينة -->
        <div class="lp-preview-wrap" id="lpPreview">
            <div class="lp-preview-header">
                <span><i class="fas fa-desktop"></i> معاينة صفحة الهبوط</span>
                <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
                    <a href="landing.php?id=<?= $product_id ?>" target="_blank" id="lpLink" style="display:none;color:var(--purple);font-size:11px;text-decoration:none"><i class="fas fa-external-link-alt"></i> فتح في تبويب</a>
                    <button type="button" class="btn btn-danger btn-sm" onclick="deleteLandingPage()" style="font-size:11px;padding:4px 10px"><i class="fas fa-trash"></i> حذف الصفحة</button>
                </div>
            </div>
            <iframe id="lpIframe" style="width:100%;height:600px;border:none"></iframe>
        </div>

        <!-- محادثة التعديل -->
        <div class="chat-wrap" id="chatWrap">
            <div class="chat-header"><i class="fas fa-comments"></i> تعديل الصفحة بالمحادثة — اطلب من Gemini تعديل أي جزء</div>
            <div class="chat-messages" id="chatMessages">
                <div class="chat-msg ai">👋 الصفحة جاهزة! يمكنك طلب أي تعديل — مثال: "غير لون الزر إلى أحمر" أو "أضف قسم مراجعات العملاء"</div>
            </div>
            <div class="chat-examples">
                <span class="chat-ex" onclick="quickChat(this)">غير لون الزر الرئيسي</span>
                <span class="chat-ex" onclick="quickChat(this)">أضف قسم مراجعات العملاء</span>
                <span class="chat-ex" onclick="quickChat(this)">حسّن قسم المميزات</span>
                <span class="chat-ex" onclick="quickChat(this)">أضف عداد تنازلي للعرض</span>
                <span class="chat-ex" onclick="quickChat(this)">اجعل التصميم أكثر احترافية</span>
                <span class="chat-ex" onclick="quickChat(this)">أضف صور المنتج في معرض</span>
            </div>
            <div class="chat-input-wrap">
                <input type="text" id="chatInput" placeholder="اكتب طلبك هنا... مثال: غير الخلفية إلى اللون الداكن" onkeydown="if(event.key==='Enter')sendChatMessage()">
                <button type="button" class="btn btn-purple btn-sm" onclick="sendChatMessage()"><i class="fas fa-paper-plane"></i></button>
            </div>
        </div>
    </div>

</div>

<template id="variantTemplate">
    <div class="variant-card" data-variant-index="">
        <div class="variant-header">
            <span class="variant-title"><i class="fas fa-cube"></i> متغير جديد #<span class="v-num"></span></span>
            <button type="button" class="btn-remove-variant" onclick="removeVariant(this)"><i class="fas fa-times"></i></button>
        </div>
        <div class="form-row">
            <div class="form-group"><label>كود SKU</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>صور المتغير</label>
            <div class="upload-box" onclick="this.querySelector('input[type=file]').click()"><div class="ub-icon"><i class="fas fa-images"></i></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">خصائص المتغير</div><div class="attr-rows"></div><button type="button" class="btn btn-gray btn-sm" onclick="addAttrRow(this)"><i class="fas fa-plus"></i> إضافة خاصية</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()"><i class="fas fa-times"></i></button>
    </div>
</template>

<script>
let vc            = <?= count($variants) ?>;
const attrsData   = <?= json_encode($attributes) ?>;
const newMainDT   = new DataTransfer();
const varDT       = {};
const PRODUCT_ID  = <?= $product_id ?>;
const BASE_URL    = '<?= BASE_URL ?>';
const MAIN_IMAGE  = '<?= $main_image ? BASE_URL . 'admin/' . $main_image['image_url'] : '' ?>';
const OPEN_LANDING = <?= $open_landing ? 'true' : 'false' ?>;

// بيانات المتجر والثيم
const STORE_NAME    = <?= json_encode($store_settings['name'] ?? 'متجرنا') ?>;
const STORE_LOGO    = '<?= !empty($store_settings['logo']) ? BASE_URL . 'admin/' . $store_settings['logo'] : '' ?>';
const STORE_PHONE   = <?= json_encode($store_settings['phone'] ?? '') ?>;
const STORE_FB      = <?= json_encode($store_settings['facebook'] ?? '') ?>;
const STORE_TG      = <?= json_encode($store_settings['telegram'] ?? '') ?>;
const STORE_IG      = <?= json_encode($store_settings['instgrame'] ?? '') ?>;
const THEME_PRIMARY = '<?= $t_primary ?>';
const THEME_ACCENT  = '<?= $t_accent ?>';
const THEME_BG      = '<?= $t_bg ?>';
const THEME_RADIUS  = '<?= $t_radius ?>';

const PRODUCT_IMAGES   = <?= json_encode($all_product_images_urls) ?>;
const PRODUCT_VARIANTS = <?= json_encode($variants_for_prompt) ?>;
const RELATED_PRODUCTS = <?= json_encode($related_products) ?>;
const DELIVERY_COS     = <?= json_encode($delivery_info_for_prompt) ?>;

// حالة الصفحة المولّدة
let currentGeneratedHTML = '';
let chatHistory = [];

window.addEventListener('DOMContentLoaded', () => {
    updateProfitMeter();
    if (OPEN_LANDING) {
        document.getElementById('aiLandingCard').scrollIntoView({ behavior:'smooth', block:'start' });
        document.getElementById('geminiApiKey').focus();
    }
});

// ===== PROFIT =====
function updateProfitMeter() {
    const buy=parseFloat(document.getElementById('purchasePrice').value)||0;
    const sell=parseFloat(document.getElementById('basePrice').value)||0;
    const meter=document.getElementById('profitMeter'), valEl=document.getElementById('profitValue'), pctEl=document.getElementById('profitPct');
    if(sell===0){meter.className='profit-meter';valEl.textContent='—';pctEl.textContent='أدخل الأسعار أعلاه';return;}
    const profit=sell-buy, 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 toggleAllDC() { const cbs=document.querySelectorAll('.dc-checkbox'),any=Array.from(cbs).some(c=>!c.checked); cbs.forEach(c=>c.checked=any); }

// ===== IMAGES =====
function markDeleteImage(imgId,btn){const wrap=document.getElementById('existing_img_'+imgId),cb=document.getElementById('del_img_'+imgId);cb.checked=!cb.checked;wrap.classList.toggle('marked-delete',cb.checked);btn.innerHTML=cb.checked?'<i class="fas fa-undo"></i>':'<i class="fas fa-trash"></i>';}
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 w=document.getElementById('existing_img_'+imgId);w.classList.add('is-primary');w.querySelector('.primary-lbl').textContent='✓ رئيسية';w.querySelector('input[type=radio]').checked=true;}
function markDeleteVariantImage(imgId,varIdx,btn){const wrap=document.getElementById('existing_vimg_'+imgId),cb=document.getElementById('del_vimg_'+imgId);cb.checked=!cb.checked;wrap.classList.toggle('marked-delete',cb.checked);btn.innerHTML=cb.checked?'<i class="fas fa-undo"></i>':'<i class="fas fa-trash"></i>';}
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 w=document.getElementById('existing_vimg_'+imgId);w.classList.add('is-primary');w.querySelector('.primary-lbl').textContent='✓ رئيسية';w.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;}if(!f.type.startsWith('image/')){alert('ملف غير مدعوم');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('حجم كبير');return;}varDT[idx].items.add(f);});input.files=varDT[idx].files;renderPreviews(varDT[idx].files,null,'variant-'+idx,input.closest('.form-group').querySelector('.variant-images-preview'));}
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.innerHTML='<i class="fas fa-times"></i>';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 hidden=type==='main'?document.getElementById('primaryMainImage'):document.querySelector('.variant-card[data-variant-index="'+type.split('-')[1]+'"] .primary-variant-image');if(hidden)hidden.value=i;};div.appendChild(img);div.appendChild(rm);div.appendChild(lbl);wrap.appendChild(div);};reader.readAsDataURL(file);});}

// ===== VARIANTS =====
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;delete varDT[btn.closest('.variant-card').dataset.variantIndex];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);tpl.querySelector('.attr-value-select').name='variants['+idx+'][attributes][]';card.querySelector('.attr-rows').appendChild(tpl);}
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+']';}

// ===== KEY TOGGLE =====
function toggleKeyVisibility(){const inp=document.getElementById('geminiApiKey'),icon=document.getElementById('eyeIcon');if(inp.type==='password'){inp.type='text';icon.className='fas fa-eye-slash';}else{inp.type='password';icon.className='fas fa-eye';}}

// ===== STATUS =====
function showStatus(msg,type='info'){const el=document.getElementById('lpStatus');const c={info:'var(--info-l)',success:'var(--success-l)',error:'var(--danger-l)'};const b={info:'#BAE6FD',success:'#A7F3D0',error:'#FECACA'};const t={info:'var(--info)',success:'var(--success)',error:'var(--danger)'};el.style.display='block';el.innerHTML=`<div style="padding:12px 16px;background:${c[type]};border:1px solid ${b[type]};border-radius:var(--radius-sm);color:${t[type]};font-weight:600;font-size:13px">${msg}</div>`;}

// ===== BUILD PROMPT =====
function buildPrompt(name, description, price, discPrice) {
    const mainImg = PRODUCT_IMAGES[0] || MAIN_IMAGE;

    // بناء قسم المتغيرات
    let variantsSection = '';
    if (PRODUCT_VARIANTS.length > 0) {
        const attrGroups = {};
        PRODUCT_VARIANTS.forEach(v => {
            v.attrs.forEach(a => {
                if (!attrGroups[a.name]) attrGroups[a.name] = new Set();
                attrGroups[a.name].add(a.value);
            });
        });
        variantsSection = '\n\nالمتغيرات المتاحة:\n';
        Object.entries(attrGroups).forEach(([k,v]) => { variantsSection += `- ${k}: ${[...v].join(' | ')}\n`; });
        variantsSection += '\nبيانات المتغيرات JSON:\n' + JSON.stringify(PRODUCT_VARIANTS);
    }

    // المنتجات المشابهة
    let relatedSection = '';
    if (RELATED_PRODUCTS.length > 0) {
        relatedSection = '\n\nمنتجات مشابهة (لعرضها في آخر الصفحة):\n';
        RELATED_PRODUCTS.forEach(r => {
            const img = r.image ? BASE_URL + 'admin/' + r.image : '';
            relatedSection += `- ${r.name} | السعر: ${r.price} دج | الرابط: ${BASE_URL}det.php?id=${r.id}${img ? ' | الصورة: ' + img : ''}\n`;
        });
    }

    // الصور الكاملة
    let imagesSection = mainImg ? `الصورة الرئيسية: ${mainImg}\n` : '';
    if (PRODUCT_IMAGES.length > 1) {
        imagesSection += `كل الصور: ${PRODUCT_IMAGES.join(' | ')}\n`;
    }

    // روابط التواصل
    const socialLinks = [];
    if (STORE_FB) socialLinks.push(`فيسبوك: ${STORE_FB}`);
    if (STORE_TG) socialLinks.push(`تيليغرام: ${STORE_TG}`);
    if (STORE_IG) socialLinks.push(`إنستجرام: ${STORE_IG}`);

    const discBadge = discPrice ? `السعر القديم: ${discPrice} دج — توفير ${Math.round((discPrice-price)/discPrice*100)}%` : '';

    return `أنت مطور ومصمم UI/UX محترف. أنشئ صفحة هبوط HTML متكاملة لمتجر جزائري.

══════════════════════════════
بيانات المتجر:
══════════════════════════════
الاسم: ${STORE_NAME}
${STORE_LOGO ? 'الشعار: ' + STORE_LOGO : ''}
الهاتف: ${STORE_PHONE || 'غير محدد'}
${socialLinks.length ? 'التواصل الاجتماعي:\n' + socialLinks.join('\n') : ''}

══════════════════════════════
بيانات المنتج:
══════════════════════════════
الاسم: ${name}
الوصف: ${description || 'منتج عالي الجودة'}
السعر: ${price} دج
${discBadge}
شركات التوصيل: ${DELIVERY_COS.join(', ') || 'متوفر'}
${imagesSection}${variantsSection}${relatedSection}

══════════════════════════════
ألوان وثيم المتجر:
══════════════════════════════
اللون الأساسي: ${THEME_PRIMARY}
لون التمييز: ${THEME_ACCENT}
لون الخلفية: ${THEME_BG}
border-radius: ${THEME_RADIUS}

══════════════════════════════
المتطلبات الإلزامية — اقرأ بعناية:
══════════════════════════════

1. NAVBAR ثابت (sticky, z-index:9999):
   - شعار + اسم المتجر (لون خلفية: ${THEME_PRIMARY})
   - لا يختفي عند التمرير أبداً

2. Hero Section:
   - صورة المنتج + الاسم + السعر + شارة الخصم إن وجد
   - زر "اطلب الآن" بلافت ونبض (animation pulse)

3. معرض الصور (Gallery):
   - صورة رئيسية كبيرة + thumbnails
   - النقر على thumbnail يغير الصورة الرئيسية بـ animation

4. المتغيرات (إن وجدت):
   - chips/buttons قابلة للاختيار
   - النقر يغير الصورة المعروضة إن توفرت صورة للمتغير

5. نموذج الطلب — MANDATORY — لا تنساه أبداً:
   هذا أهم قسم في الصفحة. يجب أن يحتوي على:
   - حقل: الاسم الكامل (required)
   - حقل: رقم الهاتف (required, pattern جزائري: 05/06/07)
   - حقل: هاتف إضافي (اختياري)
   - حقل: العنوان (اختياري)
   - اختيار نوع التوصيل: إلى المنزل / إلى المكتب (radio buttons)
   - قائمة الولايات: dropdown مع 58 ولاية جزائرية (01-أدرار إلى 58-المنيعة)
   - حقل الكمية مع أزرار + و -
   - ملخص الطلب: السعر × الكمية + رسوم التوصيل = المجموع
   - زر تأكيد الطلب كبير ولافت
   - النموذج يرسل POST إلى submit_order.php مع الحقول: customer_name, phone, phone2, address, wilaya_id, delivery_type, quantity, product_id, variant_id (hidden: ${PRODUCT_ID})
   - عند النقر على زر الإرسال: التحقق من الاسم والهاتف والولاية قبل الإرسال

6. قسم المميزات: 3-4 مميزات مع أيقونات emoji

7. قسم الثقة: 🚚 توصيل سريع | 💳 دفع عند الاستلام | ✅ ضمان الجودة

8. المنتجات المشابهة (إن وجدت):
   - grid cards احترافية مع صورة + اسم + سعر + زر
   - الروابط تفتح صفحة المنتج

9. Footer:
   - شعار + اسم المتجر + رقم الهاتف + روابط التواصل
   - حقوق الملكية

10. المتطلبات التقنية:
    - ملف HTML واحد مكتفٍ بذاته
    - Tailwind CSS من CDN: <script src="https://cdn.tailwindcss.com"><\/script>
    - Font Awesome من CDN للأيقونات
    - خط Cairo من Google Fonts
    - RTL وlang="ar"
    - متجاوب 100% مع الجوال

══════════════════════════════
قواعد الإخراج:
══════════════════════════════
- ابدأ مباشرة بـ <!DOCTYPE html>
- لا backticks لا شرح لا نص خارج الكود
- الكود يعمل مباشرة بدون أي تعديل`;
}

// ===== GENERATE =====
async function generateLandingPage() {
    const apiKey = document.getElementById('geminiApiKey').value.trim();
    if (!apiKey) { alert('⚠️ أدخل Gemini API Key أولاً'); document.getElementById('geminiApiKey').focus(); return; }

    const btn = document.getElementById('generateBtn');
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> جارٍ التوليد...';

    const name        = document.querySelector('[name="name"]')?.value || '<?= addslashes($product['name']) ?>';
    const description = document.querySelector('[name="description"]')?.value || '<?= addslashes($product['description'] ?? '') ?>';
    const price       = parseFloat(document.querySelector('[name="base_price"]')?.value || '<?= $product['price'] ?>');
    const discPrice   = parseFloat(document.querySelector('[name="discounted_price"]')?.value) || null;

    const prompt = buildPrompt(name, description, price, discPrice);
    chatHistory = []; // إعادة تهيئة سجل المحادثة

    showStatus('🤖 Gemini يولّد صفحة الهبوط الكاملة... قد يستغرق 20-40 ثانية', 'info');

    try {
        const html = await callGemini(apiKey, prompt);
        if (!html.includes('<html') && !html.includes('<!DOCTYPE')) throw new Error('الرد من Gemini لم يكن HTML صالحاً — حاول مجدداً');

        currentGeneratedHTML = html;

        // حفظ الصورة الأولى
        showStatus('💾 جارٍ الحفظ...', 'info');
        await saveLandingPage(html);

        // عرض المعاينة
        showPreview(html);

        const landingUrl = BASE_URL + 'landing.php?id=' + PRODUCT_ID;
        showStatus(`✅ تم إنشاء صفحة الهبوط! <a href="${landingUrl}" target="_blank" style="color:var(--success);text-decoration:underline;margin-right:8px">🔗 عرض الصفحة</a>`, 'success');

        // إظهار منطقة المحادثة
        document.getElementById('chatWrap').style.display = 'block';
        document.getElementById('chatMessages').innerHTML = '<div class="chat-msg ai">✅ الصفحة جاهزة! يمكنك الآن طلب أي تعديل.</div>';

        btn.innerHTML = '<i class="fas fa-magic"></i> إعادة توليد كامل';

    } catch(err) {
        showStatus('❌ ' + err.message, 'error');
        btn.innerHTML = '<i class="fas fa-magic"></i> أنشئ صفحة هبوط';
    } finally {
        btn.disabled = false;
    }
}

// ===== CHAT REFINEMENT =====
function quickChat(el) {
    document.getElementById('chatInput').value = el.textContent;
    sendChatMessage();
}

async function sendChatMessage() {
    const apiKey = document.getElementById('geminiApiKey').value.trim();
    if (!apiKey) { alert('⚠️ أدخل Gemini API Key أولاً'); return; }
    if (!currentGeneratedHTML) { alert('⚠️ يجب توليد الصفحة أولاً'); return; }

    const input = document.getElementById('chatInput');
    const msg = input.value.trim();
    if (!msg) return;

    input.value = '';
    addChatMsg(msg, 'user');

    const loadingMsg = addChatMsg('⏳ Gemini يعدّل الصفحة...', 'ai loading');

    const prompt = `أنت خبير HTML/CSS. لديك صفحة هبوط HTML كاملة، وعليك تعديلها بناءً على الطلب التالي:

الطلب: ${msg}

الصفحة الحالية:
${currentGeneratedHTML}

التعليمات:
- أعد الصفحة كاملة بعد التعديل
- لا تحذف أي محتوى موجود إلا إذا طُلب ذلك
- ابدأ مباشرة بـ <!DOCTYPE html> بدون أي شرح أو backticks
- الكود يجب أن يعمل مباشرة`;

    try {
        const html = await callGemini(apiKey, prompt);
        if (!html.includes('<html') && !html.includes('<!DOCTYPE')) throw new Error('الرد لم يكن HTML صالحاً');

        currentGeneratedHTML = html;
        loadingMsg.remove();
        addChatMsg('✅ تم التعديل! الصفحة محدّثة في المعاينة', 'ai');

        await saveLandingPage(html);
        showPreview(html);

    } catch(err) {
        loadingMsg.remove();
        addChatMsg('❌ ' + err.message, 'ai');
    }
}

function addChatMsg(text, type) {
    const wrap = document.getElementById('chatMessages');
    const div = document.createElement('div');
    div.className = 'chat-msg ' + type;
    div.textContent = text;
    wrap.appendChild(div);
    wrap.scrollTop = wrap.scrollHeight;
    return div;
}

// ===== GEMINI API =====
async function callGemini(apiKey, prompt) {
    const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${apiKey}`;
    const response = await fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            contents: [{ parts: [{ text: prompt }] }],
            generationConfig: { temperature: 0.7, maxOutputTokens: 8192 }
        })
    });
    if (!response.ok) {
        const err = await response.json();
        throw new Error(err.error?.message || 'خطأ في Gemini API');
    }
    const data = await response.json();
    let html = data.candidates?.[0]?.content?.parts?.[0]?.text || '';
    html = html.replace(/^```html\s*/i,'').replace(/^```\s*/i,'').replace(/```\s*$/i,'').trim();
    return html;
}

// ===== SAVE =====
async function saveLandingPage(html) {
    const resp = await fetch('save_landing_page.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ product_id: PRODUCT_ID, html_content: html })
    });
    let data;
    try { data = await resp.json(); } catch(e) { throw new Error('خطأ في استجابة الخادم'); }
    if (!data.success) throw new Error(data.message || 'فشل حفظ الصفحة');
}

// ===== PREVIEW =====
function showPreview(html) {
    const iframe = document.getElementById('lpIframe');
    iframe.srcdoc = html;
    document.getElementById('lpPreview').style.display = 'block';
    document.getElementById('lpLink').style.display = 'inline-flex';
}

// ===== DELETE =====
async function deleteLandingPage() {
    if (!confirm('هل تريد حذف صفحة الهبوط نهائياً؟')) return;
    try {
        const resp = await fetch('save_landing_page.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ product_id: PRODUCT_ID, action: 'delete' })
        });
        const data = await resp.json();
        if (data.success) {
            document.getElementById('lpPreview').style.display = 'none';
            document.getElementById('chatWrap').style.display = 'none';
            currentGeneratedHTML = '';
            showStatus('✅ تم حذف صفحة الهبوط', 'success');
        }
    } catch(e) { showStatus('❌ فشل الحذف', 'error'); }
}

function previewExistingLanding() {
    const iframe = document.getElementById('lpIframe');
    iframe.src = 'landing.php?id=' + PRODUCT_ID;
    document.getElementById('lpPreview').style.display = 'block';
    document.getElementById('lpLink').style.display = 'inline-flex';
    document.getElementById('chatWrap').style.display = 'block';
    iframe.scrollIntoView({ behavior:'smooth', block:'start' });
}
</script>
</body>
</html>