<?php

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

require_once __DIR__ . '/db.php';

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

// ─── هل السلة مفعّلة؟ ───────────────────────────────────────────
if (empty($store['cart_enabled'])) {
    header('Location: index.php');
    exit;
}

$categories = $pdo->query("SELECT id, name FROM categories ORDER BY name")->fetchAll();
?>
<!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($store['name']); ?></title>
<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;600;700;800;900&display=swap" rel="stylesheet">
<style>
:root{
    --primary:#1a56db;--primary-d:#1340aa;--primary-l:#eff4ff;
    --success:#10b981;--danger:#ef4444;--warn:#f59e0b;
    --ink:#0d1117;--bg:#f4f6f9;--surface:#fff;
    --border:#e2e8f0;--muted:#8492a6;
    --radius:14px;--radius-sm:8px;
    --shadow:0 4px 20px rgba(0,0,0,.08);
    --tr:.25s cubic-bezier(.4,0,.2,1);
    --font:'Cairo',sans-serif;
}
*,*::before,*::after{margin:0;padding:0;box-sizing:border-box;}
body{font-family:var(--font);background:var(--bg);color:var(--ink);line-height:1.65;padding-bottom:80px;}
a{text-decoration:none;color:inherit;}
img{max-width:100%;display:block;}
button{font-family:var(--font);cursor:pointer;}

/* ── Container ── */
.container{width:100%;max-width:1100px;margin:0 auto;padding:0 16px;}

/* ── Header ── */
.header-top{background:linear-gradient(135deg,#0d1b3e,#1a3a6b);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(--tr);}
.header-top a:hover{color:#fff;}
.header-top a i{color:#60a5fa;}

.header-main{background:#fff;padding:12px 0;box-shadow:0 2px 8px rgba(0,0,0,.08);
              position:sticky;top:0;z-index:900;border-bottom:2px solid var(--primary-l);}
.header-main .container{display:flex;align-items:center;gap:16px;}
.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(--primary);}

.search-box{flex:1;max-width:460px;margin:0 auto;display:flex;
            background:var(--bg);border:2px solid var(--border);
            border-radius:50px;overflow:hidden;transition:var(--tr);}
.search-box:focus-within{border-color:var(--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(--primary);color:#fff;border:none;padding:0 20px;font-size:16px;transition:var(--tr);}
.search-box button:hover{background:var(--primary-d);}

/* ── Cart icon in header ── */
.cart-icon-wrap{position:relative;display:flex;align-items:center;justify-content:center;
                width:42px;height:42px;border-radius:50%;background:var(--primary-l);
                color:var(--primary);font-size:18px;transition:var(--tr);flex-shrink:0;}
.cart-icon-wrap:hover{background:var(--primary);color:#fff;}
.cart-badge{position:absolute;top:-4px;left:-4px;
            background:var(--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(--primary),var(--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(--tr);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(--tr);opacity:0;}
.nav-item a:hover::after,.nav-item a.active::after{right:10px;left:10px;opacity:1;}
.nav-item a:hover,.nav-item a.active{background:rgba(255,255,255,.12);}
.dropdown{position:absolute;top:calc(100% + 4px);right:0;background:#fff;min-width:220px;
          box-shadow:0 8px 30px rgba(0,0,0,.12);border-radius:var(--radius);
          overflow:hidden;display:none;z-index:1001;border:1px solid var(--border);}
.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(--tr);}
.dropdown a:last-child{border-bottom:none;}
.dropdown a:hover{background:var(--primary-l);color:var(--primary);padding-right:22px;}

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

/* ── Page header ── */
.page-header{
    background:linear-gradient(135deg,var(--primary),var(--primary-d));
    color:#fff;border-radius:var(--radius);padding:28px 32px;
    display:flex;align-items:center;gap:16px;margin-bottom:28px;
}
.page-header .ph-icon{width:56px;height:56px;background:rgba(255,255,255,.2);
                       border-radius:50%;display:flex;align-items:center;justify-content:center;
                       font-size:24px;flex-shrink:0;}
.page-header h1{font-size:22px;font-weight:800;}
.page-header p{font-size:13px;opacity:.85;}

/* ── Empty state ── */
.empty-cart{
    text-align:center;padding:80px 20px;
    background:#fff;border-radius:var(--radius);box-shadow:var(--shadow);
}
.empty-cart i{font-size:72px;color:#d1d5db;margin-bottom:20px;display:block;}
.empty-cart h2{font-size:22px;font-weight:800;color:var(--ink);margin-bottom:8px;}
.empty-cart p{color:var(--muted);font-size:15px;margin-bottom:28px;}
.btn-primary{display:inline-flex;align-items:center;gap:8px;
             background:linear-gradient(135deg,var(--primary),var(--primary-d));
             color:#fff;padding:13px 28px;border-radius:50px;
             font-size:15px;font-weight:700;border:none;
             box-shadow:0 6px 18px rgba(26,86,219,.35);transition:var(--tr);}
.btn-primary:hover{transform:translateY(-2px);box-shadow:0 10px 26px rgba(26,86,219,.45);}

/* ── Layout ── */
.cart-layout{display:grid;grid-template-columns:1fr 360px;gap:24px;align-items:start;}
@media(max-width:900px){.cart-layout{grid-template-columns:1fr;}}

/* ── Cart items ── */
.cart-items-box{background:#fff;border-radius:var(--radius);box-shadow:var(--shadow);overflow:hidden;}
.cart-items-head{
    padding:18px 24px;border-bottom:2px solid var(--border);
    display:flex;align-items:center;justify-content:space-between;
}
.cart-items-head h2{font-size:16px;font-weight:800;display:flex;align-items:center;gap:8px;}
.clear-btn{background:none;border:1.5px solid #fca5a5;color:var(--danger);
           padding:6px 14px;border-radius:50px;font-size:12px;font-weight:700;
           display:flex;align-items:center;gap:6px;transition:var(--tr);}
.clear-btn:hover{background:#fef2f2;}

/* ── Cart item row ── */
.cart-item{
    display:grid;grid-template-columns:80px 1fr auto;gap:16px;
    align-items:center;padding:18px 24px;
    border-bottom:1px solid var(--border);
    transition:var(--tr);animation:fadeIn .3s ease;
}
.cart-item:last-child{border-bottom:none;}
.cart-item:hover{background:#fafbff;}
@keyframes fadeIn{from{opacity:0;transform:translateX(10px);}to{opacity:1;transform:translateX(0);}}

.ci-img{width:80px;height:80px;border-radius:var(--radius-sm);overflow:hidden;
        border:1px solid var(--border);background:var(--bg);flex-shrink:0;}
.ci-img img{width:100%;height:100%;object-fit:cover;}
.ci-img .no-img{width:100%;height:100%;display:flex;align-items:center;justify-content:center;
                font-size:24px;color:#ccc;}

.ci-info{display:flex;flex-direction:column;gap:5px;}
.ci-name{font-size:15px;font-weight:700;color:var(--ink);line-height:1.3;}
.ci-name a:hover{color:var(--primary);}
.ci-attrs{display:flex;flex-wrap:wrap;gap:5px;}
.ci-attr-tag{background:var(--primary-l);color:var(--primary);
             padding:2px 9px;border-radius:50px;font-size:11px;font-weight:700;}
.ci-price{font-size:16px;font-weight:800;color:var(--primary);}

.ci-actions{display:flex;flex-direction:column;align-items:flex-end;gap:10px;}
.qty-ctrl{display:flex;align-items:center;gap:6px;}
.qty-btn{width:30px;height:30px;border-radius:7px;
         border:2px solid var(--primary);background:#fff;color:var(--primary);
         font-size:16px;font-weight:700;display:flex;align-items:center;justify-content:center;
         transition:var(--tr);}
.qty-btn:hover{background:var(--primary);color:#fff;}
.qty-num{width:36px;height:30px;text-align:center;border:2px solid var(--border);
         border-radius:7px;font-size:14px;font-weight:700;outline:none;background:#fff;}
.remove-btn{background:none;border:none;color:#d1d5db;font-size:16px;
            transition:var(--tr);padding:4px;}
.remove-btn:hover{color:var(--danger);}
.ci-subtotal{font-size:13px;color:var(--muted);font-weight:600;white-space:nowrap;}

/* ── Summary ── */
.summary-box{
    background:#fff;border-radius:var(--radius);box-shadow:var(--shadow);
    overflow:hidden;position:sticky;top:80px;
}
.summary-head{
    background:linear-gradient(135deg,var(--primary),var(--primary-d));
    padding:18px 22px;color:#fff;
    display:flex;align-items:center;gap:10px;
}
.summary-head i{font-size:20px;}
.summary-head h3{font-size:16px;font-weight:800;}
.summary-body{padding:22px;}

.summary-row{
    display:flex;justify-content:space-between;align-items:center;
    padding:10px 0;border-bottom:1px solid var(--border);font-size:14px;
}
.summary-row:last-of-type{border-bottom:none;}
.summary-row .label{color:var(--muted);font-weight:600;}
.summary-row .val{font-weight:700;}
.summary-row.total .label{font-size:15px;font-weight:800;color:var(--ink);}
.summary-row.total .val{font-size:22px;font-weight:900;color:var(--primary);}

.checkout-btn{
    width:100%;padding:15px;margin-top:18px;
    background:linear-gradient(135deg,var(--success),#059669);
    color:#fff;border:none;border-radius:var(--radius-sm);
    font-size:16px;font-weight:800;
    display:flex;align-items:center;justify-content:center;gap:10px;
    box-shadow:0 6px 18px rgba(16,185,129,.3);transition:var(--tr);
}
.checkout-btn:hover{transform:translateY(-2px);box-shadow:0 10px 26px rgba(16,185,129,.4);}

.cont-shopping{
    display:flex;align-items:center;justify-content:center;gap:6px;
    width:100%;padding:11px;margin-top:10px;
    background:var(--primary-l);color:var(--primary);
    border:1.5px solid #bfdbfe;border-radius:var(--radius-sm);
    font-size:14px;font-weight:700;transition:var(--tr);
}
.cont-shopping:hover{background:var(--primary);color:#fff;}

.trust-row{
    display:flex;flex-wrap:wrap;gap:6px;margin-top:16px;
}
.trust-tag{display:flex;align-items:center;gap:5px;
           background:var(--bg);border:1px solid var(--border);
           border-radius:50px;padding:5px 10px;font-size:11px;font-weight:700;color:#555;}
.trust-tag i{font-size:13px;}
.trust-tag.green i{color:var(--success);}
.trust-tag.blue i{color:var(--primary);}

/* ── Checkout modal ── */
.modal-overlay{
    display:none;position:fixed;inset:0;
    background:rgba(0,0,0,.55);backdrop-filter:blur(4px);
    z-index:1000;align-items:center;justify-content:center;padding:16px;
}
.modal-overlay.open{display:flex;}
.modal{
    background:#fff;border-radius:var(--radius);
    width:100%;max-width:540px;max-height:90vh;overflow-y:auto;
    box-shadow:0 20px 60px rgba(0,0,0,.2);
    animation:slideUp .3s ease;
}
@keyframes slideUp{from{opacity:0;transform:translateY(30px);}to{opacity:1;transform:translateY(0);}}
.modal-head{
    background:linear-gradient(135deg,var(--primary),var(--primary-d));
    padding:20px 24px;color:#fff;
    display:flex;align-items:center;justify-content:space-between;
}
.modal-head h3{font-size:17px;font-weight:800;display:flex;align-items:center;gap:8px;}
.modal-close{background:none;border:none;color:rgba(255,255,255,.8);font-size:20px;
             transition:var(--tr);}
.modal-close:hover{color:#fff;}
.modal-body{padding:24px;}

/* ── Form inside modal ── */
.fields-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:12px;}
@media(max-width:500px){.fields-grid{grid-template-columns:1fr;}}
.form-field{display:flex;flex-direction:column;gap:4px;}
.form-field label{font-size:11px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:.04em;display:flex;align-items:center;gap:4px;}
.form-field label i{color:var(--primary);}
.field-input{padding:10px 12px;border:2px solid var(--border);border-radius:var(--radius-sm);
             font-size:14px;outline:none;transition:var(--tr);width:100%;font-family:var(--font);}
.field-input:focus{border-color:var(--primary);box-shadow:0 0 0 3px rgba(26,86,219,.1);}
.field-input.error{border-color:var(--danger);}

.del-pills{display:flex;gap:8px;margin-top:4px;}
.del-pill{flex:1;display:flex;align-items:center;justify-content:center;gap:7px;
          padding:10px;border-radius:var(--radius-sm);border:2px solid var(--border);
          cursor:pointer;font-size:13px;font-weight:600;color:#555;background:#fff;transition:var(--tr);}
.del-pill input{display:none;}
.del-pill:has(input:checked){border-color:var(--primary);background:var(--primary-l);color:var(--primary);}

.order-strip{
    background:#f0f9ff;border:1px solid #bae6fd;border-radius:var(--radius-sm);
    padding:14px;margin:16px 0;
    display:flex;justify-content:space-around;flex-wrap:wrap;gap:8px;
}
.strip-item{display:flex;flex-direction:column;align-items:center;gap:2px;}
.strip-label{font-size:10px;color:var(--muted);font-weight:700;text-transform:uppercase;}
.strip-val{font-size:18px;font-weight:800;}
.strip-val.total{color:var(--primary);font-size:22px;}

.modal-submit{
    width:100%;padding:14px;
    background:linear-gradient(135deg,var(--success),#059669);
    color:#fff;border:none;border-radius:var(--radius-sm);
    font-size:16px;font-weight:800;
    display:flex;align-items:center;justify-content:center;gap:8px;
    box-shadow:0 4px 14px rgba(16,185,129,.3);transition:var(--tr);
}
.modal-submit:hover{transform:translateY(-1px);}

/* ── Items summary inside modal ── */
.modal-items-list{margin-bottom:16px;}
.modal-item-row{display:flex;align-items:center;gap:10px;padding:8px 0;border-bottom:1px solid var(--border);}
.modal-item-row:last-child{border-bottom:none;}
.modal-item-img{width:44px;height:44px;border-radius:6px;overflow:hidden;border:1px solid var(--border);flex-shrink:0;}
.modal-item-img img{width:100%;height:100%;object-fit:cover;}
.modal-item-name{flex:1;font-size:13px;font-weight:700;color:var(--ink);}
.modal-item-qty{font-size:12px;color:var(--muted);}
.modal-item-price{font-size:14px;font-weight:800;color:var(--primary);}

/* ── 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(--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(--tr);}
.mobile-nav a.active,.mobile-nav a:hover{color:var(--primary);}
.mobile-nav i{font-size:20px;}
.mobile-nav .cart-icon-wrap{width:30px;height:30px;font-size:16px;background:none;}

/* ── Footer ── */
.footer{background:linear-gradient(135deg,#0d1b3e,#1a3a6b);color:#fff;padding:30px 0 16px;}
.footer-bottom{text-align:center;padding-top:16px;border-top:1px solid rgba(255,255,255,.1);font-size:13px;color:rgba(255,255,255,.6);}

@media(max-width:768px){
    .navbar{display:none;}
    .mobile-nav{display:block;}
    body{padding-bottom:80px;}
    .cart-item{grid-template-columns:64px 1fr;row-gap:10px;}
    .ci-actions{grid-column:1/-1;flex-direction:row;justify-content:space-between;align-items:center;}
}
@media(max-width:500px){
    .cart-item{grid-template-columns:56px 1fr;}
    .ci-img{width:56px;height:56px;}
}
</style>
</head>
<body>

<!-- ═══ 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">
                <input type="text" name="search" placeholder="ابحث عن منتجات...">
                <button type="submit"><i class="fas fa-search"></i></button>
            </form>
            <a href="cart.php" class="cart-icon-wrap" title="السلة">
                <i class="fas fa-shopping-cart"></i>
                <span class="cart-badge">0</span>
            </a>
        </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="cart.php" class="active"><i class="fas fa-shopping-cart"></i>السلة</a></li>
                <li class="nav-item">
                    <a href="#"><i class="fas fa-th-large"></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>
            </ul>
        </div>
    </nav>
</header>

<!-- ═══ MAIN ═══ -->
<main class="container" style="margin-top:24px;">

    <!-- Breadcrumb -->
    <div class="breadcrumb">
        <a href="index.php"><i class="fas fa-home"></i> الرئيسية</a>
        <i class="fas fa-chevron-left"></i>
        <span>سلة التسوق</span>
    </div>

    <!-- Page header -->
    <div class="page-header">
        <div class="ph-icon"><i class="fas fa-shopping-cart"></i></div>
        <div>
            <h1>سلة التسوق</h1>
            <p id="cartCountLabel">جارٍ التحميل...</p>
        </div>
    </div>

    <!-- Empty state -->
    <div class="empty-cart" id="emptyCartState" style="display:none;">
        <i class="fas fa-shopping-cart"></i>
        <h2>السلة فارغة</h2>
        <p>لم تقم بإضافة أي منتجات بعد. تصفّح متجرنا وأضف ما يعجبك!</p>
        <a href="index.php" class="btn-primary">
            <i class="fas fa-store"></i> تصفّح المنتجات
        </a>
    </div>

    <!-- Cart content -->
    <div class="cart-layout" id="cartContent" style="display:none;">

        <!-- Items -->
        <div class="cart-items-box">
            <div class="cart-items-head">
                <h2><i class="fas fa-list" style="color:var(--primary)"></i> المنتجات <span id="itemsCountBadge" style="background:var(--primary-l);color:var(--primary);padding:2px 10px;border-radius:50px;font-size:13px;"></span></h2>
                <button class="clear-btn" onclick="clearCartConfirm()">
                    <i class="fas fa-trash-alt"></i> إفراغ السلة
                </button>
            </div>
            <div id="cartItemsList"></div>
        </div>

        <!-- Summary -->
        <div class="summary-box">
            <div class="summary-head">
                <i class="fas fa-receipt"></i>
                <h3>ملخّص الطلب</h3>
            </div>
            <div class="summary-body">
                <div class="summary-row">
                    <span class="label">المنتجات</span>
                    <span class="val" id="summarySubtotal">0 دج</span>
                </div>
                <div class="summary-row">
                    <span class="label">التوصيل</span>
                    <span class="val" style="color:var(--muted);font-size:13px;">يُحسب عند التأكيد</span>
                </div>
                <div class="summary-row total">
                    <span class="label">المجموع</span>
                    <span class="val" id="summaryTotal">0 دج</span>
                </div>

                <button class="checkout-btn" onclick="openCheckout()">
                    <i class="fas fa-credit-card"></i> إتمام الطلب
                </button>
                <a href="index.php" class="cont-shopping">
                    <i class="fas fa-arrow-right"></i> مواصلة التسوق
                </a>

                <div class="trust-row">
                    <span class="trust-tag green"><i class="fas fa-shield-alt"></i> دفع عند الاستلام</span>
                    <span class="trust-tag blue"><i class="fas fa-truck"></i> توصيل لكل الولايات</span>
                </div>
            </div>
        </div>

    </div>
</main>

<!-- ═══ CHECKOUT MODAL ═══ -->
<div class="modal-overlay" id="checkoutModal">
    <div class="modal">
        <div class="modal-head">
            <h3><i class="fas fa-clipboard-check"></i> تأكيد الطلب</h3>
            <button class="modal-close" onclick="closeCheckout()"><i class="fas fa-times"></i></button>
        </div>
        <div class="modal-body">

            <!-- Items recap -->
            <div class="modal-items-list" id="modalItemsList"></div>

            <form id="checkoutForm" action="submit_order_cart.php" method="POST">
                <input type="hidden" name="cart_data" id="cartDataInput">

                <!-- Customer info -->
                <div class="fields-grid">
                    <div class="form-field">
                        <label><i class="fas fa-user"></i> الاسم الكامل *</label>
                        <input type="text" name="customer_name" id="co_name" class="field-input" placeholder="اسمك الكامل" required>
                    </div>
                    <div class="form-field">
                        <label><i class="fas fa-phone"></i> الهاتف *</label>
                        <input type="tel" name="phone" id="co_phone" class="field-input" placeholder="0XXXXXXXXX" required>
                    </div>
                </div>
                <div class="fields-grid">
                    <div class="form-field">
                        <label><i class="fas fa-phone-volume"></i> هاتف إضافي</label>
                        <input type="tel" name="phone2" id="co_phone2" class="field-input" placeholder="اختياري">
                    </div>
                    <div class="form-field">
                        <label><i class="fas fa-home"></i> العنوان</label>
                        <input type="text" name="address" id="co_address" class="field-input" placeholder="الشارع، الحي...">
                    </div>
                </div>

                <!-- Wilaya & Commune -->
                <div class="form-field" style="margin-bottom:12px;">
                    <label><i class="fas fa-city"></i> الولاية *</label>
                    <select name="wilaya_id" id="co_wilaya" class="field-input" required>
                        <option value="">— اختر ولايتك —</option>
                        <?php
                        $wilayas_all = $pdo->query("SELECT id, name FROM wilayas ORDER BY id ASC")->fetchAll();
                        foreach($wilayas_all as $w):
                            $id_pad = str_pad($w['id'],2,'0',STR_PAD_LEFT);
                        ?>
                        <option value="<?php echo $w['id']; ?>"><?php echo $id_pad.' - '.$w['name']; ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-field" id="co_communeRow" style="margin-bottom:12px;display:none;">
                    <label><i class="fas fa-location-arrow"></i> البلدية</label>
                    <select name="commune_id" id="co_commune" class="field-input">
                        <option value="">— اختر بلديتك —</option>
                    </select>
                </div>

                <!-- Delivery type -->
                <div class="form-field" style="margin-bottom:14px;">
                    <label><i class="fas fa-truck"></i> نوع التوصيل</label>
                    <div class="del-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>

                <!-- Strip -->
                <div class="order-strip">
                    <div class="strip-item">
                        <div class="strip-label">المنتجات</div>
                        <div class="strip-val" id="modalSubtotal">0 دج</div>
                    </div>
                    <div class="strip-item">
                        <div class="strip-label">التوصيل</div>
                        <div class="strip-val" id="modalDelivery">—</div>
                    </div>
                    <div class="strip-item">
                        <div class="strip-label">المجموع</div>
                        <div class="strip-val total" id="modalTotal">0 دج</div>
                    </div>
                </div>

                <input type="hidden" name="delivery_price" id="co_deliveryPrice" value="0">

                <button type="submit" class="modal-submit">
                    <i class="fas fa-check-circle"></i> تأكيد الطلب الآن
                </button>
                <p style="text-align:center;font-size:12px;color:var(--muted);margin-top:10px;">
                    <i class="fas fa-phone-alt"></i>
                    سنتصل بكم لتأكيد الطلب وتفاصيل التوصيل
                </p>
            </form>
        </div>
    </div>
</div>

<!-- ═══ 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>
        <a href="cart.php" class="active">
            <li>
                <span class="cart-icon-wrap" style="position:relative;">
                    <i class="fas fa-shopping-cart"></i>
                    <span class="cart-badge"></span>
                </span>
                <span>السلة</span>
            </li>
        </a>
    </ul>
</nav>

<!-- ═══ SCRIPTS ═══ -->
<script>
/* ── بيانات من PHP ── */
const BASE_URL    = '<?php echo BASE_URL; ?>';
const communesRaw = <?php
    $cities_file = __DIR__ . '/cities.json';
    echo file_exists($cities_file) ? file_get_contents($cities_file) : '[]';
?>;

/* ══════════════════════════════════════════
   CART CORE (نفس cart.js لكن مضمّن هنا)
══════════════════════════════════════════ */
const Cart = (function(){
    const KEY = 'medshop_cart';
    function getAll(){try{return JSON.parse(localStorage.getItem(KEY))||[];}catch{return[];}}
    function save(items){localStorage.setItem(KEY,JSON.stringify(items));updateBadge();}
    function count(){return getAll().reduce((s,i)=>s+i.qty,0);}
    function updateBadge(){
        const n=count();
        document.querySelectorAll('.cart-badge').forEach(el=>{
            el.textContent=n; el.style.display=n>0?'flex':'none';
        });
    }
    function remove(key){save(getAll().filter(i=>i._key!==key));}
    function updateQty(key,qty){
        const items=getAll();
        const idx=items.findIndex(i=>i._key===key);
        if(idx>=0){if(qty<=0)items.splice(idx,1);else items[idx].qty=qty;save(items);}
    }
    function clear(){save([]);}
    function subtotal(){return getAll().reduce((s,i)=>s+i.price*i.qty,0);}
    document.addEventListener('DOMContentLoaded',updateBadge);
    return{getAll,remove,updateQty,clear,subtotal,updateBadge,count};
})();

/* ══════════════════════════════════════════
   RENDER CART
══════════════════════════════════════════ */
function fmt(n){return parseFloat(n).toLocaleString('ar-DZ',{minimumFractionDigits:2});}

function renderCart(){
    const items = Cart.getAll();
    const $list  = document.getElementById('cartItemsList');
    const $empty = document.getElementById('emptyCartState');
    const $cont  = document.getElementById('cartContent');
    const $label = document.getElementById('cartCountLabel');
    const $badge = document.getElementById('itemsCountBadge');

    if(!items.length){
        $empty.style.display='';
        $cont.style.display='none';
        $label.textContent='السلة فارغة';
        $badge.textContent='0';
        return;
    }

    $empty.style.display='none';
    $cont.style.display='grid';
    const totalQty = items.reduce((s,i)=>s+i.qty,0);
    $label.textContent = totalQty + ' منتج في السلة';
    $badge.textContent = items.length;

    $list.innerHTML = items.map(item=>{
        const imgUrl = item.image ? BASE_URL+'admin/'+item.image : '';
        const attrsHtml = item.attributes ? Object.entries(item.attributes).map(([k,v])=>
            `<span class="ci-attr-tag">${k}: ${v}</span>`).join('') : '';
        const subtotal = (item.price * item.qty).toFixed(2);
        return `
        <div class="cart-item" id="item-${CSS.escape(item._key)}">
            <div class="ci-img">
                ${imgUrl
                    ? `<img src="${imgUrl}" alt="${item.name}" onerror="this.parentElement.innerHTML='<div class=no-img><i class=fas fa-image></i></div>'">`
                    : `<div class="no-img"><i class="fas fa-image"></i></div>`}
            </div>
            <div class="ci-info">
                <div class="ci-name"><a href="det.php?id=${item.id}">${item.name}</a></div>
                ${attrsHtml ? `<div class="ci-attrs">${attrsHtml}</div>` : ''}
                <div class="ci-price">${fmt(item.price)} دج</div>
            </div>
            <div class="ci-actions">
                <div style="display:flex;align-items:center;gap:8px;">
                    <div class="qty-ctrl">
                        <button class="qty-btn" onclick="changeQty('${item._key}',-1)">−</button>
                        <input class="qty-num" type="number" value="${item.qty}" min="1"
                               onchange="setQty('${item._key}',this.value)" style="width:40px;">
                        <button class="qty-btn" onclick="changeQty('${item._key}',1)">+</button>
                    </div>
                    <button class="remove-btn" onclick="removeItem('${item._key}')" title="حذف">
                        <i class="fas fa-trash-alt"></i>
                    </button>
                </div>
                <div class="ci-subtotal">الإجمالي: ${fmt(subtotal)} دج</div>
            </div>
        </div>`;
    }).join('');

    const sub = Cart.subtotal();
    document.getElementById('summarySubtotal').textContent = fmt(sub)+' دج';
    document.getElementById('summaryTotal').textContent     = fmt(sub)+' دج';
}

function changeQty(key, delta){
    const items = Cart.getAll();
    const item = items.find(i=>i._key===key);
    if(item){ Cart.updateQty(key, Math.max(1, item.qty+delta)); renderCart(); }
}
function setQty(key, val){
    const n=parseInt(val)||1;
    Cart.updateQty(key, Math.max(1,n));
    renderCart();
}
function removeItem(key){
    Cart.remove(key);
    renderCart();
    updateModalItems();
}
function clearCartConfirm(){
    if(confirm('هل تريد إفراغ السلة بالكامل؟')){ Cart.clear(); renderCart(); }
}

/* ══════════════════════════════════════════
   CHECKOUT MODAL
══════════════════════════════════════════ */
function openCheckout(){
    if(!Cart.count()){ alert('السلة فارغة!'); return; }
    updateModalItems();
    updateModalTotals();
    document.getElementById('checkoutModal').classList.add('open');
    document.body.style.overflow='hidden';
}
function closeCheckout(){
    document.getElementById('checkoutModal').classList.remove('open');
    document.body.style.overflow='';
}
document.getElementById('checkoutModal').addEventListener('click',function(e){
    if(e.target===this) closeCheckout();
});

function updateModalItems(){
    const items = Cart.getAll();
    document.getElementById('modalItemsList').innerHTML = items.map(item=>{
        const imgUrl = item.image ? BASE_URL+'admin/'+item.image : '';
        return `
        <div class="modal-item-row">
            <div class="modal-item-img">
                ${imgUrl ? `<img src="${imgUrl}" alt="">` : '<div style="width:100%;height:100%;background:#eee;display:flex;align-items:center;justify-content:center"><i class="fas fa-image" style="color:#ccc"></i></div>'}
            </div>
            <div class="modal-item-name">${item.name}
                ${item.attributes?'<br><small style="color:#888;font-weight:normal">'+Object.entries(item.attributes).map(([k,v])=>k+': '+v).join(' | ')+'</small>':''}
            </div>
            <div class="modal-item-qty">× ${item.qty}</div>
            <div class="modal-item-price">${fmt(item.price*item.qty)} دج</div>
        </div>`;
    }).join('');
    document.getElementById('cartDataInput').value = JSON.stringify(items);
}

/* ══════════════════════════════════════════
   DELIVERY PRICES (modal)
══════════════════════════════════════════ */
// نجلب أسعار التوصيل ديناميكياً حسب الولاية المختارة
async function fetchDeliveryPrice(wilayaId, type){
    try{
        const res = await fetch(`get_delivery_price.php?wilaya_id=${wilayaId}&type=${type}`);
        const data = await res.json();
        return data.price || null;
    }catch{ return null; }
}

async function updateModalTotals(){
    const sub  = Cart.subtotal();
    const wid  = document.getElementById('co_wilaya').value;
    const type = document.querySelector('input[name="delivery_type"]:checked')?.value||'home';

    document.getElementById('modalSubtotal').textContent = fmt(sub)+' دج';

    if(wid){
        const del = await fetchDeliveryPrice(wid, type);
        if(del!==null){
            document.getElementById('modalDelivery').textContent = fmt(del)+' دج';
            document.getElementById('co_deliveryPrice').value    = del;
            document.getElementById('modalTotal').textContent    = fmt(sub+parseFloat(del))+' دج';
        } else {
            document.getElementById('modalDelivery').textContent='غير متوفر';
            document.getElementById('co_deliveryPrice').value=0;
            document.getElementById('modalTotal').textContent=fmt(sub)+' دج';
        }
    } else {
        document.getElementById('modalDelivery').textContent='—';
        document.getElementById('co_deliveryPrice').value=0;
        document.getElementById('modalTotal').textContent=fmt(sub)+' دج';
    }
}

/* ── Communes ── */
document.getElementById('co_wilaya').addEventListener('change',function(){
    const wid = parseInt(this.value);
    const filtered = communesRaw.filter(c=>parseInt(c.wilaya_code)===wid);
    filtered.sort((a,b)=>(a.commune_name_ascii||'').localeCompare(b.commune_name_ascii||''));
    const row = document.getElementById('co_communeRow');
    if(filtered.length){
        let opts = '<option value="">— اختر بلديتك —</option>';
        filtered.forEach(c=>{
            const fr=c.commune_name_ascii||'', ar=c.commune_name||'';
            const display=(fr&&ar&&fr!==ar)?fr+' / '+ar:(ar||fr);
            opts += `<option value="${c.id}">${display}</option>`;
        });
        document.getElementById('co_commune').innerHTML=opts;
        row.style.display='';
    } else { row.style.display='none'; }
    updateModalTotals();
});

document.querySelectorAll('input[name="delivery_type"]').forEach(r=>
    r.addEventListener('change', updateModalTotals)
);

/* ── Form validation ── */
document.getElementById('checkoutForm').addEventListener('submit',function(e){
    const name=document.getElementById('co_name').value.trim();
    const phone=document.getElementById('co_phone').value.trim();
    const wid=document.getElementById('co_wilaya').value;
    if(!name){e.preventDefault();document.getElementById('co_name').classList.add('error');alert('يرجى إدخال الاسم');return;}
    if(!phone){e.preventDefault();document.getElementById('co_phone').classList.add('error');alert('يرجى إدخال رقم الهاتف');return;}
    if(!/^\d+$/.test(phone)){e.preventDefault();alert('رقم الهاتف يجب أن يحتوي أرقاماً فقط');return;}
    if(!wid){e.preventDefault();alert('يرجى اختيار الولاية');return;}
    document.getElementById('cartDataInput').value=JSON.stringify(Cart.getAll());
});

/* ── Init ── */
document.addEventListener('DOMContentLoaded', renderCart);

/* ── Responsive nav ── */
(function(){
    function h(){ if(window.innerWidth<=768){document.querySelector('.navbar').style.display='none';document.querySelector('.mobile-nav').style.display='block';}else{document.querySelector('.navbar').style.display='';document.querySelector('.mobile-nav').style.display='none';} }
    window.addEventListener('resize',h); h();
})();
</script>
</body>
</html>