<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/db.php';

try {
    $pixel = $pdo->query("SELECT meta_pixel_id, meta_pixel_enabled FROM stores WHERE id = 1")->fetch();
} catch (Exception $e) { $pixel = null; }

if (isset($_GET['id']) && is_numeric($_GET['id'])) {
    $product_id = (int) $_GET['id'];
} else { die("معرف المنتج غير صالح أو مفقود"); }

$product = []; $product_attributes = []; $product_images = [];
$product_variants = []; $delivery_info = [];
$delivery_prices_home = []; $delivery_prices_office = []; $wilayas = [];

function formatWilayaForDisplay($id, $name) {
    $id_padded = str_pad($id, 2, '0', STR_PAD_LEFT);
    $arabic_names = [
        1=>'أدرار',2=>'الشلف',3=>'الأغواط',4=>'أم البواقي',5=>'باتنة',
        6=>'بجاية',7=>'بسكرة',8=>'بشار',9=>'البليدة',10=>'البويرة',
        11=>'تمنراست',12=>'تبسة',13=>'تلمسان',14=>'تيارت',15=>'تيزي وزو',
        16=>'الجزائر',17=>'الجلفة',18=>'جيجل',19=>'سطيف',20=>'سعيدة',
        21=>'سكيكدة',22=>'سيدي بلعباس',23=>'عنابة',24=>'قالمة',25=>'قسنطينة',
        26=>'المدية',27=>'مستغانم',28=>'المسيلة',29=>'معسكر',30=>'ورقلة',
        31=>'وهران',32=>'البيض',33=>'إليزي',34=>'برج بوعريريج',35=>'بومرداس',
        36=>'الطارف',37=>'تندوف',38=>'تيسمسيلت',39=>'الوادي',40=>'خنشلة',
        41=>'سوق أهراس',42=>'تيبازة',43=>'ميلة',44=>'عين الدفلة',45=>'النعامة',
        46=>'عين تموشنت',47=>'غرداية',48=>'غليزان',49=>'تيميمون',50=>'برج باجي مختار',
        51=>'أولاد جلال',52=>'بني عباس',53=>'عين صالح',54=>'عين قزام',55=>'تقرت',
        56=>'جانت',57=>'المغير',58=>'المنيعة'
    ];
    $arabic_name = isset($arabic_names[$id]) ? $arabic_names[$id] : $name;
    return $id_padded . ' - ' . $name . ' / ' . $arabic_name;
}

try {
    $stmt = $pdo->prepare("
        SELECT p.*, c.name AS category_name,
               (SELECT GROUP_CONCAT(dc.id) FROM product_delivery_companies pdc 
                JOIN delivery_companies dc ON pdc.delivery_company_id = dc.id 
                WHERE pdc.product_id = p.id) AS delivery_company_ids
        FROM products p 
        LEFT JOIN categories c ON p.category_id = c.id 
        WHERE p.id = ?
    ");
    $stmt->execute([$product_id]);
    $product = $stmt->fetch();
    if (!$product) { die("المنتج غير موجود"); }

    $stmt = $pdo->prepare("SELECT a.id, a.name, pa.value, a.input_type, a.values_list FROM product_attributes pa JOIN attributes a ON pa.attribute_id = a.id WHERE pa.product_id = ?");
    $stmt->execute([$product_id]);
    $product_attributes = $stmt->fetchAll();

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

    $stmt = $pdo->prepare("SELECT pv.id, pv.sku, pv.price, pv.stock, pv.is_default FROM product_variants pv WHERE pv.product_id = ?");
    $stmt->execute([$product_id]);
    $product_variants = $stmt->fetchAll();

    foreach ($product_variants as &$variant) {
        $stmt = $pdo->prepare("SELECT a.name AS attribute_name, va.attribute_value FROM variant_attributes va JOIN attributes a ON va.attribute_id = a.id WHERE va.variant_id = ?");
        $stmt->execute([$variant['id']]);
        $variant['variant_attrs'] = $stmt->fetchAll();
        $stmt = $pdo->prepare("SELECT image_url, is_primary FROM variant_images WHERE variant_id = ? ORDER BY is_primary DESC, id ASC");
        $stmt->execute([$variant['id']]);
        $variant['variant_images'] = $stmt->fetchAll();
    }
    unset($variant);

    if (!empty($product['delivery_company_ids'])) {
        $delivery_company_ids = explode(',', $product['delivery_company_ids']);
        $first_company_id = $delivery_company_ids[0];
        $stmt = $pdo->prepare("SELECT dc.id, dc.name FROM delivery_companies dc WHERE dc.id = ?");
        $stmt->execute([$first_company_id]);
        $delivery_info = $stmt->fetch();
        $stmt = $pdo->prepare("SELECT dp.wilaya_id, dp.price, w.name AS wilaya_name FROM delivery_prices dp JOIN wilayas w ON dp.wilaya_id = w.id WHERE dp.delivery_company_id = ? AND dp.delivery_type = 'home'");
        $stmt->execute([$first_company_id]);
        $delivery_prices_home = $stmt->fetchAll();
        $stmt = $pdo->prepare("SELECT dp.wilaya_id, dp.price, w.name AS wilaya_name FROM delivery_prices dp JOIN wilayas w ON dp.wilaya_id = w.id WHERE dp.delivery_company_id = ? AND dp.delivery_type = 'office'");
        $stmt->execute([$first_company_id]);
        $delivery_prices_office = $stmt->fetchAll();
        $available_wilayas = array_unique(array_merge(array_column($delivery_prices_home, 'wilaya_id'), array_column($delivery_prices_office, 'wilaya_id')));
        if (!empty($available_wilayas)) {
            sort($available_wilayas);
            $stmt = $pdo->prepare("SELECT id, name FROM wilayas WHERE id IN (" . implode(',', array_fill(0, count($available_wilayas), '?')) . ") ORDER BY id ASC");
            $stmt->execute($available_wilayas);
            $wilayas = $stmt->fetchAll();
        }
    }
} catch (PDOException $e) {
    die("خطأ: " . $e->getMessage());
}

$communes_data = [];
$cities_json_file = __DIR__ . '/cities.json';
if (file_exists($cities_json_file)) {
    $json_content = file_get_contents($cities_json_file);
    $communes_data = json_decode($json_content, true);
    if (json_last_error() !== JSON_ERROR_NONE) { $communes_data = []; }
}

$default_variant = !empty($product_variants) ? $product_variants[0] : null;
$default_price_for_display = $product['price'];
if (!empty($product_variants)) {
    foreach ($product_variants as $variant) {
        if ($variant['stock'] > 0) { $default_price_for_display = $variant['price']; break; }
    }
}

$stmt2 = $pdo->query("SELECT * FROM stores WHERE id = 1");
$store = $stmt2->fetch();

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

$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) {}

$all_images = [];
foreach ($product_images as $image) {
    $all_images[] = ['type'=>'product','image_url'=>$image['image_url'],'is_primary'=>$image['is_primary']];
}

$variant_attributes = [];
if (!empty($product_variants)) {
    foreach ($product_variants as $variant) {
        if ($variant['stock'] > 0) {
            foreach ($variant['variant_attrs'] as $attr) {
                $attr_name = $attr['attribute_name'];
                $attr_value = $attr['attribute_value'];
                if (!isset($variant_attributes[$attr_name])) { $variant_attributes[$attr_name] = []; }
                if (!in_array($attr_value, $variant_attributes[$attr_name])) { $variant_attributes[$attr_name][] = $attr_value; }
            }
        }
        foreach ($variant['variant_images'] as $image) {
            $found = false;
            foreach ($all_images as $existing) { if ($existing['image_url'] === $image['image_url']) { $found = true; break; } }
            if (!$found) { $all_images[] = ['type'=>'variant','variant_id'=>$variant['id'],'image_url'=>$image['image_url'],'is_primary'=>$image['is_primary']]; }
        }
    }
}

usort($all_images, function($a, $b) { return ($a['is_primary'] == $b['is_primary']) ? 0 : (($a['is_primary'] > $b['is_primary']) ? -1 : 1); });
$main_image_url = !empty($all_images) ? $all_images[0]['image_url'] : '';

$is_product_available = false;
$available_stock = 0;
if (!empty($product_variants)) {
    foreach ($product_variants as $variant) { if ($variant['stock'] > 0) { $is_product_available = true; $available_stock += $variant['stock']; } }
} else {
    $is_product_available = ($product['stock_quantity'] > 0);
    $available_stock = $product['stock_quantity'];
}

$has_variants = !empty($variant_attributes);
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($product['name']); ?> - Riham Cosmetics</title>

    <?php if ($pixel && $pixel['meta_pixel_enabled'] && !empty(trim($pixel['meta_pixel_id']))): ?>
    <?php $pixel_id = htmlspecialchars(trim($pixel['meta_pixel_id'])); ?>
    <script>
    !function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','https://connect.facebook.net/en_US/fbevents.js');
    fbq('init','<?php echo $pixel_id; ?>');fbq('track','PageView');
    fbq('track','ViewContent',{content_ids:['<?php echo $product['id']; ?>'],content_name:'<?php echo addslashes($product['name']); ?>',content_type:'product',value:<?php echo $product['discounted_price'] ?: $product['price']; ?>,currency:'DZD',content_category:'<?php echo addslashes($product['category_name'] ?? 'عام'); ?>'});
    </script>
    <noscript><img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=<?php echo $pixel_id; ?>&ev=PageView&noscript=1"/></noscript>
    <?php endif; ?>

    <link rel="icon" href="<?php echo BASE_URL . 'admin/' . htmlspecialchars($store['logo']); ?>" type="image/jpg">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;700;800;900&family=Playfair+Display:ital,wght@0,700;1,400&display=swap" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<style>
/* ══════════════════════════════════════
   RIHAM COSMETICS — PRODUCT DETAIL PAGE
   ══════════════════════════════════════ */
:root {
    --rose:        #e8547a;
    --rose-light:  #f9a8bf;
    --rose-dark:   #c0395c;
    --blush:       #fce4ec;
    --blush-deep:  #f8bbd9;
    --green:       #6abf69;
    --green-dark:  #388e3c;
    --cream:       #fff8f9;
    --white:       #ffffff;
    --text-dark:   #3a1a24;
    --text-mid:    #7a4a5a;
    --text-light:  #b08090;
    --success:     #10b981;
    --danger:      #ef4444;
    --warn:        #f59e0b;
    --warn-light:  #fef3c7;

    --shadow-xs:  0 1px 4px rgba(232,84,122,.08);
    --shadow-sm:  0 2px 12px rgba(232,84,122,.12);
    --shadow-md:  0 6px 28px rgba(232,84,122,.18);
    --shadow-lg:  0 16px 48px rgba(232,84,122,.22);

    --radius-sm: 10px;
    --radius:    16px;
    --radius-lg: 24px;
    --radius-xl: 50px;

    --transition: .3s cubic-bezier(.4,0,.2,1);
    --font: 'Tajawal', sans-serif;
}

*,*::before,*::after { margin:0; padding:0; box-sizing:border-box; }
html { scroll-behavior:smooth; }
body {
    font-family: var(--font);
    background: var(--cream);
    color: var(--text-dark);
    line-height: 1.65;
    -webkit-font-smoothing: antialiased;
    overflow-x: hidden;
}
body::before {
    content:'';
    position:fixed; inset:0;
    background:
        radial-gradient(circle at 10% 15%, rgba(249,168,191,.15) 0%, transparent 40%),
        radial-gradient(circle at 90% 85%, rgba(106,191,105,.10) 0%, transparent 35%);
    pointer-events:none; z-index:0;
}
a { text-decoration:none; color:inherit; }
img { max-width:100%; display:block; }
button,select,input,textarea { font-family:var(--font); }
button { cursor:pointer; }

/* ── Container ── */
.container { width:100%; max-width:1200px; margin:0 auto; padding:0 20px; position:relative; z-index:1; }

/* ═══ TOP BAR ═══ */
.topbar {
    background: linear-gradient(90deg, var(--rose-dark), var(--rose), var(--rose-dark));
    background-size:200% 100%;
    animation: shimmerBar 4s linear infinite;
    padding:8px 0; color:white; font-size:13px; z-index:10; position:relative;
}
@keyframes shimmerBar { 0%{background-position:0%} 100%{background-position:200%} }
.topbar .container { display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:8px; }
.topbar a { color:rgba(255,255,255,.9); display:flex; align-items:center; gap:6px; transition:var(--transition); }
.topbar a:hover { color:white; transform:translateY(-1px); }
.topbar-links { display:flex; gap:20px; }
.topbar-badge { background:rgba(255,255,255,.2); border-radius:20px; padding:2px 12px; font-size:12px; }

/* ═══ HEADER ═══ */
.header {
    position:sticky; top:0; z-index:100;
    background:rgba(255,255,255,.96);
    backdrop-filter:blur(16px);
    box-shadow: 0 2px 20px rgba(232,84,122,.10);
    border-bottom:2px solid var(--blush-deep);
}
.header-inner {
    display:flex; align-items:center; gap:24px;
    padding:12px 20px; max-width:1200px; margin:0 auto;
}
.logo-area { display:flex; align-items:center; gap:12px; flex-shrink:0; }
.logo-img-wrap {
    width:62px; height:62px; border-radius:50%; overflow:hidden;
    border:3px solid var(--rose-light);
    box-shadow:var(--shadow-sm);
    transition:var(--transition);
    flex-shrink:0;
}
.logo-img-wrap:hover { transform:scale(1.06) rotate(-2deg); box-shadow:var(--shadow-md); }
.logo-img-wrap img { width:100%; height:100%; object-fit:cover; }
.logo-name { font-family:'Playfair Display',serif; font-size:22px; font-weight:700; color:var(--rose-dark); }
.logo-name span { font-style:italic; color:var(--green-dark); }
.logo-sub { font-size:11px; color:var(--text-light); font-weight:300; letter-spacing:2px; text-transform:uppercase; }

.search-form {
    flex:1; max-width:480px; margin:0 auto;
    display:flex; border:2px solid var(--blush-deep);
    border-radius:var(--radius-xl); overflow:hidden;
    background:var(--blush); transition:var(--transition);
}
.search-form:focus-within { border-color:var(--rose); background:white; box-shadow:0 0 0 4px rgba(232,84,122,.12); }
.search-form input {
    flex:1; border:none; background:transparent;
    padding:11px 18px; font-size:14px; outline:none; color:var(--text-dark);
}
.search-form input::placeholder { color:var(--text-light); }
.search-form button {
    background:linear-gradient(135deg,var(--rose),var(--rose-dark));
    border:none; padding:0 20px; color:white; font-size:16px;
    transition:var(--transition);
}
.search-form button:hover { background:var(--rose-dark); }

/* ═══ NAVBAR ═══ */
.navbar {
    background:linear-gradient(90deg,var(--rose-dark) 0%,var(--rose) 50%,var(--green) 100%);
    position:relative;
}
.navbar::after {
    content:''; position:absolute; bottom:0; left:0; right:0; height:3px;
    background:linear-gradient(90deg,var(--rose-dark),var(--rose-light),var(--green),var(--rose-light),var(--rose-dark));
}
.nav-list { list-style:none; display:flex; justify-content:center; max-width:1200px; margin:0 auto; padding:0 20px; }
.nav-item a {
    display:flex; align-items:center; gap:7px; color:white;
    padding:14px 20px; font-weight:600; font-size:14px;
    transition:var(--transition); position:relative;
}
.nav-item a::after {
    content:''; position:absolute; bottom:8px; right:50%; left:50%;
    height:2px; background:white; border-radius:2px; transition:var(--transition);
}
.nav-item a:hover::after { right:14px; left:14px; }
.nav-item a:hover { background:rgba(255,255,255,.12); }
.nav-item { position:relative; }
.dropdown {
    position:absolute; top:calc(100%+6px); right:0;
    background:white; min-width:220px;
    box-shadow:var(--shadow-lg); border-radius:var(--radius-sm);
    overflow:hidden; display:none; z-index:200;
    border:1px solid var(--blush-deep);
    animation:dropIn .2s ease;
}
@keyframes dropIn { from{opacity:0;transform:translateY(-8px);} to{opacity:1;transform:translateY(0);} }
.nav-item:hover .dropdown { display:block; }
.dropdown a {
    display:flex; align-items:center; gap:8px;
    padding:11px 16px; color:var(--text-dark); font-size:14px;
    border-bottom:1px solid var(--blush); transition:var(--transition);
}
.dropdown a:last-child { border-bottom:none; }
.dropdown a:hover { background:var(--blush); color:var(--rose-dark); padding-right:22px; }

/* ═══ BREADCRUMB ═══ */
.breadcrumb {
    display:flex; align-items:center; gap:6px;
    flex-wrap:wrap; padding:16px 0; font-size:13px; color:var(--text-light);
}
.breadcrumb a { color:var(--rose); transition:var(--transition); }
.breadcrumb a:hover { color:var(--rose-dark); }
.breadcrumb i { font-size:10px; }

/* ═══ TRUST BAR ═══ */
.trust-bar {
    display:flex; align-items:center; justify-content:center;
    flex-wrap:wrap; gap:10px;
    background:white; border:1.5px solid var(--blush-deep);
    border-radius:var(--radius); padding:14px 18px; margin-bottom:10px;
    box-shadow:var(--shadow-xs);
}
.trust-item {
    display:flex; align-items:center; gap:6px;
    font-size:12px; font-weight:700; color:var(--text-mid);
    padding:6px 14px; background:var(--cream);
    border-radius:var(--radius-xl); border:1px solid var(--blush-deep);
}
.trust-item i { font-size:15px; }
.trust-item.rose i { color:var(--rose); }
.trust-item.green i { color:var(--green-dark); }
.trust-item.orange i { color:#f97316; }
.trust-item.gold i { color:#d4a017; }

/* ═══ PRODUCT CARD ═══ */
.product-card {
    background:white;
    border-radius:var(--radius-lg);
    box-shadow:var(--shadow-sm);
    border:1.5px solid var(--blush-deep);
    padding:28px;
    display:grid; grid-template-columns:1fr 1fr; gap:36px;
    margin-bottom:32px;
    animation:fadeUp .5s ease;
}
@keyframes fadeUp { from{opacity:0;transform:translateY(24px);} to{opacity:1;transform:translateY(0);} }
@media(max-width:768px) { .product-card{grid-template-columns:1fr;padding:16px;gap:20px;} }

/* ═══ GALLERY ═══ */
.product-gallery { position:relative; }
.main-image-wrap {
    position:relative; overflow:hidden;
    border-radius:var(--radius); height:420px;
    background:linear-gradient(135deg,var(--blush),#fce4f0);
    border:1.5px solid var(--blush-deep);
    display:flex; align-items:center; justify-content:center;
    cursor:zoom-in;
}
.main-image-wrap img {
    max-width:100%; max-height:100%; object-fit:contain;
    transition:transform .4s ease;
}
.main-image-wrap:hover img { transform:scale(1.42); }

.gallery-btn {
    position:absolute; top:50%; transform:translateY(-50%);
    width:40px; height:40px;
    background:rgba(255,255,255,.92); border:1.5px solid var(--blush-deep);
    border-radius:50%; display:flex; align-items:center; justify-content:center;
    font-size:15px; color:var(--text-dark);
    box-shadow:var(--shadow-xs); transition:var(--transition); z-index:5;
}
.gallery-btn:hover { background:var(--rose); color:white; border-color:var(--rose); transform:translateY(-50%) scale(1.1); }
.gallery-btn.prev { right:10px; }
.gallery-btn.next { left:10px; }

.thumbs {
    display:flex; gap:8px; margin-top:12px;
    overflow-x:auto; padding:4px 2px 8px;
    scrollbar-width:thin; scrollbar-color:var(--rose) #eee;
}
.thumbs::-webkit-scrollbar { height:4px; }
.thumbs::-webkit-scrollbar-thumb { background:var(--rose); border-radius:4px; }
.thumb {
    width:72px; height:72px; flex-shrink:0;
    border-radius:var(--radius-sm); overflow:hidden;
    border:2.5px solid transparent; cursor:pointer;
    transition:var(--transition); background:var(--blush);
}
.thumb img { width:100%; height:100%; object-fit:cover; }
.thumb:hover { border-color:var(--rose); transform:scale(1.06); }
.thumb.active { border-color:var(--rose); box-shadow:0 0 0 3px rgba(232,84,122,.22); }

@media(max-width:480px) { .main-image-wrap{height:270px;} .thumb{width:58px;height:58px;} }

/* ═══ PRODUCT INFO ═══ */
.product-info { display:flex; flex-direction:column; gap:18px; }

.product-badge {
    display:inline-flex; align-items:center; gap:6px;
    background:var(--blush); color:var(--rose-dark);
    padding:5px 14px; border-radius:var(--radius-xl);
    font-size:12px; font-weight:700; width:fit-content;
    border:1px solid var(--blush-deep);
}
.product-title {
    font-family:'Playfair Display',serif;
    font-size:24px; font-weight:700;
    color:var(--text-dark); line-height:1.35;
}
@media(max-width:480px) { .product-title{font-size:19px;} }

.product-desc-box {
    background:var(--blush); border-right:4px solid var(--rose);
    border-radius:var(--radius-sm); padding:14px 16px;
    font-size:14px; color:var(--text-mid); line-height:1.75;
}

/* ═══ OUT OF STOCK ═══ */
.oos-box {
    background:linear-gradient(135deg,#fff5f5,#fee2e2);
    border:2px solid #fca5a5; border-radius:var(--radius);
    padding:24px; text-align:center;
}
.oos-box i { font-size:40px; color:var(--danger); margin-bottom:10px; display:block; }
.oos-box h3 { color:#dc2626; margin-bottom:6px; }
.oos-box p { color:#666; font-size:14px; }

/* ═══ VARIANTS ═══ */
.variants-wrapper { display:flex; flex-direction:column; gap:14px; }

.variant-block {
    background:var(--cream); border:2px solid var(--blush-deep);
    border-radius:var(--radius); padding:18px;
    transition:var(--transition);
}
.variant-block.completed {
    border-color:var(--green); background:linear-gradient(135deg,#f0fdf4,#dcfce7);
}
.variant-block.needs-selection {
    border-color:var(--warn); background:linear-gradient(135deg,#fffbeb,#fef3c7);
    animation:attentionPulse 1.5s ease 3;
}
@keyframes attentionPulse {
    0%,100%{box-shadow:0 0 0 0 rgba(245,158,11,.4);}
    50%{box-shadow:0 0 0 8px rgba(245,158,11,0);}
}
.variant-block h4 {
    font-size:13px; font-weight:700; color:var(--text-mid);
    text-transform:uppercase; letter-spacing:.05em; margin-bottom:12px;
    display:flex; align-items:center; gap:6px;
}
.status-icon {
    margin-right:auto; width:22px; height:22px; border-radius:50%;
    display:flex; align-items:center; justify-content:center;
    font-size:12px; font-weight:700; flex-shrink:0; transition:var(--transition);
}
.variant-block.completed .status-icon { background:var(--green); color:white; }
.variant-block:not(.completed) .status-icon { background:var(--warn-light); color:#92400e; }

.variant-values { display:flex; gap:8px; flex-wrap:wrap; }
.v-chip {
    padding:8px 16px; border:2px solid var(--blush-deep);
    border-radius:var(--radius-xl); cursor:pointer;
    font-size:13px; font-weight:600; color:var(--text-mid);
    background:white; transition:var(--transition); user-select:none;
}
.v-chip:hover { border-color:var(--rose); color:var(--rose); }
.v-chip.selected {
    border-color:var(--rose); background:var(--rose); color:white;
    box-shadow:0 4px 12px rgba(232,84,122,.3);
}
.v-chip.has-image { display:flex; align-items:center; gap:8px; padding:6px 14px 6px 8px; }
.chip-thumb { width:28px; height:28px; border-radius:6px; object-fit:cover; border:1px solid rgba(0,0,0,.1); }
.v-chip.oos { opacity:.4; cursor:not-allowed; text-decoration:line-through; }

.variant-error-hint {
    display:none; margin-top:10px; padding:8px 12px;
    background:var(--warn-light); border:1px solid #fbbf24;
    border-radius:8px; font-size:12px; font-weight:700; color:#92400e;
    align-items:center; gap:6px;
}
.variant-block.needs-selection .variant-error-hint { display:flex; }

/* ─ Global alert ─ */
.variant-global-alert {
    display:none; background:linear-gradient(135deg,#fff7ed,#fed7aa);
    border:2px solid #fb923c; border-radius:var(--radius);
    padding:16px 20px; gap:14px; align-items:flex-start;
    animation:slideDown .3s ease;
}
@keyframes slideDown { from{opacity:0;transform:translateY(-10px);} to{opacity:1;transform:translateY(0);} }
.variant-global-alert.visible { display:flex; }
.alert-icon {
    width:42px; height:42px; flex-shrink:0; background:#fb923c;
    border-radius:50%; display:flex; align-items:center; justify-content:center;
    font-size:20px; color:white;
}
.alert-title { font-size:15px; font-weight:800; color:#9a3412; margin-bottom:4px; }
.alert-list { list-style:none; padding:0; margin:0; display:flex; flex-direction:column; gap:4px; }
.alert-list li { font-size:13px; color:#7c2d12; font-weight:600; display:flex; align-items:center; gap:6px; }
.alert-list li i { color:#fb923c; }
.alert-action {
    display:inline-flex; align-items:center; gap:6px;
    margin-top:10px; padding:7px 14px;
    background:#fb923c; color:white; border:none; border-radius:var(--radius-xl);
    font-size:13px; font-weight:700; transition:var(--transition);
}
.alert-action:hover { background:#ea580c; }

/* ─ Complete badge ─ */
.variant-complete-badge {
    display:none; background:linear-gradient(135deg,#f0fdf4,#dcfce7);
    border:2px solid #86efac; border-radius:var(--radius);
    padding:14px 18px; align-items:center; gap:12px;
    animation:popIn .3s cubic-bezier(.34,1.56,.64,1);
}
@keyframes popIn { from{opacity:0;transform:scale(.92);} to{opacity:1;transform:scale(1);} }
.variant-complete-badge.visible { display:flex; }
.badge-icon {
    width:40px; height:40px; flex-shrink:0; background:var(--green);
    border-radius:50%; display:flex; align-items:center; justify-content:center;
    font-size:18px; color:white;
}
.badge-title { font-size:14px; font-weight:800; color:#166534; }
.badge-attrs { display:flex; flex-wrap:wrap; gap:6px; margin-top:6px; }
.badge-attr-tag {
    background:var(--green); color:white;
    padding:3px 10px; border-radius:var(--radius-xl);
    font-size:12px; font-weight:700;
}

/* ═══ PRICE BOX ═══ */
.price-box {
    background:linear-gradient(135deg,var(--blush),#fce4f0);
    border:2px solid var(--blush-deep); border-radius:var(--radius);
    padding:18px 20px;
    display:flex; align-items:center; justify-content:space-between;
    flex-wrap:wrap; gap:10px;
}
.price-main { font-size:32px; font-weight:900; color:var(--rose-dark); }
.price-old { font-size:18px; color:var(--text-light); text-decoration:line-through; }
.price-badge {
    background:var(--danger); color:white;
    padding:3px 10px; border-radius:var(--radius-xl);
    font-size:12px; font-weight:700; width:fit-content;
}
.price-note { font-size:12px; color:var(--text-light); display:flex; align-items:center; gap:4px; margin-top:4px; }

/* ═══ FAB ═══ */
.order-fab {
    position:fixed; bottom:76px; left:16px; right:16px;
    z-index:800; text-align:center;
    opacity:0; transform:translateY(16px);
    transition:var(--transition); pointer-events:none;
}
.order-fab.show { opacity:1; transform:translateY(0); pointer-events:all; }
.order-fab-btn {
    display:inline-flex; align-items:center; justify-content:center; gap:10px;
    color:white; border:none; padding:16px 32px;
    border-radius:var(--radius-xl); font-size:17px; font-weight:800;
    width:100%; max-width:420px; transition:var(--transition);
}
.order-fab-btn.state-select {
    background:linear-gradient(135deg,var(--warn),#d97706);
    box-shadow:0 8px 24px rgba(245,158,11,.4);
    animation:fabWarn 2.5s ease infinite;
}
.order-fab-btn.state-ready {
    background:linear-gradient(135deg,var(--rose),var(--rose-dark));
    box-shadow:0 8px 24px rgba(232,84,122,.45);
    animation:fabReady 2.5s ease infinite;
}
.order-fab-btn.state-disabled { background:#ccc; box-shadow:none; animation:none; cursor:not-allowed; }
@keyframes fabWarn {
    0%,100%{box-shadow:0 8px 24px rgba(245,158,11,.4);}
    50%{box-shadow:0 12px 36px rgba(245,158,11,.6),0 0 0 8px rgba(245,158,11,.1);}
}
@keyframes fabReady {
    0%,100%{box-shadow:0 8px 24px rgba(232,84,122,.45);}
    50%{box-shadow:0 12px 36px rgba(232,84,122,.65),0 0 0 8px rgba(232,84,122,.12);}
}
.order-fab-btn:hover:not(.state-disabled) { animation:none; transform:translateY(-2px); }

/* ═══ ORDER SECTION ═══ */
.order-section {
    background:white; border-radius:var(--radius-lg);
    box-shadow:var(--shadow-sm); border:1.5px solid var(--blush-deep);
    overflow:hidden; margin-bottom:40px;
}
.order-title-bar {
    background:linear-gradient(135deg,var(--rose),var(--rose-dark));
    padding:22px 28px; display:flex; align-items:center; gap:14px; color:white;
}
.order-title-bar .icon-wrap {
    width:48px; height:48px; background:rgba(255,255,255,.2);
    border-radius:50%; display:flex; align-items:center; justify-content:center;
    font-size:22px;
}
.order-title-bar h3 { font-family:'Playfair Display',serif; font-size:20px; font-weight:700; }
.order-title-bar p { font-size:13px; opacity:.85; margin-top:2px; }

.order-body { padding:26px 28px; }
@media(max-width:600px) { .order-body{padding:16px;} }

/* Form fields */
.fields-grid { display:grid; grid-template-columns:1fr 1fr; gap:14px; }
@media(max-width:600px) { .fields-grid{grid-template-columns:1fr;} }

.form-field { display:flex; flex-direction:column; gap:5px; }
.form-field label {
    font-size:12px; font-weight:700; color:var(--text-light);
    text-transform:uppercase; letter-spacing:.04em;
    display:flex; align-items:center; gap:5px;
}
.form-field label i { color:var(--rose); }
.field-input {
    padding:11px 14px; border:2px solid var(--blush-deep);
    border-radius:var(--radius-sm); font-size:14px; background:white;
    transition:var(--transition); outline:none; width:100%;
}
.field-input:focus { border-color:var(--rose); box-shadow:0 0 0 3px rgba(232,84,122,.1); }
.field-input.error { border-color:var(--danger); }
.field-note { font-size:11px; color:var(--text-light); margin-top:2px; display:flex; align-items:center; gap:4px; }

.form-divider {
    display:flex; align-items:center; gap:10px;
    margin:18px 0; color:var(--text-light); font-size:12px; font-weight:600;
}
.form-divider::before,.form-divider::after { content:''; flex:1; height:1px; background:var(--blush-deep); }

/* Delivery pills */
.delivery-pills { display:flex; gap:10px; margin-top:4px; }
.del-pill {
    flex:1; display:flex; align-items:center; justify-content:center; gap:8px;
    padding:11px; border-radius:var(--radius-sm); border:2px solid var(--blush-deep);
    cursor:pointer; transition:var(--transition);
    background:white; font-size:13px; font-weight:600; color:var(--text-mid);
}
.del-pill input { display:none; }
.del-pill:has(input:checked) { border-color:var(--rose); background:var(--blush); color:var(--rose-dark); }
.del-pill i { font-size:18px; }

/* Order strip */
.order-strip {
    background:linear-gradient(135deg,var(--blush),#fce4f0);
    border:1.5px solid var(--blush-deep); border-radius:var(--radius);
    padding:16px 20px; margin:18px 0;
    display:flex; align-items:center; justify-content:space-between;
    flex-wrap:wrap; gap:12px;
}
.strip-item { display:flex; flex-direction:column; gap:4px; align-items:center; }
.strip-label { font-size:11px; color:var(--text-light); font-weight:600; text-transform:uppercase; }
.strip-val { font-size:20px; font-weight:800; color:var(--text-dark); }
.strip-val.total { color:var(--rose-dark); font-size:24px; }

/* Qty */
.qty-ctrl { display:flex; align-items:center; gap:8px; }
.qty-btn {
    width:34px; height:34px; border-radius:8px;
    border:2px solid var(--rose); background:white; color:var(--rose);
    font-size:18px; font-weight:700; display:flex; align-items:center; justify-content:center;
    transition:var(--transition);
}
.qty-btn:hover { background:var(--rose); color:white; }
.qty-input {
    width:52px; height:34px; text-align:center;
    border:2px solid var(--blush-deep); border-radius:8px;
    font-size:16px; font-weight:700; outline:none; transition:var(--transition);
}
.qty-input:focus { border-color:var(--rose); }

/* Submit btn */
.submit-btn {
    width:100%; padding:16px;
    background:linear-gradient(135deg,var(--green),var(--green-dark));
    color:white; border:none; border-radius:var(--radius);
    font-size:17px; font-weight:800;
    display:flex; align-items:center; justify-content:center; gap:10px;
    box-shadow:0 6px 20px rgba(106,191,105,.35);
    transition:var(--transition);
}
.submit-btn:hover:not(:disabled) { background:linear-gradient(135deg,var(--green-dark),#1b5e20); transform:translateY(-2px); box-shadow:0 10px 28px rgba(56,142,60,.45); }
.submit-btn:disabled { background:#ccc; box-shadow:none; cursor:not-allowed; }
.submit-note {
    display:flex; align-items:center; justify-content:center; gap:6px;
    margin-top:12px; background:#f0fdf4; border:1px solid #86efac;
    border-radius:8px; padding:10px; font-size:13px; color:#166534; font-weight:600;
}

/* ═══ RELATED ═══ */
.section-head { text-align:center; margin:50px 0 28px; }
.section-head h2 {
    font-family:'Playfair Display',serif;
    font-size:clamp(20px,3vw,30px); color:var(--text-dark);
    display:inline-block; position:relative; padding-bottom:12px;
}
.section-head h2::before,.section-head h2::after { content:'✦'; color:var(--rose-light); font-size:16px; margin:0 10px; }
.section-head h2 .line {
    position:absolute; bottom:0; left:50%; transform:translateX(-50%);
    width:60px; height:3px;
    background:linear-gradient(90deg,var(--rose),var(--green));
    border-radius:2px;
}
.section-head p { color:var(--text-light); font-size:14px; margin-top:6px; }

.related-grid {
    display:grid; grid-template-columns:repeat(4,1fr); gap:20px; margin-bottom:50px;
}
@media(max-width:900px) { .related-grid{grid-template-columns:repeat(2,1fr);} }
@media(max-width:480px) { .related-grid{grid-template-columns:1fr 1fr;gap:12px;} }

.rel-card {
    background:white; border-radius:var(--radius);
    border:1.5px solid var(--blush-deep);
    overflow:hidden; transition:var(--transition);
    box-shadow:var(--shadow-xs);
}
.rel-card:hover { transform:translateY(-7px); box-shadow:var(--shadow-md); border-color:var(--rose-light); }
.rel-img { height:170px; overflow:hidden; background:var(--blush); }
.rel-img img { width:100%; height:100%; object-fit:cover; transition:var(--transition); }
.rel-card:hover .rel-img img { transform:scale(1.07); }
.rel-body { padding:12px; }
.rel-name { font-size:14px; font-weight:700; color:var(--text-dark); height:40px; overflow:hidden; line-height:1.4; margin-bottom:8px; }
.rel-price { font-size:16px; font-weight:800; color:var(--rose-dark); }
.rel-price-old { font-size:12px; color:var(--text-light); text-decoration:line-through; margin-right:6px; }
.rel-btn {
    display:flex; align-items:center; justify-content:center; gap:6px;
    background:var(--blush); color:var(--rose-dark); padding:8px;
    border-radius:8px; font-size:13px; font-weight:700; margin-top:10px;
    border:1px solid var(--blush-deep); transition:var(--transition);
}
.rel-btn:hover { background:var(--rose); color:white; }

/* ═══ FOOTER ═══ */
.footer {
    background:linear-gradient(135deg,var(--text-dark) 0%,#5a1a2a 50%,#1a3a1a 100%);
    color:white; padding:40px 0 20px; position:relative;
}
.footer::before {
    content:''; position:absolute; top:0; left:0; right:0; height:4px;
    background:linear-gradient(90deg,var(--rose-dark),var(--rose-light),var(--green),var(--rose-light),var(--rose-dark));
}
.footer-bottom {
    text-align:center; padding-top:20px;
    border-top:1px solid rgba(255,255,255,.1);
    font-size:13px; color:rgba(255,255,255,.6);
}
.footer-bottom span { color:var(--rose-light); }

/* ═══ MOBILE NAV ═══ */
.mobile-nav {
    display:none; position:fixed; bottom:0; right:0; left:0;
    background:white; border-top:2px solid var(--blush-deep);
    box-shadow:0 -4px 20px rgba(232,84,122,.12); z-index:900;
}
.mobile-nav ul { display:flex; list-style:none; padding:8px 0; margin:0; }
.mobile-nav a {
    flex:1; display:flex; flex-direction:column; align-items:center; gap:3px;
    color:var(--text-light); font-size:11px; font-weight:600; padding:4px 0;
    transition:var(--transition);
}
.mobile-nav a.active,.mobile-nav a:hover { color:var(--rose-dark); }
.mobile-nav a i { font-size:20px; }
@media(max-width:768px) { .navbar{display:none;} .mobile-nav{display:block;} .order-fab{bottom:68px;} body{padding-bottom:70px;} }

/* ─ Scroll top ─ */
.scroll-top {
    position:fixed; bottom:24px; left:24px;
    background:linear-gradient(135deg,var(--rose),var(--rose-dark));
    color:white; width:46px; height:46px; border-radius:50%;
    display:flex; align-items:center; justify-content:center;
    cursor:pointer; opacity:0; visibility:hidden;
    transition:var(--transition); z-index:200;
    box-shadow:var(--shadow-md); border:none; font-size:16px;
}
.scroll-top.show { opacity:1; visibility:visible; }
.scroll-top:hover { transform:translateY(-3px); }
@media(max-width:768px) { .scroll-top{bottom:80px;} }

.hidden { display:none!important; }
</style>
</head>
<body>

<!-- Scroll top -->
<button class="scroll-top" id="scrollTop"><i class="fas fa-chevron-up"></i></button>

<!-- Top bar -->
<div class="topbar">
    <div class="container">
        <div class="topbar-links">
            <a href="tel:<?php echo htmlspecialchars($store['phone']); ?>">
                <i class="fas fa-phone-alt"></i><?php echo htmlspecialchars($store['phone']); ?>
            </a>
            <a href="mailto:<?php echo htmlspecialchars($store['emailp']); ?>">
                <i class="fas fa-envelope"></i><?php echo htmlspecialchars($store['emailp']); ?>
            </a>
        </div>
        <span class="topbar-badge">🌸 منتجات تجميل أصيلة</span>
    </div>
</div>

<!-- Header -->
<header class="header">
    <div class="header-inner">
        <div class="logo-area">
            <a href="index.php">
                <div class="logo-img-wrap">
                    <?php if (!empty($store['logo'])): ?>
                        <img src="<?php echo BASE_URL.'admin/'.htmlspecialchars($store['logo']); ?>" alt="Riham Cosmetics">
                    <?php else: ?>
                        <div style="width:100%;height:100%;display:flex;align-items:center;justify-content:center;background:var(--blush);font-size:24px;">🌸</div>
                    <?php endif; ?>
                </div>
            </a>
            <a href="index.php">
                <div class="logo-name">Riham <span>Cosmetics</span></div>
                <div class="logo-sub">ريهام كوسميتك</div>
            </a>
        </div>
        <form action="index.php" method="GET" class="search-form">
            <input type="text" name="search" placeholder="ابحثي عن منتج جمالك...">
            <button type="submit"><i class="fas fa-search"></i></button>
        </form>
    </div>
    <nav class="navbar">
        <ul class="nav-list">
            <li class="nav-item"><a href="index.php"><i class="fas fa-home"></i> الرئيسية</a></li>
            <li class="nav-item"><a href="track_order.php"><i class="fas fa-box"></i> طلباتك</a></li>
            <li class="nav-item">
                <a href="#"><i class="fas fa-th-large"></i> الأقسام <i class="fas fa-chevron-down" style="font-size:10px"></i></a>
                <div class="dropdown">
                    <?php foreach($categories as $cat): ?>
                        <a href="index.php?category=<?php echo $cat['id']; ?>"><i class="fas fa-tag"></i><?php echo htmlspecialchars($cat['name']); ?></a>
                    <?php endforeach; ?>
                </div>
            </li>
            <li class="nav-item"><a href="#"><i class="fas fa-heart"></i> عنا</a></li>
            <li class="nav-item"><a href="#"><i class="fas fa-phone-alt"></i> اتصلي بنا</a></li>
        </ul>
    </nav>
</header>

<!-- Main -->
<main class="container">

    <!-- Breadcrumb -->
    <div class="breadcrumb">
        <a href="index.php"><i class="fas fa-home"></i> الرئيسية</a>
        <i class="fas fa-chevron-left"></i>
        <?php if(!empty($product['category_name'])): ?>
            <a href="index.php?category=<?php echo $product['category_id']; ?>"><?php echo htmlspecialchars($product['category_name']); ?></a>
            <i class="fas fa-chevron-left"></i>
        <?php endif; ?>
        <span><?php echo htmlspecialchars($product['name']); ?></span>
    </div>

    <!-- Trust bar -->
    <div class="trust-bar">
        <div class="trust-item rose"><i class="fas fa-shield-alt"></i> دفع عند الاستلام</div>
        <div class="trust-item green"><i class="fas fa-truck"></i> توصيل لكل الولايات</div>
        <div class="trust-item orange"><i class="fas fa-undo"></i> إمكانية الإرجاع</div>
        <div class="trust-item gold"><i class="fas fa-star"></i> منتجات أصلية مضمونة</div>
    </div>

    <!-- Product Card -->
    <div class="product-card">

        <!-- Gallery -->
        <div class="product-gallery" id="productGallery">
            <div class="main-image-wrap" id="mainImageWrap">
                <button class="gallery-btn prev" onclick="prevImage()"><i class="fas fa-chevron-right"></i></button>
                <img id="mainImage"
                     src="<?php echo $main_image_url ? BASE_URL.'admin/'.htmlspecialchars($main_image_url) : ''; ?>"
                     alt="<?php echo htmlspecialchars($product['name']); ?>">
                <button class="gallery-btn next" onclick="nextImage()"><i class="fas fa-chevron-left"></i></button>
            </div>
            <div class="thumbs" id="thumbsGallery">
                <?php foreach($all_images as $i=>$img): if(empty($img['image_url'])) continue; ?>
                <div class="thumb <?php echo $i===0?'active':''; ?>"
                     data-index="<?php echo $i; ?>"
                     data-variant="<?php echo $img['type']==='variant' ? $img['variant_id'] : ''; ?>"
                     onclick="changeMainImage('<?php echo BASE_URL.'admin/'.htmlspecialchars($img['image_url']); ?>',<?php echo $i; ?>)">
                    <img src="<?php echo BASE_URL.'admin/'.htmlspecialchars($img['image_url']); ?>" alt="">
                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <!-- Info -->
        <div class="product-info">
            <?php if(!empty($product['category_name'])): ?>
            <div class="product-badge"><i class="fas fa-tag"></i><?php echo htmlspecialchars($product['category_name']); ?></div>
            <?php endif; ?>

            <h1 class="product-title"><?php echo htmlspecialchars($product['name']); ?></h1>

            <div class="product-desc-box"><?php echo nl2br(htmlspecialchars($product['description'])); ?></div>

            <?php if(!$is_product_available): ?>
            <div class="oos-box">
                <i class="fas fa-times-circle"></i>
                <h3>نعتذر، المنتج غير متوفر حالياً</h3>
                <p>تم نفاد الكمية. نعمل على تجديد المخزون قريباً 🌸</p>
            </div>
            <?php endif; ?>

            <!-- Variants -->
            <?php if($is_product_available && $has_variants): ?>

            <div class="variant-global-alert" id="variantGlobalAlert">
                <div class="alert-icon"><i class="fas fa-exclamation"></i></div>
                <div>
                    <div class="alert-title">يرجى اختيار الخصائص التالية أولاً</div>
                    <ul class="alert-list" id="missingAttrsList"></ul>
                    <button type="button" class="alert-action" id="goToSelectBtn">
                        <i class="fas fa-arrow-up"></i> اختر الآن
                    </button>
                </div>
            </div>

            <div class="variants-wrapper" id="variantsWrapper">
                <?php foreach($variant_attributes as $attr_name => $attr_values): ?>
                <div class="variant-block"
                     id="vblock-<?php echo htmlspecialchars(preg_replace('/\s+/','_',$attr_name)); ?>"
                     data-attr="<?php echo htmlspecialchars($attr_name); ?>">
                    <h4>
                        <i class="fas fa-palette"></i>
                        اختر <?php echo htmlspecialchars($attr_name); ?>
                        <span class="status-icon" id="sicon-<?php echo htmlspecialchars(preg_replace('/\s+/','_',$attr_name)); ?>">
                            <i class="fas fa-question"></i>
                        </span>
                    </h4>
                    <div class="variant-values">
                        <?php foreach($attr_values as $val):
                            $chip_img = '';
                            foreach($product_variants as $vv) {
                                $has_val = false;
                                foreach($vv['variant_attrs'] as $va) {
                                    if($va['attribute_name']===$attr_name && $va['attribute_value']===$val) { $has_val=true; break; }
                                }
                                if($has_val && !empty($vv['variant_images'])) {
                                    $chip_img = BASE_URL.'admin/'.htmlspecialchars($vv['variant_images'][0]['image_url']);
                                    break;
                                }
                            }
                        ?>
                        <div class="v-chip <?php echo $chip_img?'has-image':''; ?>"
                             data-attribute="<?php echo htmlspecialchars($attr_name); ?>"
                             data-value="<?php echo htmlspecialchars($val); ?>">
                            <?php if($chip_img): ?>
                                <img class="chip-thumb" src="<?php echo $chip_img; ?>" alt="<?php echo htmlspecialchars($val); ?>">
                            <?php endif; ?>
                            <?php echo htmlspecialchars($val); ?>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <div class="variant-error-hint">
                        <i class="fas fa-hand-point-up"></i>
                        <span>يرجى اختيار <?php echo htmlspecialchars($attr_name); ?> للمتابعة</span>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>

            <div class="variant-complete-badge" id="variantCompleteBadge">
                <div class="badge-icon"><i class="fas fa-check"></i></div>
                <div>
                    <div class="badge-title">✓ ممتاز! تم تحديد الخصائص</div>
                    <div class="badge-attrs" id="badgeAttrsList"></div>
                </div>
            </div>

            <?php endif; ?>

            <!-- Price -->
            <?php if($is_product_available): ?>
            <div class="price-box" id="priceBox">
                <div>
                    <div style="font-size:12px;color:var(--text-light);font-weight:600;margin-bottom:4px;">السعر</div>
                    <div class="price-main" id="variantPriceDisplay"><?php echo number_format($default_price_for_display,2); ?> دج</div>
                    <div class="price-note"><i class="fas fa-info-circle"></i> لا يشمل التوصيل</div>
                </div>
                <div>
                    <?php if($product['discounted_price'] && $product['discounted_price'] < $product['price']): ?>
                    <div class="price-old"><?php echo number_format($product['price'],2); ?> دج</div>
                    <div class="price-badge">-<?php echo round(($product['price']-$product['discounted_price'])/$product['price']*100); ?>%</div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- FAB -->
    <div class="order-fab" id="orderFab">
        <button class="order-fab-btn <?php echo (!$is_product_available)?'state-disabled':($has_variants?'state-select':'state-ready'); ?>"
                id="orderFabBtn"
                <?php echo !$is_product_available?'disabled':''; ?>>
            <?php if(!$is_product_available): ?>
                <i class="fas fa-times-circle"></i> غير متوفر
            <?php elseif($has_variants): ?>
                <i class="fas fa-hand-pointer"></i>
                <span id="fabBtnText">اختر الخصائص أولاً</span>
            <?php else: ?>
                <i class="fas fa-shopping-bag"></i> اطلبي الآن
            <?php endif; ?>
        </button>
    </div>

    <!-- Order Section -->
    <div class="order-section" id="orderSection">
        <div class="order-title-bar">
            <div class="icon-wrap"><i class="fas fa-clipboard-list"></i></div>
            <div>
                <h3>أكملي طلبك 🌸</h3>
                <p>أدخلي بياناتك وسنتصل بك لتأكيد الطلب</p>
            </div>
        </div>
        <div class="order-body">
            <form id="orderForm" action="submit_order.php" method="POST">

                <?php if($has_variants): ?>
                <div class="form-field" style="margin-bottom:16px;">
                    <label><i class="fas fa-check-circle"></i> الخصائص المختارة</label>
                    <div id="formAttrsDisplay" style="
                        background:var(--blush); border:2px dashed var(--blush-deep);
                        border-radius:var(--radius-sm); padding:12px 16px;
                        font-size:14px; color:var(--text-light);
                        display:flex; align-items:center; gap:8px; flex-wrap:wrap;">
                        <i class="fas fa-mouse-pointer"></i> يرجى اختيار الخصائص من الأعلى
                    </div>
                    <input type="hidden" id="selectedAttributesInput" name="selected_attributes" value="">
                </div>
                <?php else: ?>
                <input type="hidden" id="selectedAttributesInput" name="selected_attributes" value="[]">
                <?php endif; ?>

                <div class="fields-grid">
                    <div class="form-field">
                        <label><i class="fas fa-user"></i> الاسم الكامل *</label>
                        <div style="position:relative;">
                            <span style="position:absolute;top:50%;right:12px;transform:translateY(-50%);color:var(--rose);pointer-events:none;"><i class="fas fa-id-card"></i></span>
                            <input type="text" name="customer_name" id="customer_name" class="field-input" placeholder="أدخلي اسمك الكامل" required style="padding-right:38px;">
                        </div>
                    </div>
                    <div class="form-field">
                        <label><i class="fas fa-phone"></i> الهاتف الأساسي *</label>
                        <div style="position:relative;">
                            <span style="position:absolute;top:50%;right:12px;transform:translateY(-50%);color:var(--rose);pointer-events:none;"><i class="fas fa-mobile-alt"></i></span>
                            <input type="tel" name="phone" id="phone" class="field-input" placeholder="0XXXXXXXXX" required style="padding-right:38px;">
                        </div>
                    </div>
                </div>
                <div class="fields-grid" style="margin-top:14px;">
                    <div class="form-field">
                        <label><i class="fas fa-phone-volume"></i> هاتف إضافي <span style="font-weight:400;text-transform:none">(اختياري)</span></label>
                        <div style="position:relative;">
                            <span style="position:absolute;top:50%;right:12px;transform:translateY(-50%);color:var(--text-light);pointer-events:none;"><i class="fas fa-phone-square-alt"></i></span>
                            <input type="tel" name="phone2" id="phone2" class="field-input" placeholder="0XXXXXXXXX" style="padding-right:38px;">
                        </div>
                    </div>
                    <div class="form-field">
                        <label><i class="fas fa-map-marker-alt"></i> العنوان <span style="font-weight:400;text-transform:none">(اختياري)</span></label>
                        <div style="position:relative;">
                            <span style="position:absolute;top:50%;right:12px;transform:translateY(-50%);color:var(--text-light);pointer-events:none;"><i class="fas fa-home"></i></span>
                            <input type="text" name="address" id="address" class="field-input" placeholder="الشارع، الحي..." style="padding-right:38px;">
                        </div>
                    </div>
                </div>

                <div class="form-divider"><i class="fas fa-map"></i> معلومات التوصيل</div>

                <div class="form-field">
                    <label><i class="fas fa-city"></i> الولاية *</label>
                    <div style="position:relative;">
                        <span style="position:absolute;top:50%;right:12px;transform:translateY(-50%);color:var(--rose);pointer-events:none;"><i class="fas fa-map-marked-alt"></i></span>
                        <select name="wilaya_id" id="wilaya-select-form" class="field-input" required style="padding-right:38px;">
                            <option value="">— اختري ولايتك —</option>
                            <?php foreach($wilayas as $w): ?>
                            <option value="<?php echo $w['id']; ?>"><?php echo formatWilayaForDisplay($w['id'],$w['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="field-note"><i class="fas fa-info-circle"></i> اختري ولايتك لحساب سعر التوصيل</div>
                </div>

                <div id="communeRow" style="margin-top:14px;display:none;">
                    <div class="form-field">
                        <label><i class="fas fa-location-arrow"></i> البلدية</label>
                        <div style="position:relative;">
                            <span style="position:absolute;top:50%;right:12px;transform:translateY(-50%);color:var(--rose);pointer-events:none;"><i class="fas fa-map-pin"></i></span>
                            <select name="commune_id" id="commune-select-form" class="field-input" style="padding-right:38px;">
                                <option value="">— اختري بلديتك —</option>
                            </select>
                        </div>
                    </div>
                </div>

                <div style="margin-top:16px;">
                    <label style="font-size:12px;font-weight:700;color:var(--text-light);text-transform:uppercase;letter-spacing:.04em;display:flex;align-items:center;gap:5px;margin-bottom:8px;">
                        <i class="fas fa-truck" style="color:var(--rose)"></i> نوع التوصيل
                    </label>
                    <div class="delivery-pills">
                        <label class="del-pill"><input type="radio" name="delivery_type" value="home" checked><i class="fas fa-home"></i> إلى المنزل</label>
                        <label class="del-pill"><input type="radio" name="delivery_type" value="office"><i class="fas fa-building"></i> إلى المكتب</label>
                    </div>
                </div>

                <div class="order-strip">
                    <div class="strip-item">
                        <div class="strip-label">الكمية</div>
                        <div class="qty-ctrl">
                            <button type="button" class="qty-btn minus">−</button>
                            <input type="number" class="qty-input" id="quantity" name="quantity" value="1" min="1" max="<?php echo $available_stock; ?>">
                            <button type="button" class="qty-btn plus">+</button>
                        </div>
                    </div>
                    <div class="strip-item">
                        <div class="strip-label">التوصيل</div>
                        <div class="strip-val" id="deliveryPriceDisplay">—</div>
                    </div>
                    <div class="strip-item">
                        <div class="strip-label">المجموع</div>
                        <div class="strip-val total" id="orderTotalPrice"><?php echo number_format($default_price_for_display,2); ?> دج</div>
                    </div>
                </div>

                <input type="hidden" name="product_id" value="<?php echo $product_id; ?>">
                <input type="hidden" id="variantIdInput" name="variant_id" value="<?php echo $default_variant['id'] ?? ''; ?>">
                <input type="hidden" name="delivery_company_id" value="<?php echo $delivery_info['id'] ?? ''; ?>">
                <input type="hidden" id="deliveryPriceInput" name="delivery_price" value="0">

                <button type="submit" class="submit-btn" id="submitOrderBtn" <?php echo !$is_product_available?'disabled':''; ?>>
                    <i class="fas fa-check-circle"></i> تأكيد الطلب
                </button>
                <div class="submit-note">
                    <i class="fas fa-phone-alt"></i>
                    سنتصل بكم على الرقم المدخل لتأكيد الطلب وتفاصيل التوصيل 🌸
                </div>
            </form>
        </div>
    </div>

    <!-- Related -->
    <?php if(!empty($related_products)): ?>
    <div class="section-head">
        <h2>🌸 منتجات مشابهة <span class="line"></span></h2>
        <p>قد يعجبك أيضاً</p>
    </div>
    <div class="related-grid">
        <?php foreach($related_products as $rel):
            $ri = !empty($rel['image']) ? BASE_URL.'admin/'.$rel['image'] : '';
            $rp = $rel['discounted_price'] ?? $rel['price'];
            $ro = $rel['discounted_price'] ? $rel['price'] : null;
        ?>
        <a href="det.php?id=<?php echo $rel['id']; ?>" class="rel-card">
            <div class="rel-img">
                <?php if($ri): ?>
                    <img src="<?php echo $ri; ?>" alt="<?php echo htmlspecialchars($rel['name']); ?>">
                <?php else: ?>
                    <div style="width:100%;height:100%;display:flex;align-items:center;justify-content:center;background:var(--blush);font-size:36px;">💄</div>
                <?php endif; ?>
            </div>
            <div class="rel-body">
                <div class="rel-name"><?php echo htmlspecialchars($rel['name']); ?></div>
                <div>
                    <?php if($ro): ?><span class="rel-price-old"><?php echo number_format($ro,2); ?> دج</span><?php endif; ?>
                    <span class="rel-price"><?php echo number_format($rp,2); ?> دج</span>
                </div>
                <div class="rel-btn"><i class="fas fa-eye"></i> عرض المنتج</div>
            </div>
        </a>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>

</main>

<!-- Footer -->
<footer class="footer">
    <div class="container">
        <div class="footer-bottom">
            <i class="far fa-copyright"></i>
            جميع الحقوق محفوظة © <?php echo date('Y'); ?>
            <span>Riham Cosmetics</span> 🌸
        </div>
    </div>
</footer>

<!-- Mobile Nav -->
<nav class="mobile-nav">
    <ul>
        <a href="index.php" class="<?php echo basename($_SERVER['PHP_SELF'])=='index.php'?'active':''; ?>">
            <li><i class="fas fa-home"></i><span>الرئيسية</span></li>
        </a>
        <a href="track_order.php" class="<?php echo basename($_SERVER['PHP_SELF'])=='track_order.php'?'active':''; ?>">
            <li><i class="fas fa-box"></i><span>طلباتي</span></li>
        </a>
    </ul>
</nav>

<script>
const allImages = <?php echo json_encode($all_images); ?>;
let currentImageIndex = 0;

function changeMainImage(url, index) {
    const img = document.getElementById('mainImage');
    img.style.transition = 'opacity .15s';
    img.style.opacity = '0';
    setTimeout(() => { img.src = url; img.style.opacity = '1'; }, 150);
    currentImageIndex = index;
    document.querySelectorAll('.thumb').forEach(t => t.classList.remove('active'));
    const t = document.querySelectorAll('.thumb')[index];
    if(t){ t.classList.add('active'); t.scrollIntoView({behavior:'smooth',block:'nearest',inline:'center'}); }
}
function nextImage(){
    currentImageIndex = (currentImageIndex+1) % allImages.length;
    const url = '<?php echo BASE_URL; ?>admin/' + allImages[currentImageIndex].image_url;
    changeMainImage(url, currentImageIndex);
}
function prevImage(){
    currentImageIndex = (currentImageIndex - 1 + allImages.length) % allImages.length;
    const url = '<?php echo BASE_URL; ?>admin/' + allImages[currentImageIndex].image_url;
    changeMainImage(url, currentImageIndex);
}

// Scroll top
const scrollBtn = document.getElementById('scrollTop');
window.addEventListener('scroll', () => scrollBtn.classList.toggle('show', window.scrollY > 300));
scrollBtn.addEventListener('click', () => window.scrollTo({top:0,behavior:'smooth'}));

$(document).ready(function(){
    const productVariants      = <?php echo json_encode($product_variants); ?>;
    const deliveryPricesHome   = <?php echo json_encode($delivery_prices_home); ?>;
    const deliveryPricesOffice = <?php echo json_encode($delivery_prices_office); ?>;
    const communesData         = <?php echo json_encode($communes_data); ?>;
    const variantAttributesMap = <?php echo json_encode($variant_attributes); ?>;
    const hasVariants = <?php echo $has_variants ? 'true' : 'false'; ?>;
    const isAvailable = <?php echo $is_product_available ? 'true' : 'false'; ?>;

    let selectedAttributes = {};
    let currentVariant = <?php echo json_encode($default_variant); ?>;
    let defaultPrice = <?php echo (float)$default_price_for_display; ?>;

    const originalAllImages = <?php echo json_encode($all_images); ?>;

    /* Auto-select first values */
    if(hasVariants && isAvailable){
        Object.keys(variantAttributesMap).forEach(function(attr){
            const values = variantAttributesMap[attr];
            if(values && values.length > 0){
                selectedAttributes[attr] = values[0];
                $(`.v-chip[data-attribute="${attr}"][data-value="${values[0]}"]`).addClass('selected');
            }
        });
        findVariant(false);
        updateAttrsDisplay();
        refreshBlockStates();
        updateFabBtn();
    }

    /* Chip click */
    $(document).on('click', '.v-chip:not(.oos)', function(){
        const attr = $(this).data('attribute');
        const val  = $(this).data('value');
        $(`.v-chip[data-attribute="${attr}"]`).removeClass('selected');
        $(this).addClass('selected');
        selectedAttributes[attr] = val;
        findVariant(true);
        updateAttrsDisplay();
        refreshBlockStates();
        updateFabBtn();
        hideGlobalAlert();
    });

    /* Thumb click */
    $(document).on('click', '.thumb', function(){
        const vid = $(this).data('variant');
        if(vid){
            const v = productVariants.find(x => x.id == vid);
            if(v){
                v.variant_attrs.forEach(function(va){
                    selectedAttributes[va.attribute_name] = va.attribute_value;
                    $(`.v-chip[data-attribute="${va.attribute_name}"]`).removeClass('selected');
                    $(`.v-chip[data-attribute="${va.attribute_name}"][data-value="${va.attribute_value}"]`).addClass('selected');
                });
                currentVariant = v;
                updateVariantDetails(v);
                updateVariantImages(v.id);
                updateAttrsDisplay();
                refreshBlockStates();
                updateFabBtn();
            }
        }
    });

    function findVariant(updateImages){
        if(!Object.keys(selectedAttributes).length){ currentVariant=null; return; }
        const match = productVariants.find(v =>
            Object.keys(variantAttributesMap).every(attr =>
                v.variant_attrs.some(va =>
                    va.attribute_name===attr && va.attribute_value===selectedAttributes[attr]
                )
            ) && v.stock > 0
        );
        if(match){
            currentVariant = match;
            updateVariantDetails(match);
            if(updateImages !== false) updateVariantImages(match.id);
        } else { currentVariant = null; }
    }

    function updateVariantDetails(v){
        $('#variantPriceDisplay').text(Number(v.price).toFixed(2) + ' دج');
        $('#variantIdInput').val(v.id);
        $('#quantity').attr('max', v.stock);
        updateTotal();
    }

    function buildThumbsFromImages(images, activeIndex){
        $('#thumbsGallery').empty();
        images.forEach(function(img, i){
            if(!img.image_url) return;
            const url = '<?php echo BASE_URL; ?>admin/' + img.image_url;
            const isVariant = img.type === 'variant' ? `data-variant="${img.variant_id}"` : '';
            $('#thumbsGallery').append(
                `<div class="thumb ${i===activeIndex?'active':''}" data-index="${i}" ${isVariant}
                     onclick="changeMainImage('${url}',${i})">
                    <img src="${url}" alt="">
                </div>`
            );
        });
    }

    function updateVariantImages(vid){
        const v = productVariants.find(x => x.id == vid);
        let mergedImages = originalAllImages.slice();
        if(v && v.variant_images && v.variant_images.length){
            v.variant_images.forEach(function(vi){
                if(!mergedImages.some(m => m.image_url === vi.image_url)){
                    mergedImages.push({ type:'variant', variant_id:vid, image_url:vi.image_url, is_primary:vi.is_primary });
                }
            });
            const firstVariantUrl = '<?php echo BASE_URL; ?>admin/' + v.variant_images[0].image_url;
            const targetIndex = mergedImages.findIndex(m => m.image_url === v.variant_images[0].image_url);
            const showIndex = targetIndex >= 0 ? targetIndex : 0;
            buildThumbsFromImages(mergedImages, showIndex);
            changeMainImage(firstVariantUrl, showIndex);
            currentImageIndex = showIndex;
        } else {
            buildThumbsFromImages(mergedImages, 0);
            if(mergedImages.length > 0){
                changeMainImage('<?php echo BASE_URL; ?>admin/' + mergedImages[0].image_url, 0);
            }
            currentImageIndex = 0;
        }
    }

    function refreshBlockStates(){
        Object.keys(variantAttributesMap).forEach(function(attr){
            const blockId = 'vblock-' + attr.replace(/\s+/g,'_');
            const iconId  = 'sicon-' + attr.replace(/\s+/g,'_');
            const $block  = $('#' + blockId);
            const $icon   = $('#' + iconId);
            if(selectedAttributes[attr]){
                $block.addClass('completed').removeClass('needs-selection');
                $icon.html('<i class="fas fa-check"></i>');
            } else {
                $block.removeClass('completed').addClass('needs-selection');
                $icon.html('<i class="fas fa-question"></i>');
            }
        });
    }

    function updateFabBtn(){
        if(!hasVariants || !isAvailable) return;
        const $btn = $('#orderFabBtn');
        if(isAllSelected()){
            $btn.removeClass('state-select state-disabled').addClass('state-ready');
            $btn.html('<i class="fas fa-shopping-bag"></i> اطلبي الآن');
        } else {
            $btn.removeClass('state-ready state-disabled').addClass('state-select');
            const missing = getMissingAttrs();
            $btn.html(`<i class="fas fa-hand-pointer"></i> اختري ${missing[0]||''} أولاً`);
        }
    }

    function isAllSelected(){
        return Object.keys(variantAttributesMap).every(k => k in selectedAttributes && selectedAttributes[k]);
    }
    function getMissingAttrs(){
        return Object.keys(variantAttributesMap).filter(k => !(k in selectedAttributes) || !selectedAttributes[k]);
    }

    function showGlobalAlert(){
        const missing = getMissingAttrs();
        if(!missing.length) return;
        let html = '';
        missing.forEach(attr => { html += `<li><i class="fas fa-arrow-left"></i> ${attr}</li>`; });
        $('#missingAttrsList').html(html);
        $('#variantGlobalAlert').addClass('visible');
        missing.forEach(function(attr){
            const blockId = 'vblock-' + attr.replace(/\s+/g,'_');
            $('#' + blockId).addClass('needs-selection').removeClass('completed');
        });
        const firstMissing = missing[0];
        const blockId = 'vblock-' + firstMissing.replace(/\s+/g,'_');
        $('html,body').animate({scrollTop: $('#' + blockId).offset().top - 100}, 500);
    }
    function hideGlobalAlert(){ if(isAllSelected()) $('#variantGlobalAlert').removeClass('visible'); }

    function updateAttrsDisplay(){
        const allDone = isAllSelected();
        if(Object.keys(selectedAttributes).length){
            let html = '';
            for(const [k,v] of Object.entries(selectedAttributes)){
                if(v) html += `<span style="background:var(--rose);color:white;padding:3px 10px;border-radius:50px;font-size:12px;font-weight:700;">${k}: ${v}</span> `;
            }
            $('#formAttrsDisplay').html(html || '<i class="fas fa-mouse-pointer"></i> يرجى اختيار الخصائص من الأعلى');
            if(html) $('#formAttrsDisplay').css({'border-color':'var(--green)','background':'#f0fdf4','color':'var(--text-dark)'});
            else $('#formAttrsDisplay').css({'border-color':'var(--blush-deep)','background':'var(--blush)','color':'var(--text-light)'});
        }
        $('#selectedAttributesInput').val(JSON.stringify(selectedAttributes));
        if(allDone){
            let badgeHtml = '';
            for(const [k,v] of Object.entries(selectedAttributes)){
                badgeHtml += `<span class="badge-attr-tag">${k}: ${v}</span>`;
            }
            $('#badgeAttrsList').html(badgeHtml);
            $('#variantCompleteBadge').addClass('visible');
        } else { $('#variantCompleteBadge').removeClass('visible'); }
    }

    /* Communes */
    function loadCommunes(wilayaId){
        if(!wilayaId){ $('#communeRow').hide(); return; }
        const filtered = communesData.filter(c => parseInt(c.wilaya_code) === parseInt(wilayaId));
        filtered.sort((a,b) => (a.commune_name_ascii||'').localeCompare(b.commune_name_ascii||''));
        if(filtered.length){
            let opts = '<option value="">— اختري بلديتك —</option>';
            filtered.forEach(c => {
                const fr = c.commune_name_ascii || '';
                const ar = c.commune_name || '';
                const display = (fr && ar && fr!==ar) ? `${fr} / ${ar}` : (ar||fr);
                opts += `<option value="${c.id}">${display}</option>`;
            });
            $('#commune-select-form').html(opts);
            $('#communeRow').show();
        } else { $('#communeRow').hide(); }
    }

    /* Delivery */
    function updateDelivery(){
        const wid = $('#wilaya-select-form').val();
        const dtype = $('input[name="delivery_type"]:checked').val();
        if(!wid){ $('#deliveryPriceDisplay').text('—'); $('#deliveryPriceInput').val(0); updateTotal(); return; }
        const arr = dtype==='home' ? deliveryPricesHome : deliveryPricesOffice;
        const found = arr.find(x => x.wilaya_id == wid);
        if(found){ $('#deliveryPriceDisplay').text(parseFloat(found.price).toFixed(2)+' دج'); $('#deliveryPriceInput').val(found.price); }
        else { $('#deliveryPriceDisplay').text('غير متوفر'); $('#deliveryPriceInput').val(0); }
        updateTotal();
    }

    function updateTotal(){
        const qty = parseInt($('#quantity').val())||1;
        let price = defaultPrice;
        if(currentVariant) price = parseFloat(currentVariant.price);
        const del = parseFloat($('#deliveryPriceInput').val())||0;
        $('#orderTotalPrice').text(((price*qty)+del).toFixed(2)+' دج');
    }

    $('#wilaya-select-form').on('change', function(){ loadCommunes($(this).val()); updateDelivery(); });
    $('input[name="delivery_type"]').on('change', updateDelivery);
    $('.qty-btn.minus').on('click', function(){ let v=parseInt($('#quantity').val()); if(v>1){$('#quantity').val(v-1);updateTotal();} });
    $('.qty-btn.plus').on('click',  function(){ let v=parseInt($('#quantity').val()); const mx=parseInt($('#quantity').attr('max'))||100; if(v<mx){$('#quantity').val(v+1);updateTotal();} });
    $('#quantity').on('change', function(){ let v=parseInt($(this).val()); const mx=parseInt($(this).attr('max'))||100; if(isNaN(v)||v<1)v=1; if(v>mx)v=mx; $(this).val(v); updateTotal(); });

    /* FAB click */
    $('#orderFabBtn').on('click', function(){
        if(!isAvailable) return;
        if(hasVariants && !isAllSelected()){ showGlobalAlert(); return; }
        $('html,body').animate({scrollTop:$('#orderSection').offset().top - 20}, 700);
    });

    /* Go to select btn */
    $('#goToSelectBtn').on('click', function(){
        const missing = getMissingAttrs();
        if(missing.length){
            const blockId = 'vblock-' + missing[0].replace(/\s+/g,'_');
            $('html,body').animate({scrollTop: $('#' + blockId).offset().top - 100}, 500);
        }
    });

    /* FAB visibility */
    function handleFab(){
        const sTop = $(window).scrollTop();
        const secTop = $('#orderSection').offset().top;
        if(sTop + $(window).height() > secTop) $('#orderFab').removeClass('show');
        else $('#orderFab').addClass('show');
    }
    $(window).on('scroll resize', handleFab);
    setTimeout(handleFab, 300);

    /* Responsive nav */
    function handleNav(){
        if($(window).width()<=768){ $('.navbar').hide(); $('.mobile-nav').show(); }
        else { $('.navbar').show(); $('.mobile-nav').hide(); }
    }
    $(window).on('resize', handleNav);
    handleNav();

    /* Form submit */
    $('#orderForm').on('submit', function(e){
        if(hasVariants && !isAllSelected()){ e.preventDefault(); showGlobalAlert(); return false; }
        const name  = $('#customer_name').val().trim();
        const phone = $('#phone').val().trim();
        const wid   = $('#wilaya-select-form').val();
        if(!name){ e.preventDefault(); $('#customer_name').addClass('error').focus(); alert('يرجى إدخال الاسم الكامل'); return false; }
        if(!phone){ e.preventDefault(); $('#phone').addClass('error').focus(); alert('يرجى إدخال رقم الهاتف'); return false; }
        if(!/^\d+$/.test(phone)){ e.preventDefault(); alert('رقم الهاتف يجب أن يحتوي على أرقام فقط'); return false; }
        const phone2 = $('#phone2').val().trim();
        if(phone2 && !/^\d+$/.test(phone2)){ e.preventDefault(); alert('رقم الهاتف الإضافي يجب أن يحتوي على أرقام فقط'); return false; }
        if(!wid){ e.preventDefault(); alert('يرجى اختيار الولاية'); return false; }
        return true;
    });

    $('input, select').on('input change', function(){ $(this).removeClass('error'); });

    updateDelivery();
    updateTotal();
});
</script>
</body>
</html>