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

// هل السلة مفعّلة؟
$cart_enabled = !empty($store['cart_enabled']);

$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) { if ($a['is_primary'] == $b['is_primary']) return 0; return ($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 http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($product['name']); ?> - <?php echo htmlspecialchars($store['name']); ?></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 href="https://fonts.googleapis.com/css2?family=Cairo:wght@300;400;500;600;700;800;900&display=swap" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<style>
:root{
    --c-ink:       #0d1117;
    --c-surface:   #ffffff;
    --c-bg:        #f4f6f9;
    --c-border:    #e2e8f0;
    --c-muted:     #8492a6;
    --c-primary:   #1a56db;
    --c-primary-d: #1340aa;
    --c-primary-l: #eff4ff;
    --c-accent:    #f97316;
    --c-success:   #10b981;
    --c-danger:    #ef4444;
    --c-warn:      #f59e0b;
    --c-gold:      #d4a017;
    --radius-sm: 8px;
    --radius:    14px;
    --radius-lg: 22px;
    --radius-xl: 32px;
    --shadow-xs: 0 1px 3px rgba(0,0,0,.06);
    --shadow-sm: 0 2px 8px rgba(0,0,0,.08);
    --shadow:    0 4px 20px rgba(0,0,0,.10);
    --shadow-md: 0 8px 30px rgba(0,0,0,.12);
    --shadow-lg: 0 16px 50px rgba(0,0,0,.15);
    --transition: .25s cubic-bezier(.4,0,.2,1);
    --font-main: 'Cairo', sans-serif;
}
*,*::before,*::after{margin:0;padding:0;box-sizing:border-box;}
html{scroll-behavior:smooth;}
body{font-family:var(--font-main);background:var(--c-bg);color:var(--c-ink);line-height:1.65;-webkit-font-smoothing:antialiased;}
a{text-decoration:none;color:inherit;}
img{max-width:100%;display:block;}
button{font-family:var(--font-main);cursor:pointer;}
select,input,textarea{font-family:var(--font-main);}
.container{width:100%;max-width:1200px;margin:0 auto;padding:0 16px;}

/* ── Header ── */
.header-top{background:linear-gradient(135deg,#0d1b3e 0%,#1a3a6b 100%);padding:8px 0;font-size:13px;}
.header-top .container{display:flex;justify-content:flex-end;gap:20px;}
.header-top a{color:rgba(255,255,255,.85);display:flex;align-items:center;gap:6px;transition:var(--transition);}
.header-top a:hover{color:#fff;}
.header-top a i{color:#60a5fa;}
.header-main{background:#fff;padding:12px 0;box-shadow:var(--shadow-sm);position:sticky;top:0;z-index:900;border-bottom:2px solid var(--c-primary-l);}
.header-main .container{display:flex;align-items:center;gap:20px;}
.logo-wrap a{display:flex;align-items:center;gap:10px;}
.logo-image{height:48px;width:auto;object-fit:contain;}
.logo-text{font-size:20px;font-weight:800;color:var(--c-primary);}
.search-box{flex:1;max-width:480px;margin:0 auto;display:flex;background:var(--c-bg);border:2px solid var(--c-border);border-radius:50px;overflow:hidden;transition:var(--transition);}
.search-box:focus-within{border-color:var(--c-primary);background:#fff;box-shadow:0 0 0 4px rgba(26,86,219,.1);}
.search-box input{flex:1;padding:10px 18px;border:none;background:transparent;font-size:14px;outline:none;}
.search-box button{background:var(--c-primary);color:#fff;border:none;padding:0 20px;font-size:16px;transition:var(--transition);}
.search-box button:hover{background:var(--c-primary-d);}

/* ── Cart icon ── */
.cart-icon-wrap{position:relative;display:flex;align-items:center;justify-content:center;width:42px;height:42px;border-radius:50%;background:var(--c-primary-l);color:var(--c-primary);font-size:18px;transition:var(--transition);flex-shrink:0;}
.cart-icon-wrap:hover{background:var(--c-primary);color:#fff;}
.cart-badge{position:absolute;top:-4px;left:-4px;background:var(--c-danger);color:#fff;width:20px;height:20px;border-radius:50%;font-size:11px;font-weight:800;display:none;align-items:center;justify-content:center;border:2px solid #fff;}

/* ── Navbar ── */
.navbar{background:linear-gradient(90deg,var(--c-primary),var(--c-primary-d));box-shadow:0 2px 8px rgba(26,86,219,.3);}
.nav-list{display:flex;list-style:none;justify-content:center;padding:0;margin:0;}
.nav-item a{display:flex;align-items:center;gap:7px;color:#fff;padding:13px 22px;font-weight:600;font-size:14px;transition:var(--transition);position:relative;}
.nav-item a::after{content:'';position:absolute;bottom:0;right:50%;left:50%;height:3px;background:#fff;border-radius:3px 3px 0 0;transition:var(--transition);opacity:0;}
.nav-item a:hover::after{right:10px;left:10px;opacity:1;}
.nav-item a:hover{background:rgba(255,255,255,.12);}
.dropdown{position:absolute;top:calc(100% + 4px);right:0;background:#fff;min-width:220px;box-shadow:var(--shadow-md);border-radius:var(--radius);overflow:hidden;display:none;z-index:1001;border:1px solid var(--c-border);animation:dropIn .2s ease;}
@keyframes dropIn{from{opacity:0;transform:translateY(-8px);}to{opacity:1;transform:translateY(0);}}
.nav-item{position:relative;}
.nav-item:hover .dropdown{display:block;}
.dropdown a{color:#333;padding:11px 16px;display:flex;align-items:center;gap:8px;border-bottom:1px solid #f0f0f0;font-size:14px;transition:var(--transition);}
.dropdown a:last-child{border-bottom:none;}
.dropdown a:hover{background:var(--c-primary-l);color:var(--c-primary);padding-right:22px;}

/* ── Breadcrumb ── */
.breadcrumb{padding:14px 0;font-size:13px;color:var(--c-muted);display:flex;align-items:center;gap:6px;flex-wrap:wrap;}
.breadcrumb a{color:var(--c-primary);}

/* ── Trust bar ── */
.trust-bar{display:flex;align-items:center;justify-content:center;flex-wrap:wrap;gap:12px;padding:14px 20px;background:var(--c-bg);border:1px solid var(--c-border);border-radius:var(--radius);margin-bottom:8px;}
.trust-item{display:flex;align-items:center;gap:6px;font-size:12px;font-weight:700;color:#555;padding:6px 12px;background:#fff;border-radius:50px;border:1px solid var(--c-border);box-shadow:var(--shadow-xs);}
.trust-item i{font-size:15px;}
.trust-item.green i{color:var(--c-success);}
.trust-item.blue  i{color:var(--c-primary);}
.trust-item.orange i{color:var(--c-accent);}
.trust-item.gold  i{color:var(--c-gold);}

/* ── Product card ── */
.product-card{background:#fff;border-radius:var(--radius-lg);box-shadow:var(--shadow);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;}
.gallery-overlay{position:absolute;inset:0;background:rgba(13,17,23,.55);backdrop-filter:blur(3px);border-radius:var(--radius);display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;z-index:20;opacity:0;pointer-events:none;transition:var(--transition);}
.gallery-overlay.visible{opacity:1;pointer-events:all;}
.gallery-overlay i{font-size:38px;color:#fbbf24;}
.gallery-overlay p{color:#fff;font-size:15px;font-weight:700;text-align:center;padding:0 20px;}
.main-image-wrap{position:relative;overflow:hidden;border-radius:var(--radius);background:#f8fafc;border:1px solid var(--c-border);height:440px;display:flex;align-items:center;justify-content:center;cursor:zoom-in;}
.main-image-wrap img{max-width:100%;max-height:100%;width:auto;height:auto;object-fit:contain;transition:transform .35s ease;}
.main-image-wrap:hover img{transform:scale(1.45);}
.gallery-btn{position:absolute;top:50%;transform:translateY(-50%);width:40px;height:40px;background:rgba(255,255,255,.92);border:1px solid var(--c-border);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:15px;color:var(--c-ink);box-shadow:var(--shadow-sm);transition:var(--transition);z-index:5;}
.gallery-btn:hover{background:var(--c-primary);color:#fff;border-color:var(--c-primary);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(--c-primary) #eee;}
.thumbs::-webkit-scrollbar{height:5px;}
.thumbs::-webkit-scrollbar-track{background:#eee;border-radius:10px;}
.thumbs::-webkit-scrollbar-thumb{background:var(--c-primary);border-radius:10px;}
.thumb{width:76px;height:76px;flex-shrink:0;border-radius:var(--radius-sm);overflow:hidden;border:2.5px solid transparent;cursor:pointer;transition:var(--transition);background:#f8fafc;}
.thumb img{width:100%;height:100%;object-fit:cover;}
.thumb:hover{border-color:var(--c-primary);transform:scale(1.05);}
.thumb.active{border-color:var(--c-primary);box-shadow:0 0 0 3px rgba(26,86,219,.2);}
.thumb.variant-linked{position:relative;}
.thumb.variant-linked::after{content:'★';position:absolute;bottom:2px;right:2px;background:var(--c-accent);color:#fff;font-size:9px;padding:1px 3px;border-radius:3px;line-height:1.4;}
@media(max-width:480px){.main-image-wrap{height:280px;}.thumb{width:60px;height:60px;}}

/* ── Product info ── */
.product-info{display:flex;flex-direction:column;gap:18px;}
.product-badge{display:inline-flex;align-items:center;gap:6px;background:var(--c-primary-l);color:var(--c-primary);padding:4px 12px;border-radius:50px;font-size:12px;font-weight:700;width:fit-content;}
.product-title{font-size:24px;font-weight:800;color:var(--c-ink);line-height:1.35;}
@media(max-width:480px){.product-title{font-size:19px;}}
.product-desc-box{background:var(--c-bg);border-radius:var(--radius-sm);padding:14px 16px;border-right:4px solid var(--c-primary);font-size:14px;color:#444;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(--c-danger);margin-bottom:10px;display:block;}
.oos-box h3{color:#dc2626;margin-bottom:6px;}
.oos-box p{color:#666;font-size:14px;}

/* ── Variant blocks ── */
.variants-wrapper{display:flex;flex-direction:column;gap:14px;transition:var(--transition);}
.variants-wrapper.has-error .variant-block{border-color:var(--c-danger);box-shadow:0 0 0 3px rgba(239,68,68,.12);}
.variant-block{background:var(--c-bg);border-radius:var(--radius);padding:18px;border:2px solid var(--c-border);transition:var(--transition);position:relative;}
.variant-block.completed{border-color:var(--c-success);background:linear-gradient(135deg,#f0fdf4,#dcfce7);}
.variant-block.needs-selection{border-color:var(--c-warn);background:linear-gradient(135deg,#fffbeb,#fef3c7);animation:attentionPulse 1.5s ease-in-out 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(--c-muted);text-transform:uppercase;letter-spacing:.05em;margin-bottom:12px;display:flex;align-items:center;gap:6px;}
.variant-block h4 .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;transition:var(--transition);flex-shrink:0;}
.variant-block.completed h4 .status-icon{background:var(--c-success);color:#fff;}
.variant-block:not(.completed) h4 .status-icon{background:#fde68a;color:#92400e;}
.variant-values{display:flex;gap:8px;flex-wrap:wrap;}
.v-chip{padding:8px 16px;border:2px solid var(--c-border);border-radius:50px;cursor:pointer;font-size:13px;font-weight:600;color:#555;background:#fff;transition:var(--transition);position:relative;user-select:none;}
.v-chip:hover{border-color:var(--c-primary);color:var(--c-primary);}
.v-chip.selected{border-color:var(--c-primary);background:var(--c-primary);color:#fff;box-shadow:0 4px 12px rgba(26,86,219,.3);}
.v-chip.has-image{display:flex;align-items:center;gap:8px;padding:6px 14px 6px 8px;}
.v-chip.has-image .chip-thumb{width:28px;height:28px;border-radius:4px;object-fit:cover;border:1px solid rgba(0,0,0,.1);}
.v-chip.oos{opacity:.45;cursor:not-allowed;text-decoration:line-through;}
.variant-error-hint{display:none;margin-top:10px;padding:8px 12px;background:#fef3c7;border:1px solid #fbbf24;border-radius:8px;font-size:12px;font-weight:700;color:#92400e;align-items:center;gap:6px;}
.variant-error-hint i{font-size:14px;color:var(--c-warn);}
.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;}
.variant-global-alert .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:#fff;}
.variant-global-alert .alert-title{font-size:15px;font-weight:800;color:#9a3412;margin-bottom:4px;}
.variant-global-alert .alert-list{list-style:none;padding:0;margin:0;display:flex;flex-direction:column;gap:4px;}
.variant-global-alert .alert-list li{font-size:13px;color:#7c2d12;font-weight:600;display:flex;align-items:center;gap:6px;}
.variant-global-alert .alert-list li i{color:#fb923c;}
.variant-global-alert .alert-action{display:inline-flex;align-items:center;gap:6px;margin-top:10px;padding:7px 14px;background:#fb923c;color:#fff;border:none;border-radius:50px;font-size:13px;font-weight:700;cursor:pointer;font-family:var(--font-main);transition:var(--transition);}
.variant-global-alert .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;}
.variant-complete-badge .badge-icon{width:40px;height:40px;flex-shrink:0;background:var(--c-success);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:18px;color:#fff;}
.variant-complete-badge .badge-text{flex:1;}
.variant-complete-badge .badge-title{font-size:14px;font-weight:800;color:#166534;}
.variant-complete-badge .badge-attrs{display:flex;flex-wrap:wrap;gap:6px;margin-top:6px;}
.badge-attr-tag{background:var(--c-success);color:#fff;padding:3px 10px;border-radius:50px;font-size:12px;font-weight:700;}

/* ── Price box ── */
.price-box{background:linear-gradient(135deg,#eff4ff,#e0eaff);border:2px solid #bfdbfe;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(--c-primary);}
.price-right{display:flex;flex-direction:column;gap:4px;}
.price-old{font-size:18px;color:var(--c-muted);text-decoration:line-through;}
.price-badge{background:var(--c-danger);color:#fff;padding:3px 10px;border-radius:50px;font-size:12px;font-weight:700;width:fit-content;}
.price-note{font-size:12px;color:var(--c-muted);display:flex;align-items:center;gap:4px;}

/* ── Action buttons area ── */
.product-actions-area{display:flex;flex-direction:column;gap:10px;}

/* ── زر السلة ── */
.add-to-cart-btn{
    width:100%;padding:14px;
    background:linear-gradient(135deg,var(--c-success),#059669);
    color:#fff;border:none;border-radius:var(--radius);
    font-size:15px;font-weight:800;
    display:flex;align-items:center;justify-content:center;gap:10px;
    box-shadow:0 6px 20px rgba(16,185,129,.35);
    transition:var(--transition);
}
.add-to-cart-btn:hover{background:linear-gradient(135deg,#059669,#047857);transform:translateY(-2px);box-shadow:0 10px 28px rgba(16,185,129,.45);}
.add-to-cart-btn:disabled{background:#ccc;box-shadow:none;transform:none;cursor:not-allowed;}
.add-to-cart-btn.added{background:linear-gradient(135deg,#047857,#065f46);}

/* ── 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:#fff;border:none;padding:17px 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,#f59e0b,#d97706);box-shadow:0 8px 24px rgba(245,158,11,.45);animation:fabPulseWarn 2.5s ease infinite;}
.order-fab-btn.state-ready{background:linear-gradient(135deg,var(--c-primary),var(--c-primary-d));box-shadow:0 8px 24px rgba(26,86,219,.45);animation:fabPulse 2.5s ease infinite;}
.order-fab-btn.state-disabled{background:#ccc;box-shadow:none;animation:none;cursor:not-allowed;}
@keyframes fabPulse{0%,100%{box-shadow:0 8px 24px rgba(26,86,219,.45);}50%{box-shadow:0 12px 36px rgba(26,86,219,.65),0 0 0 8px rgba(26,86,219,.12);}}
@keyframes fabPulseWarn{0%,100%{box-shadow:0 8px 24px rgba(245,158,11,.45);}50%{box-shadow:0 12px 36px rgba(245,158,11,.65),0 0 0 8px rgba(245,158,11,.12);}}
.order-fab-btn:hover:not(.state-disabled){animation:none;transform:translateY(-2px);}

/* ── Order form ── */
.order-section{background:#fff;border-radius:var(--radius-lg);box-shadow:var(--shadow);overflow:hidden;margin-bottom:40px;transition:var(--transition);}
.order-title-bar{background:linear-gradient(135deg,var(--c-primary),var(--c-primary-d));padding:20px 28px;display:flex;align-items:center;gap:12px;color:#fff;}
.order-title-bar .icon-wrap{width:44px;height:44px;background:rgba(255,255,255,.2);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:20px;}
.order-title-bar h3{font-size:20px;font-weight:800;}
.order-title-bar p{font-size:13px;opacity:.85;}
.order-body{padding:24px 28px;position:relative;}
@media(max-width:600px){.order-body{padding:16px;}}
.fields-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px;}
.fields-grid.single{grid-template-columns:1fr;}
@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(--c-muted);text-transform:uppercase;letter-spacing:.04em;display:flex;align-items:center;gap:5px;}
.form-field label i{color:var(--c-primary);}
.field-input{padding:11px 14px;border:2px solid var(--c-border);border-radius:var(--radius-sm);font-size:14px;background:#fff;transition:var(--transition);outline:none;width:100%;}
.field-input:focus{border-color:var(--c-primary);box-shadow:0 0 0 3px rgba(26,86,219,.1);}
.field-input.error{border-color:var(--c-danger);}
.field-note{font-size:11px;color:var(--c-muted);margin-top:2px;}
.form-divider{display:flex;align-items:center;gap:10px;margin:18px 0;color:var(--c-muted);font-size:12px;font-weight:600;}
.form-divider::before,.form-divider::after{content:'';flex:1;height:1px;background:var(--c-border);}
.geo-row{display:grid;grid-template-columns:1fr;gap:14px;}
.commune-row{display:grid;grid-template-columns:1fr;gap:14px;}
.delivery-pills{display:flex;gap:10px;margin-top:4px;}
.del-pill{flex:1;display:flex;align-items:center;justify-content:center;gap:8px;padding:10px;border-radius:var(--radius-sm);border:2px solid var(--c-border);cursor:pointer;transition:var(--transition);background:#fff;font-size:13px;font-weight:600;color:#555;}
.del-pill input{display:none;}
.del-pill:has(input:checked){border-color:var(--c-primary);background:var(--c-primary-l);color:var(--c-primary);}
.del-pill i{font-size:18px;}
.order-strip{background:linear-gradient(135deg,#f0f9ff,#e0f2fe);border:1px solid #bae6fd;border-radius:var(--radius);padding:16px 20px;display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:12px;margin:18px 0;}
.strip-item{display:flex;flex-direction:column;gap:2px;align-items:center;}
.strip-label{font-size:11px;color:var(--c-muted);font-weight:600;text-transform:uppercase;}
.strip-val{font-size:20px;font-weight:800;color:var(--c-ink);}
.strip-val.total{color:var(--c-primary);font-size:24px;}
.qty-ctrl{display:flex;align-items:center;gap:8px;}
.qty-btn{width:34px;height:34px;border-radius:8px;border:2px solid var(--c-primary);background:#fff;color:var(--c-primary);font-size:18px;font-weight:700;display:flex;align-items:center;justify-content:center;transition:var(--transition);}
.qty-btn:hover{background:var(--c-primary);color:#fff;}
.qty-input{width:52px;height:34px;text-align:center;border:2px solid var(--c-border);border-radius:8px;font-size:16px;font-weight:700;outline:none;transition:var(--transition);}
.qty-input:focus{border-color:var(--c-primary);}
.submit-btn{width:100%;padding:16px;background:linear-gradient(135deg,var(--c-success),#059669);color:#fff;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(16,185,129,.35);transition:var(--transition);}
.submit-btn:hover:not(:disabled){background:linear-gradient(135deg,#059669,#047857);transform:translateY(-2px);box-shadow:0 10px 28px rgba(16,185,129,.45);}
.submit-btn:disabled{background:#ccc;box-shadow:none;transform: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;}

/* ── Toast notification ── */
.toast{
    position:fixed;bottom:90px;left:50%;transform:translateX(-50%) translateY(20px);
    padding:13px 24px;border-radius:50px;
    font-family:var(--font-main);font-weight:700;font-size:14px;
    color:#fff;z-index:9999;opacity:0;
    transition:opacity .3s, transform .3s;
    box-shadow:0 8px 24px rgba(0,0,0,.2);
    white-space:nowrap;pointer-events:none;
}
.toast.show{opacity:1;transform:translateX(-50%) translateY(0);}
.toast.success{background:#10b981;}
.toast.error{background:#ef4444;}

/* ── Related ── */
.section-head{text-align:center;margin:48px 0 28px;}
.section-head h2{font-size:26px;font-weight:800;color:var(--c-ink);display:inline-flex;align-items:center;gap:10px;}
.section-head h2 span{background:var(--c-primary-l);color:var(--c-primary);padding:2px 12px;border-radius:50px;font-size:14px;font-weight:700;}
.section-head p{color:var(--c-muted);font-size:14px;margin-top:6px;}
.related-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:20px;margin-bottom:48px;}
@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:#fff;border-radius:var(--radius);border:1px solid var(--c-border);overflow:hidden;transition:var(--transition);box-shadow:var(--shadow-xs);}
.rel-card:hover{transform:translateY(-6px);box-shadow:var(--shadow-md);border-color:var(--c-primary);}
.rel-img-wrap{height:180px;overflow:hidden;background:var(--c-bg);}
.rel-img-wrap img{width:100%;height:100%;object-fit:cover;transition:var(--transition);}
.rel-card:hover .rel-img-wrap img{transform:scale(1.06);}
.rel-body{padding:12px;}
.rel-name{font-size:14px;font-weight:700;color:var(--c-ink);height:40px;overflow:hidden;line-height:1.4;margin-bottom:8px;}
.rel-price{font-size:16px;font-weight:800;color:var(--c-primary);}
.rel-price-old{font-size:12px;color:var(--c-muted);text-decoration:line-through;margin-right:6px;}
.rel-btn{display:flex;align-items:center;justify-content:center;gap:6px;background:var(--c-primary-l);color:var(--c-primary);padding:8px;border-radius:8px;font-size:13px;font-weight:700;margin-top:10px;transition:var(--transition);border:1px solid #bfdbfe;}
.rel-btn:hover{background:var(--c-primary);color:#fff;}

/* ── Footer ── */
.footer{background:linear-gradient(135deg,#0d1b3e,#1a3a6b);color:#fff;padding:40px 0 20px;}
.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);}

/* ── Mobile nav ── */
.mobile-nav{display:none;position:fixed;bottom:0;right:0;left:0;background:#fff;box-shadow:0 -2px 12px rgba(0,0,0,.1);z-index:900;border-top:2px solid var(--c-primary-l);}
.mobile-nav ul{display:flex;list-style:none;padding:10px 0;margin:0;}
.mobile-nav a{flex:1;display:flex;flex-direction:column;align-items:center;gap:3px;color:#555;font-size:11px;font-weight:600;padding:4px 0;transition:var(--transition);position:relative;}
.mobile-nav a.active,.mobile-nav a:hover{color:var(--c-primary);}
.mobile-nav i{font-size:20px;}

@media(max-width:768px){
    .navbar{display:none;}
    .mobile-nav{display:block;}
    .order-fab{bottom:68px;}
    body{padding-bottom:70px;}
}
.hidden{display:none!important;}
</style>
</head>
<body>

<!-- Toast -->
<div class="toast" id="toastMsg"></div>

<!-- ═══ HEADER TOP ═══ -->
<div class="header-top">
    <div class="container">
        <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>
</div>

<!-- ═══ HEADER MAIN ═══ -->
<header>
    <div class="header-main">
        <div class="container">
            <div class="logo-wrap">
                <a href="index.php">
                    <?php if (!empty($store['logo'])): ?>
                        <img src="<?php echo BASE_URL.'admin/'.htmlspecialchars($store['logo']); ?>"
                             alt="<?php echo htmlspecialchars($store['name']); ?>" class="logo-image">
                    <?php else: ?>
                        <span class="logo-text"><?php echo htmlspecialchars($store['name']); ?></span>
                    <?php endif; ?>
                </a>
            </div>
            <form action="index.php" method="GET" class="search-box" id="searchForm">
                <input type="text" name="search" placeholder="ابحث عن منتجات...">
                <button type="submit"><i class="fas fa-search"></i></button>
            </form>
            <?php if ($cart_enabled): ?>
            <a href="cart.php" class="cart-icon-wrap" title="السلة">
                <i class="fas fa-shopping-cart"></i>
                <span class="cart-badge"></span>
            </a>
            <?php endif; ?>
        </div>
    </div>
    <nav class="navbar">
        <div class="container">
            <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>
                <?php if ($cart_enabled): ?>
                <li class="nav-item">
                    <a href="cart.php" style="position:relative;">
                        <i class="fas fa-shopping-cart"></i>السلة
                        <span class="cart-badge" style="position:absolute;top:6px;left:4px;border:2px solid transparent;"></span>
                    </a>
                </li>
                <?php endif; ?>
            </ul>
        </div>
    </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 green"><i class="fas fa-shield-alt"></i> دفع عند الاستلام</div>
        <div class="trust-item blue"><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="gallery-overlay" id="galleryOverlay">
                <i class="fas fa-hand-pointer"></i>
                <p>اختر الخصائص أدناه<br>لمشاهدة صورة المنتج</p>
            </div>
            <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 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':''; ?> <?php echo $img['type']==='variant'?'variant-linked':''; ?>"
                     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>

            <!-- Out of stock -->
            <?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 class="alert-body">
                    <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-sliders-h"></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 class="badge-text">
                    <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(--c-muted);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 class="price-right">
                    <?php if($product['discounted_price'] && $product['discounted_price'] < $product['price']): ?>
                    <div class="price-old" id="oldPriceDisplay"><?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>

            <!-- ── أزرار الإجراءات ── -->
            <div class="product-actions-area">
                <?php if($cart_enabled): ?>
                <button type="button" id="addToCartBtn" class="add-to-cart-btn" onclick="addToCartDet()">
                    <i class="fas fa-cart-plus"></i> أضف للسلة
                </button>
                <?php endif; ?>
            </div>
            <?php endif; ?>

        </div>
    </div>

    <!-- ═══ FIXED 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-bolt"></i> اطلب الآن
            <?php endif; ?>
        </button>
    </div>

    <!-- ═══ ORDER FORM ═══ -->
    <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(--c-bg);border:2px dashed var(--c-border);border-radius:var(--radius-sm);padding:12px 16px;font-size:14px;color:var(--c-muted);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(--c-primary);font-size:15px;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:40px;">
                        </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(--c-primary);font-size:15px;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:40px;">
                        </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(--c-muted);font-size:15px;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:40px;">
                        </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(--c-muted);font-size:15px;pointer-events:none;"><i class="fas fa-home"></i></span>
                            <input type="text" name="address" id="address" class="field-input" placeholder="الشارع، الحي..." style="padding-right:40px;">
                        </div>
                    </div>
                </div>

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

                <div class="geo-row">
                    <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(--c-primary);font-size:16px;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:40px;">
                                <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>

                <div class="commune-row" 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(--c-primary);font-size:16px;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:40px;">
                                <option value="">— اختر بلديتك —</option>
                            </select>
                        </div>
                        <div class="field-note"><i class="fas fa-info-circle"></i> حدد بلديتك لضبط العنوان بدقة</div>
                    </div>
                </div>

                <div style="margin-top:16px;">
                    <label style="font-size:12px;font-weight:700;color:var(--c-muted);text-transform:uppercase;letter-spacing:.04em;display:flex;align-items:center;gap:5px;margin-bottom:8px;">
                        <i class="fas fa-truck" style="color:var(--c-primary)"></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><i class="fas fa-th-large" style="font-size:20px"></i> منتجات مشابهة <span><?php echo count($related_products); ?></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-wrap">
                <?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(--c-bg)">
                        <i class="fas fa-image" style="font-size:36px;color:#ccc;"></i>
                    </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">
            <p><i class="far fa-copyright"></i> جميع الحقوق محفوظة © <?php echo date('Y'); ?> <?php echo htmlspecialchars($store['name']); ?></p>
        </div>
    </div>
</footer>

<!-- MOBILE NAV -->
<nav class="mobile-nav">
    <ul>
        <a href="index.php"><li><i class="fas fa-home"></i><span>الرئيسية</span></li></a>
        <a href="track_order.php"><li><i class="fas fa-box"></i><span>طلباتي</span></li></a>
        <?php if($cart_enabled): ?>
        <a href="cart.php" style="position:relative;">
            <li>
                <i class="fas fa-shopping-cart"></i>
                <span class="cart-badge" style="position:absolute;top:0;left:50%;margin-left:4px;border:2px solid #fff;"></span>
                <span>السلة</span>
            </li>
        </a>
        <?php endif; ?>
    </ul>
</nav>

<!-- ═══ CART JS ═══ -->
<?php if($cart_enabled): ?>
<script src="cart.js"></script>
<script>
function showToast(msg, type='success') {
    const t = document.getElementById('toastMsg');
    t.textContent = msg;
    t.className = 'toast ' + type;
    setTimeout(() => t.classList.add('show'), 10);
    setTimeout(() => t.classList.remove('show'), 2500);
}

function addToCartDet() {
    // التحقق من اختيار الخصائص
    if (typeof hasVariants !== 'undefined' && hasVariants) {
        const missing = Object.keys(variantAttributesMap).filter(k => !selectedAttributes[k]);
        if (missing.length) {
            showToast('يرجى اختيار ' + missing[0] + ' أولاً', 'error');
            // لفت الانتباه لأول بلوك ناقص
            const blockId = 'vblock-' + missing[0].replace(/\s+/g, '_');
            const block = document.getElementById(blockId);
            if (block) {
                block.classList.add('needs-selection');
                block.scrollIntoView({ behavior: 'smooth', block: 'center' });
            }
            return;
        }
    }

    const productId = <?php echo $product_id; ?>;
    const name      = <?php echo json_encode($product['name']); ?>;
    const priceText = document.getElementById('variantPriceDisplay').textContent.replace(/[^\d.]/g, '');
    const price     = parseFloat(priceText) || <?php echo (float)$default_price_for_display; ?>;
    const variantId = document.getElementById('variantIdInput')?.value || 0;
    const mainImg   = <?php echo json_encode($main_image_url); ?>;
    const attrs     = (typeof selectedAttributes !== 'undefined') ? selectedAttributes : {};

    Cart.add({
        id: productId,
        variant_id: variantId,
        name, price, image: mainImg,
        attributes: attrs,
        max_qty: <?php echo $available_stock; ?>
    });

    showToast('✓ تمت الإضافة للسلة', 'success');

    // تغيير الزر مؤقتاً
    const btn = document.getElementById('addToCartBtn');
    if (btn) {
        btn.innerHTML = '<i class="fas fa-check"></i> تمت الإضافة!';
        btn.classList.add('added');
        setTimeout(() => {
            btn.innerHTML = '<i class="fas fa-cart-plus"></i> أضف للسلة';
            btn.classList.remove('added');
        }, 2000);
    }
}
</script>
<?php endif; ?>

<!-- ═══ MAIN JS ═══ -->
<script>
const allImages = <?php echo json_encode($all_images); ?>;
let currentImageIndex = 0;

function changeMainImage(url, index) {
    const img = document.getElementById('mainImage');
    img.style.opacity = '0';
    setTimeout(() => { img.src = url; img.style.opacity = '1'; }, 150);
    img.style.transition = 'opacity .15s';
    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);
}

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

    /* Auto-select first value */
    if (hasVariants && isAvailable) {
        Object.keys(variantAttributesMap).forEach(attr => {
            const values = variantAttributesMap[attr];
            if (values && values.length > 0) {
                const firstVal = values[0];
                selectedAttributes[attr] = firstVal;
                $(`.v-chip[data-attribute="${attr}"][data-value="${firstVal}"]`).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(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();
            }
        }
    });

    /* Find variant */
    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();
    }

    const originalAllImages = <?php echo json_encode($all_images); ?>;
    function buildThumbsFromImages(images, activeIndex) {
        $('#thumbsGallery').empty();
        images.forEach((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}"` : '';
            const varCls    = img.type === 'variant' ? 'variant-linked' : '';
            $('#thumbsGallery').append(
                `<div class="thumb ${i === activeIndex ? 'active' : ''} ${varCls}" 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(vi => {
                const exists = mergedImages.some(m => m.image_url === vi.image_url);
                if (!exists) 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(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');
        const allDone = isAllSelected();
        if (allDone) {
            $btn.removeClass('state-select state-disabled').addClass('state-ready');
            $btn.html('<i class="fas fa-bolt"></i> اطلب الآن');
        } else {
            $btn.removeClass('state-ready state-disabled').addClass('state-select');
            const missing = getMissingAttrs();
            const first   = missing[0] || '';
            $btn.html(`<i class="fas fa-hand-pointer"></i> اختر ${first} أولاً`);
        }
    }

    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(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(--c-primary);color:#fff;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(--c-success)', 'background': '#f0fdf4', 'color': 'var(--c-ink)' });
            } else {
                $('#formAttrsDisplay').css({ 'border-color': 'var(--c-border)', 'background': 'var(--c-bg)', 'color': 'var(--c-muted)' });
            }
        }
        $('#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 price */
    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) + ' دج');
    }

    /* Events */
    $('#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 */
    $('#orderFabBtn').on('click', function () {
        if (!isAvailable) return;
        if (hasVariants && !isAllSelected()) { showGlobalAlert(); return; }
        $('html,body').animate({ scrollTop: $('#orderSection').offset().top - 20 }, 700);
    });

    $('#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, function () {
                $('#' + blockId).addClass('needs-selection');
                setTimeout(() => $('#' + blockId).css('transform', 'scale(1.02)'), 100);
                setTimeout(() => $('#' + blockId).css('transform', ''), 300);
            });
        } else { $('html,body').animate({ scrollTop: $('#variantsWrapper').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'); });

    /* Init */
    updateDelivery();
    updateTotal();

    // expose for cart
    window.hasVariants         = hasVariants;
    window.variantAttributesMap = variantAttributesMap;
    window.selectedAttributes  = selectedAttributes;
});
</script>
</body>
</html>