<?php
// ═══════════════════════════════════════════════════════════════
//  ملاحظة: أضف هذا الكود في orders.php
//  1. الجزء PHP يُوضع في بداية الملف (قبل HTML)
//  2. الجزء HTML يُوضع قبل </body>
//  3. الجزء CSS يُوضع داخل <style>
//  4. الجزء JS يُوضع داخل <script>
// ═══════════════════════════════════════════════════════════════

// ════════════════════════════════════════════
//  PHP — أضفه في بداية orders.php مع باقي POST handlers
// ════════════════════════════════════════════

/*

// ===== إنشاء جدول الاستبدالات تلقائياً =====
$pdo->exec("
CREATE TABLE IF NOT EXISTS `order_replacements` (
  `id`                    INT(11) NOT NULL AUTO_INCREMENT,
  `order_id`              INT(11) NOT NULL,
  `original_item_id`      INT(11) NOT NULL,
  `original_product_name` VARCHAR(255) NOT NULL,
  `original_variant_id`   INT(11) DEFAULT NULL,
  `original_attributes`   TEXT DEFAULT NULL,
  `original_quantity`     INT(11) NOT NULL DEFAULT 1,
  `original_unit_price`   DECIMAL(10,2) NOT NULL,
  `new_product_name`      VARCHAR(255) NOT NULL,
  `new_variant_id`        INT(11) DEFAULT NULL,
  `new_attributes`        TEXT DEFAULT NULL,
  `new_quantity`          INT(11) NOT NULL DEFAULT 1,
  `new_unit_price`        DECIMAL(10,2) NOT NULL,
  `status`                ENUM('pending','sent','received') NOT NULL DEFAULT 'pending',
  `notes`                 TEXT DEFAULT NULL,
  `created_at`            DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at`            DATETIME DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `order_id` (`order_id`),
  KEY `original_item_id` (`original_item_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
");

// ===== معالجة إضافة استبدال =====
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_replacement'])) {
    $orderId           = (int)($_POST['order_id'] ?? 0);
    $originalItemId    = (int)($_POST['original_item_id'] ?? 0);
    $origName          = $_POST['original_product_name'] ?? '';
    $origVariantId     = !empty($_POST['original_variant_id']) ? (int)$_POST['original_variant_id'] : null;
    $origAttrs         = $_POST['original_attributes'] ?? '[]';
    $origQty           = (int)($_POST['original_quantity'] ?? 1);
    $origPrice         = floatval($_POST['original_unit_price'] ?? 0);
    $newName           = $_POST['new_product_name'] ?? '';
    $newVariantId      = !empty($_POST['new_variant_id']) ? (int)$_POST['new_variant_id'] : null;
    $newAttrs          = $_POST['new_attributes'] ?? '[]';
    $newQty            = (int)($_POST['new_quantity'] ?? 1);
    $newPrice          = floatval($_POST['new_unit_price'] ?? 0);
    $notes             = $_POST['notes'] ?? '';

    if ($orderId && $originalItemId && $newName) {
        try {
            $pdo->prepare("
                INSERT INTO order_replacements
                (order_id, original_item_id, original_product_name, original_variant_id,
                 original_attributes, original_quantity, original_unit_price,
                 new_product_name, new_variant_id, new_attributes,
                 new_quantity, new_unit_price, status, notes)
                VALUES (?,?,?,?,?,?,?,?,?,?,?,?,'pending',?)
            ")->execute([
                $orderId, $originalItemId, $origName, $origVariantId,
                $origAttrs, $origQty, $origPrice,
                $newName, $newVariantId, $newAttrs,
                $newQty, $newPrice, $notes
            ]);
            $_SESSION['message'] = "✅ تم تسجيل الاستبدال بنجاح";
        } catch (Exception $e) {
            $_SESSION['error'] = "خطأ: " . $e->getMessage();
        }
    }
    $redirectUrl = "orders.php?filter=" . urlencode($_GET['filter'] ?? 'all');
    header("Location: $redirectUrl");
    exit();
}

// ===== تغيير حالة الاستبدال =====
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_replacement_status'])) {
    $replacementId = (int)($_POST['replacement_id'] ?? 0);
    $newStatus     = $_POST['replacement_status'] ?? '';
    $allowed       = ['pending', 'sent', 'received'];
    if ($replacementId && in_array($newStatus, $allowed)) {
        try {
            $pdo->prepare("UPDATE order_replacements SET status=? WHERE id=?")
                ->execute([$newStatus, $replacementId]);
            $_SESSION['message'] = "✅ تم تحديث حالة الاستبدال";
        } catch (Exception $e) {
            $_SESSION['error'] = "خطأ: " . $e->getMessage();
        }
    }
    $redirectUrl = "orders.php?filter=" . urlencode($_GET['filter'] ?? 'all');
    header("Location: $redirectUrl");
    exit();
}

// ===== حذف استبدال =====
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_replacement'])) {
    $replacementId = (int)($_POST['replacement_id'] ?? 0);
    if ($replacementId) {
        try {
            $pdo->prepare("DELETE FROM order_replacements WHERE id=?")->execute([$replacementId]);
            $_SESSION['message'] = "🗑️ تم حذف سجل الاستبدال";
        } catch (Exception $e) {
            $_SESSION['error'] = "خطأ: " . $e->getMessage();
        }
    }
    $redirectUrl = "orders.php?filter=" . urlencode($_GET['filter'] ?? 'all');
    header("Location: $redirectUrl");
    exit();
}

*/

// ===== جلب الاستبدالات لكل طلب — أضف هذا بعد جلب الطلبات =====
/*
$orderReplacements = [];
if (!empty($orders)) {
    $orderIds = array_column($orders, 'id');
    $inPlaceholders = implode(',', array_fill(0, count($orderIds), '?'));
    $replStmt = $pdo->prepare("SELECT * FROM order_replacements WHERE order_id IN ($inPlaceholders) ORDER BY created_at DESC");
    $replStmt->execute($orderIds);
    foreach ($replStmt->fetchAll() as $repl) {
        $orderReplacements[$repl['order_id']][] = $repl;
    }
}
*/

?>

<!-- ════════════════════════════════════════════════════════════
     CSS — أضفه داخل <style> في orders.php
════════════════════════════════════════════════════════════ -->
<style id="replacement-css-placeholder">
/* ===== REPLACEMENT MODAL ===== */
.repl-modal {
    display: none;
    position: fixed;
    z-index: 3000;
    inset: 0;
    background: rgba(15, 23, 42, 0.65);
    align-items: center;
    justify-content: center;
    backdrop-filter: blur(6px);
    padding: 16px;
}
.repl-modal.open { display: flex; }

.repl-box {
    background: white;
    border-radius: 20px;
    width: 100%;
    max-width: 700px;
    max-height: 92vh;
    overflow-y: auto;
    box-shadow: 0 30px 80px rgba(0,0,0,0.22);
    animation: replIn 0.35s cubic-bezier(0.34,1.56,0.64,1);
}
@keyframes replIn {
    from { opacity: 0; transform: scale(0.87) translateY(24px); }
    to   { opacity: 1; transform: scale(1)    translateY(0);     }
}

.repl-header {
    padding: 22px 24px 16px;
    background: linear-gradient(135deg, #7C3AED 0%, #4F46E5 100%);
    color: white;
    border-radius: 20px 20px 0 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.repl-header h2 {
    font-size: 18px;
    font-weight: 900;
    display: flex;
    align-items: center;
    gap: 10px;
    color: white;
}
.repl-header-close {
    width: 32px; height: 32px;
    background: rgba(255,255,255,0.15);
    border: none; border-radius: 50%;
    color: white; font-size: 20px;
    cursor: pointer; display: flex;
    align-items: center; justify-content: center;
    transition: all 0.2s;
}
.repl-header-close:hover { background: rgba(255,255,255,0.3); transform: scale(1.1); }

.repl-body { padding: 22px 24px; }

/* Items list in step 1 */
.repl-items-list { display: flex; flex-direction: column; gap: 12px; }
.repl-item-card {
    border: 2px solid #E2E8F0;
    border-radius: 14px;
    padding: 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    transition: all 0.2s;
    cursor: default;
}
.repl-item-card:hover { border-color: #A78BFA; background: #FAFAFA; }
.repl-item-left { display: flex; align-items: center; gap: 12px; flex: 1; }
.repl-item-img {
    width: 52px; height: 52px;
    border-radius: 10px;
    object-fit: cover;
    background: #F1F5F9;
    display: flex; align-items: center; justify-content: center;
    font-size: 22px;
    flex-shrink: 0;
    border: 1px solid #E2E8F0;
}
.repl-item-info strong {
    display: block;
    font-size: 14px;
    font-weight: 800;
    color: #0F172A;
    margin-bottom: 3px;
}
.repl-item-info span {
    font-size: 12px;
    color: #64748B;
    display: block;
    margin-bottom: 4px;
}
.repl-item-attrs { display: flex; flex-wrap: wrap; gap: 4px; }
.repl-attr-chip {
    background: #EFF6FF;
    color: #1D4ED8;
    border: 1px solid #BFDBFE;
    border-radius: 12px;
    padding: 2px 8px;
    font-size: 11px;
    font-weight: 700;
}
.btn-start-repl {
    background: linear-gradient(135deg, #7C3AED, #4F46E5);
    color: white;
    border: none;
    border-radius: 10px;
    padding: 9px 16px;
    font-size: 12px;
    font-weight: 800;
    cursor: pointer;
    transition: all 0.2s;
    font-family: 'Tajawal', sans-serif;
    white-space: nowrap;
    display: inline-flex;
    align-items: center;
    gap: 5px;
}
.btn-start-repl:hover { transform: translateY(-2px); box-shadow: 0 6px 18px rgba(124,58,237,0.35); }

/* Step 2 — choose replacement */
.repl-step2 { display: none; }
.repl-step2.show { display: block; }
.repl-step1 { display: block; }
.repl-step1.hide { display: none; }

.repl-selected-item {
    background: linear-gradient(135deg, #EDE9FE, #F5F3FF);
    border: 2px solid #C4B5FD;
    border-radius: 14px;
    padding: 14px 18px;
    margin-bottom: 18px;
    display: flex;
    align-items: center;
    gap: 12px;
}
.repl-selected-item .repl-tag {
    background: #7C3AED;
    color: white;
    border-radius: 8px;
    padding: 4px 10px;
    font-size: 11px;
    font-weight: 800;
    white-space: nowrap;
}
.repl-selected-item .repl-name {
    font-weight: 800;
    color: #4C1D95;
    font-size: 14px;
}
.repl-selected-item .repl-price-qty {
    font-size: 12px;
    color: #6D28D9;
    margin-top: 2px;
}

.repl-section-title {
    font-size: 14px;
    font-weight: 900;
    color: #0F172A;
    margin-bottom: 12px;
    display: flex;
    align-items: center;
    gap: 8px;
}

/* Same product option */
.repl-same-product-box {
    background: #F0FDF4;
    border: 2px solid #A7F3D0;
    border-radius: 12px;
    padding: 14px 16px;
    margin-bottom: 14px;
}
.repl-same-toggle {
    display: flex;
    align-items: center;
    gap: 10px;
    cursor: pointer;
    margin-bottom: 0;
}
.repl-same-toggle input[type="checkbox"] {
    width: 17px; height: 17px;
    accent-color: #059669;
    cursor: pointer;
}
.repl-same-toggle label {
    font-size: 13px;
    font-weight: 800;
    color: #065F46;
    cursor: pointer;
}
.repl-same-attrs { display: none; margin-top: 12px; }
.repl-same-attrs.show { display: block; }

/* Product search */
.repl-search-box {
    position: relative;
    margin-bottom: 14px;
}
.repl-search-box input {
    width: 100%;
    padding: 11px 16px 11px 40px;
    border: 2px solid #E2E8F0;
    border-radius: 12px;
    font-size: 14px;
    font-family: 'Tajawal', sans-serif;
    outline: none;
    transition: all 0.2s;
    color: #0F172A;
    direction: rtl;
}
.repl-search-box input:focus { border-color: #7C3AED; box-shadow: 0 0 0 3px rgba(124,58,237,0.12); }
.repl-search-icon {
    position: absolute;
    left: 14px;
    top: 50%;
    transform: translateY(-50%);
    color: #94A3B8;
    pointer-events: none;
    font-size: 16px;
}
.repl-products-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    gap: 10px;
    max-height: 220px;
    overflow-y: auto;
    padding: 4px;
    margin-bottom: 14px;
}
.repl-product-card {
    border: 2px solid #E2E8F0;
    border-radius: 12px;
    padding: 12px;
    cursor: pointer;
    transition: all 0.2s;
    text-align: center;
    background: white;
}
.repl-product-card:hover { border-color: #A78BFA; background: #FAF5FF; }
.repl-product-card.selected-prod {
    border-color: #7C3AED;
    background: linear-gradient(135deg, #EDE9FE, #F5F3FF);
    box-shadow: 0 0 0 2px rgba(124,58,237,0.2);
}
.repl-product-card .prod-icon { font-size: 26px; margin-bottom: 6px; display: block; }
.repl-product-card .prod-name {
    font-size: 12px;
    font-weight: 700;
    color: #0F172A;
    line-height: 1.3;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

/* Variant + attrs selection */
.repl-variant-section {
    background: #F8FAFC;
    border: 1.5px solid #E2E8F0;
    border-radius: 12px;
    padding: 14px;
    margin-bottom: 14px;
}
.repl-variant-select {
    width: 100%;
    padding: 10px 14px;
    border: 1.5px solid #E2E8F0;
    border-radius: 10px;
    font-family: 'Tajawal', sans-serif;
    font-size: 13px;
    color: #0F172A;
    background: white;
    outline: none;
    transition: all 0.2s;
    cursor: pointer;
}
.repl-variant-select:focus { border-color: #7C3AED; }

.repl-attr-row { margin-bottom: 10px; }
.repl-attr-row label {
    display: block;
    font-size: 12px;
    font-weight: 700;
    color: #475569;
    margin-bottom: 6px;
}
.repl-attr-chips {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
}
.repl-attr-chip-btn {
    padding: 5px 13px;
    border: 1.5px solid #E2E8F0;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 700;
    cursor: pointer;
    background: white;
    color: #475569;
    transition: all 0.2s;
    font-family: 'Tajawal', sans-serif;
}
.repl-attr-chip-btn:hover { border-color: #7C3AED; color: #7C3AED; }
.repl-attr-chip-btn.active {
    background: #7C3AED;
    border-color: #7C3AED;
    color: white;
}
.repl-attr-input {
    width: 100%;
    padding: 9px 12px;
    border: 1.5px solid #E2E8F0;
    border-radius: 10px;
    font-family: 'Tajawal', sans-serif;
    font-size: 13px;
    outline: none;
    transition: all 0.2s;
}
.repl-attr-input:focus { border-color: #7C3AED; }

/* Quantity & price */
.repl-qty-price {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 12px;
    margin-bottom: 14px;
}
.repl-field label {
    display: block;
    font-size: 12px;
    font-weight: 700;
    color: #475569;
    margin-bottom: 6px;
}
.repl-field input {
    width: 100%;
    padding: 10px 12px;
    border: 1.5px solid #E2E8F0;
    border-radius: 10px;
    font-family: 'Tajawal', sans-serif;
    font-size: 14px;
    font-weight: 700;
    outline: none;
    transition: all 0.2s;
    color: #0F172A;
}
.repl-field input:focus { border-color: #7C3AED; box-shadow: 0 0 0 3px rgba(124,58,237,0.1); }

.repl-notes textarea {
    width: 100%;
    padding: 10px 12px;
    border: 1.5px solid #E2E8F0;
    border-radius: 10px;
    font-family: 'Tajawal', sans-serif;
    font-size: 13px;
    resize: vertical;
    min-height: 70px;
    outline: none;
    transition: all 0.2s;
    color: #0F172A;
}
.repl-notes textarea:focus { border-color: #7C3AED; }

.repl-footer {
    display: flex;
    gap: 10px;
    padding: 16px 24px 22px;
    border-top: 1px solid #F1F5F9;
}
.repl-footer .btn { flex: 1; justify-content: center; padding: 13px; font-size: 14px; }
.btn-repl-save {
    background: linear-gradient(135deg, #7C3AED, #4F46E5);
    color: white;
    border: none;
    border-radius: 10px;
    font-weight: 900;
}
.btn-repl-save:hover { opacity: 0.9; transform: translateY(-1px); box-shadow: 0 8px 20px rgba(124,58,237,0.35); }
.btn-repl-back {
    background: #F1F5F9;
    color: #64748B;
    border: 1.5px solid #E2E8F0;
    border-radius: 10px;
    font-weight: 700;
}
.btn-repl-back:hover { background: #E2E8F0; }

/* ===== Replacements Log in Details Modal ===== */
.repl-log-section {
    margin-top: 20px;
    background: linear-gradient(135deg, #EDE9FE, #F5F3FF);
    border: 2px solid #C4B5FD;
    border-radius: 14px;
    overflow: hidden;
}
.repl-log-header {
    background: linear-gradient(135deg, #7C3AED, #4F46E5);
    padding: 12px 18px;
    display: flex;
    align-items: center;
    gap: 8px;
}
.repl-log-header h3 { color: white; font-size: 14px; font-weight: 900; }
.repl-log-body { padding: 14px 16px; display: flex; flex-direction: column; gap: 10px; }
.repl-log-card {
    background: white;
    border-radius: 12px;
    padding: 14px 16px;
    border: 1.5px solid #E2E8F0;
    box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}
.repl-log-top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
    flex-wrap: wrap;
    gap: 8px;
}
.repl-log-arrow {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;
}
.repl-log-orig {
    background: #FEE2E2;
    color: #991B1B;
    border-radius: 8px;
    padding: 4px 10px;
    font-size: 12px;
    font-weight: 700;
    text-decoration: line-through;
}
.repl-log-new {
    background: #D1FAE5;
    color: #065F46;
    border-radius: 8px;
    padding: 4px 10px;
    font-size: 12px;
    font-weight: 700;
}
.repl-arrow-icon { font-size: 16px; color: #7C3AED; }
.repl-log-status-wrap { display: flex; align-items: center; gap: 8px; }
.repl-status-badge {
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 800;
    display: inline-flex;
    align-items: center;
    gap: 4px;
}
.repl-status-pending  { background: #FEF3C7; color: #D97706; border: 1px solid #FDE68A; }
.repl-status-sent     { background: #EDE9FE; color: #7C3AED; border: 1px solid #DDD6FE; }
.repl-status-received { background: #D1FAE5; color: #059669; border: 1px solid #A7F3D0; }
.repl-log-details {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    font-size: 12px;
    color: #64748B;
    margin-bottom: 10px;
}
.repl-log-detail { display: flex; align-items: center; gap: 4px; font-weight: 600; }
.repl-log-actions { display: flex; gap: 6px; flex-wrap: wrap; }
.btn-repl-status {
    padding: 5px 12px;
    border-radius: 8px;
    font-size: 11px;
    font-weight: 800;
    cursor: pointer;
    border: none;
    font-family: 'Tajawal', sans-serif;
    transition: all 0.2s;
    display: inline-flex;
    align-items: center;
    gap: 4px;
}
.btn-repl-sent     { background: #EDE9FE; color: #7C3AED; }
.btn-repl-sent:hover { background: #7C3AED; color: white; }
.btn-repl-received { background: #D1FAE5; color: #059669; }
.btn-repl-received:hover { background: #059669; color: white; }
.btn-repl-delete   { background: #FEE2E2; color: #DC2626; }
.btn-repl-delete:hover { background: #DC2626; color: white; }
.repl-log-date { font-size: 11px; color: #94A3B8; margin-top: 6px; }
.repl-log-notes {
    font-size: 12px;
    color: #64748B;
    background: #F8FAFC;
    border-radius: 8px;
    padding: 6px 10px;
    margin-top: 8px;
    border-right: 3px solid #7C3AED;
}
.repl-empty {
    text-align: center;
    padding: 20px;
    color: #94A3B8;
    font-size: 13px;
}
</style>

<!-- ════════════════════════════════════════════════════════════
     HTML — أضفه قبل </body> في orders.php
════════════════════════════════════════════════════════════ -->

<!-- زر الاستبدال — يُضاف داخل openDetailsModal() في JS ديناميكياً -->

<!-- REPLACEMENT MODAL -->
<div class="repl-modal" id="replModal">
    <div class="repl-box">
        <div class="repl-header">
            <h2>🔄 استبدال منتج</h2>
            <button class="repl-header-close" onclick="closeReplModal()">×</button>
        </div>
        <div class="repl-body">
            <!-- Step 1: اختر المنتج المراد استبداله -->
            <div id="replStep1" class="repl-step1">
                <div class="repl-section-title">
                    <span>📦</span> اختر المنتج الذي تريد استبداله
                </div>
                <div class="repl-items-list" id="replItemsList"></div>
            </div>

            <!-- Step 2: اختر البديل -->
            <div id="replStep2" class="repl-step2">
                <!-- المنتج المختار -->
                <div class="repl-selected-item" id="replSelectedItem">
                    <span class="repl-tag">المنتج الأصلي</span>
                    <div>
                        <div class="repl-name" id="replOrigName"></div>
                        <div class="repl-price-qty" id="replOrigPriceQty"></div>
                    </div>
                </div>

                <!-- نفس المنتج بخصائص مختلفة أو نفسها -->
                <div class="repl-same-product-box" id="replSameBox">
                    <div class="repl-same-toggle">
                        <input type="checkbox" id="replSameCheck" onchange="toggleSameProduct(this.checked)">
                        <label for="replSameCheck">🔄 استبدال بنفس المنتج (تغيير الخصائص فقط)</label>
                    </div>
                    <div class="repl-same-attrs" id="replSameAttrs"></div>
                </div>

                <!-- اختيار منتج آخر -->
                <div id="replOtherSection">
                    <div class="repl-section-title">
                        <span>🔍</span> أو اختر منتجاً آخر
                    </div>
                    <div class="repl-search-box">
                        <span class="repl-search-icon">🔍</span>
                        <input type="text" id="replSearch" placeholder="ابحث عن منتج..." oninput="filterReplProducts(this.value)">
                    </div>
                    <div class="repl-products-grid" id="replProductsGrid"></div>
                </div>

                <!-- المتغير والخصائص -->
                <div class="repl-variant-section" id="replVariantSection" style="display:none">
                    <div class="repl-section-title" style="margin-bottom:10px">
                        <span>🏷️</span> <span id="replVariantTitle">خصائص البديل</span>
                    </div>
                    <div id="replVariantContent"></div>
                </div>

                <!-- الكمية والسعر -->
                <div class="repl-qty-price">
                    <div class="repl-field">
                        <label>📦 الكمية</label>
                        <input type="number" id="replNewQty" value="1" min="1">
                    </div>
                    <div class="repl-field">
                        <label>💰 سعر الوحدة (دج)</label>
                        <input type="number" id="replNewPrice" step="0.01" min="0" placeholder="0.00">
                    </div>
                </div>

                <!-- ملاحظات -->
                <div class="repl-notes">
                    <label style="display:block;font-size:12px;font-weight:700;color:#475569;margin-bottom:6px">📝 ملاحظات (اختياري)</label>
                    <textarea id="replNotes" placeholder="سبب الاستبدال، ملاحظات..."></textarea>
                </div>
            </div>
        </div>
        <div class="repl-footer">
            <button class="btn btn-repl-back" id="replBackBtn" onclick="replGoBack()" style="display:none">← رجوع</button>
            <button class="btn sr-btn-abort" onclick="closeReplModal()">إلغاء</button>
            <button class="btn btn-repl-save" id="replSaveBtn" style="display:none" onclick="saveReplacement()">💾 حفظ الاستبدال</button>
        </div>
    </div>
</div>

<!-- ════════════════════════════════════════════════════════════
     JavaScript — أضفه داخل <script> في orders.php
     (بعد تعريف المتغيرات allProductsData, allProductVariants, allProductAttributes)
════════════════════════════════════════════════════════════ -->
<script id="replacement-js-placeholder">
// ════════════════════════════════════════════
//  REPLACEMENT SYSTEM
// ════════════════════════════════════════════

// تأكد أن هذا المتغير معرَّف في orders.php بنفس الشكل
// var orderReplacements = <?php /* = json_encode($orderReplacements) */ ?>;

var _replState = {
    orderId: null,
    originalItem: null,
    selectedProductId: null,
    selectedVariantId: null,
    selectedAttrs: {},
    isSameProduct: false,
    newProductName: '',
    newPrice: 0,
    newQty: 1,
};

// ── فتح Modal الاستبدال ──
function openReplModal(orderId) {
    _replState = { orderId: orderId, originalItem: null, selectedProductId: null, selectedVariantId: null, selectedAttrs: {}, isSameProduct: false, newProductName: '', newPrice: 0, newQty: 1 };
    var items = orderItems[orderId] || [];

    // بناء قائمة المنتجات في الطلب
    var html = '';
    items.forEach(function(item) {
        var attrs = {};
        try { attrs = JSON.parse(item.selected_attribute_value || '{}') || {}; } catch(e) {}
        var attrsHtml = '';
        Object.keys(attrs).forEach(function(k) {
            if (attrs[k]) attrsHtml += '<span class="repl-attr-chip">'+escapeHtml(k)+': '+escapeHtml(attrs[k])+'</span>';
        });
        html += '<div class="repl-item-card">' +
            '<div class="repl-item-left">' +
                '<div class="repl-item-img">📦</div>' +
                '<div class="repl-item-info">' +
                    '<strong>'+escapeHtml(item.product_name||'منتج')+'</strong>' +
                    '<span>الكمية: '+item.quantity+' | السعر: '+Number(item.unit_price).toFixed(2)+' دج</span>' +
                    (attrsHtml ? '<div class="repl-item-attrs">'+attrsHtml+'</div>' : '') +
                '</div>' +
            '</div>' +
            '<button class="btn-start-repl" onclick="replSelectItem('+JSON.stringify(item)+')">🔄 استبدال</button>' +
        '</div>';
    });
    document.getElementById('replItemsList').innerHTML = html || '<div class="repl-empty">لا توجد منتجات</div>';

    // إعادة ضبط الخطوات
    document.getElementById('replStep1').classList.remove('hide');
    document.getElementById('replStep2').classList.remove('show');
    document.getElementById('replStep1').classList.add('');
    document.getElementById('replBackBtn').style.display = 'none';
    document.getElementById('replSaveBtn').style.display = 'none';

    document.getElementById('replModal').classList.add('open');
}

function closeReplModal() {
    document.getElementById('replModal').classList.remove('open');
}

// ── اختيار المنتج الأصلي ──
function replSelectItem(item) {
    _replState.originalItem    = item;
    _replState.selectedAttrs   = {};
    _replState.selectedVariantId = null;
    _replState.isSameProduct   = false;

    // ملء معلومات المنتج الأصلي
    document.getElementById('replOrigName').textContent = item.product_name || 'منتج';
    document.getElementById('replOrigPriceQty').textContent = 'الكمية: '+item.quantity+' | السعر: '+Number(item.unit_price).toFixed(2)+' دج';
    document.getElementById('replNewQty').value = item.quantity;
    document.getElementById('replNewPrice').value = item.unit_price;
    document.getElementById('replNotes').value = '';

    // إعداد "نفس المنتج"
    document.getElementById('replSameCheck').checked = false;
    var sameAttrsHtml = buildSameProductAttrs(item);
    document.getElementById('replSameAttrs').innerHTML = sameAttrsHtml;
    document.getElementById('replSameAttrs').classList.remove('show');
    document.getElementById('replVariantSection').style.display = 'none';
    document.getElementById('replVariantContent').innerHTML = '';

    // بناء شبكة المنتجات الأخرى
    buildProductsGrid('');
    document.getElementById('replSearch').value = '';

    // الانتقال للخطوة 2
    document.getElementById('replStep1').style.display = 'none';
    document.getElementById('replStep2').classList.add('show');
    document.getElementById('replBackBtn').style.display = '';
    document.getElementById('replSaveBtn').style.display = '';
    _replState.newProductName = item.product_name;
    _replState.newPrice = item.unit_price;
}

function replGoBack() {
    document.getElementById('replStep1').style.display = 'block';
    document.getElementById('replStep2').classList.remove('show');
    document.getElementById('replBackBtn').style.display = 'none';
    document.getElementById('replSaveBtn').style.display = 'none';
}

// ── نفس المنتج ──
function buildSameProductAttrs(item) {
    var productId = item.product_id;
    var currentAttrs = {};
    try { currentAttrs = JSON.parse(item.selected_attribute_value || '{}') || {}; } catch(e) {}
    var attrs = allProductAttributes[productId] || [];
    var variants = allProductVariants[productId] || [];

    if (!attrs.length && variants.length <= 1) {
        return '<p style="font-size:13px;color:#059669;font-weight:700">✅ لا توجد خصائص — سيتم الاستبدال بنفس المنتج</p>';
    }

    var html = '';

    // اختيار المتغير إذا كان هناك أكثر من متغير
    if (variants.length > 1) {
        html += '<div class="repl-attr-row"><label>اختر المتغير:</label>';
        html += '<select class="repl-variant-select" id="sameVariantSelect" onchange="onSameVariantChange(this.value)">';
        html += '<option value="">— اختر —</option>';
        variants.forEach(function(v) {
            html += '<option value="'+v.id+'" data-price="'+v.price+'" '+(item.variant_id==v.id?'selected':'')+'>متغير #'+v.id+' — '+v.price+' دج</option>';
        });
        html += '</select></div>';
    } else if (variants.length === 1) {
        html += '<input type="hidden" id="sameVariantHidden" value="'+variants[0].id+'">';
    }

    // خصائص
    attrs.forEach(function(attr) {
        var currentVal = currentAttrs[attr.name] || '';
        html += '<div class="repl-attr-row"><label>'+escapeHtml(attr.name)+'</label>';
        if (attr.input_type === 'select' && attr.values_list) {
            var vals = attr.values_list.split(',').map(function(v){ return v.trim(); });
            html += '<div class="repl-attr-chips">';
            vals.forEach(function(v) {
                html += '<button type="button" class="repl-attr-chip-btn same-attr-chip '+(currentVal===v?'active':'')+'" '+
                    'data-attr="'+escapeHtml(attr.name)+'" data-val="'+escapeHtml(v)+'" '+
                    'onclick="toggleSameAttr(this)">'+escapeHtml(v)+'</button>';
            });
            html += '</div>';
        } else {
            html += '<input type="text" class="repl-attr-input same-attr-input" data-attr="'+escapeHtml(attr.name)+'" value="'+escapeHtml(currentVal)+'">';
        }
        html += '</div>';
    });

    return html;
}

function onSameVariantChange(variantId) {
    _replState.selectedVariantId = variantId || null;
    var variants = allProductVariants[_replState.originalItem.product_id] || [];
    var v = variants.find(function(x){ return x.id == variantId; });
    if (v) document.getElementById('replNewPrice').value = v.price;
}

function toggleSameAttr(btn) {
    var attrName = btn.getAttribute('data-attr');
    // deactivate siblings
    btn.closest('.repl-attr-chips').querySelectorAll('.same-attr-chip').forEach(function(b){
        b.classList.remove('active');
    });
    btn.classList.add('active');
    _replState.selectedAttrs[attrName] = btn.getAttribute('data-val');
}

function toggleSameProduct(checked) {
    _replState.isSameProduct = checked;
    document.getElementById('replSameAttrs').classList.toggle('show', checked);
    document.getElementById('replOtherSection').style.display = checked ? 'none' : 'block';
    document.getElementById('replVariantSection').style.display = 'none';
    document.getElementById('replVariantContent').innerHTML = '';
    _replState.selectedProductId = checked ? _replState.originalItem.product_id : null;
    _replState.selectedVariantId = null;
    _replState.selectedAttrs = {};
    _replState.newProductName = _replState.originalItem.product_name;

    if (checked) {
        // auto-set variant if only one
        var variants = allProductVariants[_replState.originalItem.product_id] || [];
        if (variants.length === 1) {
            _replState.selectedVariantId = variants[0].id;
            document.getElementById('replNewPrice').value = variants[0].price;
        }
        document.querySelectorAll('#replProductsGrid .repl-product-card').forEach(function(c){ c.classList.remove('selected-prod'); });
    }
}

// ── شبكة المنتجات الأخرى ──
function buildProductsGrid(filter) {
    var grid = document.getElementById('replProductsGrid');
    var filtered = allProductsData;
    if (filter) {
        filter = filter.toLowerCase();
        filtered = filtered.filter(function(p){ return p.name.toLowerCase().indexOf(filter) !== -1; });
    }
    if (!filtered.length) {
        grid.innerHTML = '<div style="grid-column:1/-1;text-align:center;padding:20px;color:#94A3B8;font-size:13px">لا توجد نتائج</div>';
        return;
    }
    var html = '';
    filtered.forEach(function(p) {
        var isSelected = (_replState.selectedProductId == p.id && !_replState.isSameProduct);
        html += '<div class="repl-product-card '+(isSelected?'selected-prod':'')+'" onclick="selectReplProduct('+p.id+',\''+escapeHtml(p.name)+'\')" data-prod-id="'+p.id+'">' +
            '<span class="prod-icon">📦</span>' +
            '<span class="prod-name">'+escapeHtml(p.name)+'</span>' +
        '</div>';
    });
    grid.innerHTML = html;
}

function filterReplProducts(val) {
    buildProductsGrid(val);
}

function selectReplProduct(productId, productName) {
    if (_replState.isSameProduct) {
        document.getElementById('replSameCheck').checked = false;
        toggleSameProduct(false);
    }

    _replState.selectedProductId = productId;
    _replState.selectedVariantId = null;
    _replState.selectedAttrs     = {};
    _replState.newProductName    = productName;

    // تظليل البطاقة المختارة
    document.querySelectorAll('#replProductsGrid .repl-product-card').forEach(function(c){
        c.classList.toggle('selected-prod', parseInt(c.getAttribute('data-prod-id')) === productId);
    });

    // بناء قسم المتغير والخصائص
    buildReplVariantSection(productId);
}

function buildReplVariantSection(productId) {
    var variants = allProductVariants[productId] || [];
    var attrs    = allProductAttributes[productId] || [];
    var section  = document.getElementById('replVariantSection');
    var content  = document.getElementById('replVariantContent');

    if (!variants.length && !attrs.length) {
        section.style.display = 'none';
        content.innerHTML = '';
        return;
    }

    section.style.display = 'block';
    var html = '';

    // اختيار المتغير
    if (variants.length === 1) {
        _replState.selectedVariantId = variants[0].id;
        document.getElementById('replNewPrice').value = variants[0].price;
        html += '<div style="background:#D1FAE5;border-radius:8px;padding:8px 12px;font-size:12px;font-weight:700;color:#065F46;margin-bottom:12px">✅ متغير وحيد — السعر: '+variants[0].price+' دج | المخزون: '+variants[0].stock+'</div>';
    } else if (variants.length > 1) {
        html += '<div class="repl-attr-row"><label>اختر المتغير:</label>';
        html += '<select class="repl-variant-select" onchange="onReplVariantChange(this.value)">';
        html += '<option value="">— اختر المتغير —</option>';
        variants.forEach(function(v) {
            html += '<option value="'+v.id+'" data-price="'+v.price+'" data-stock="'+v.stock+'">متغير #'+v.id+' — '+v.price+' دج (مخزون: '+v.stock+')</option>';
        });
        html += '</select></div>';
    }

    // الخصائص
    attrs.forEach(function(attr) {
        html += '<div class="repl-attr-row"><label>'+escapeHtml(attr.name)+'</label>';
        if (attr.input_type === 'select' && attr.values_list) {
            var vals = attr.values_list.split(',').map(function(v){ return v.trim(); });
            html += '<div class="repl-attr-chips">';
            vals.forEach(function(v) {
                html += '<button type="button" class="repl-attr-chip-btn other-attr-chip" '+
                    'data-attr="'+escapeHtml(attr.name)+'" data-val="'+escapeHtml(v)+'" '+
                    'onclick="toggleOtherAttr(this)">'+escapeHtml(v)+'</button>';
            });
            html += '</div>';
        } else {
            html += '<input type="text" class="repl-attr-input other-attr-input" data-attr="'+escapeHtml(attr.name)+'" placeholder="أدخل '+escapeHtml(attr.name)+'">';
        }
        html += '</div>';
    });

    content.innerHTML = html;
}

function onReplVariantChange(variantId) {
    _replState.selectedVariantId = variantId || null;
    var sel = document.querySelector('#replVariantContent .repl-variant-select');
    if (sel) {
        var opt = sel.options[sel.selectedIndex];
        if (opt && opt.value) document.getElementById('replNewPrice').value = opt.getAttribute('data-price') || '';
    }
}

function toggleOtherAttr(btn) {
    var attrName = btn.getAttribute('data-attr');
    btn.closest('.repl-attr-chips').querySelectorAll('.other-attr-chip').forEach(function(b){
        b.classList.remove('active');
    });
    btn.classList.add('active');
    _replState.selectedAttrs[attrName] = btn.getAttribute('data-val');
}

// ── حفظ الاستبدال ──
function saveReplacement() {
    var item = _replState.originalItem;
    if (!item) { alert('خطأ: لم يتم اختيار المنتج الأصلي'); return; }

    var newProductName = _replState.newProductName || '';
    var newVariantId   = _replState.selectedVariantId || null;
    var newQty         = parseInt(document.getElementById('replNewQty').value) || 1;
    var newPrice       = parseFloat(document.getElementById('replNewPrice').value) || 0;
    var notes          = document.getElementById('replNotes').value.trim();

    // جمع الخصائص من الـ inputs
    var finalAttrs = Object.assign({}, _replState.selectedAttrs);

    if (_replState.isSameProduct) {
        // نفس المنتج: جمع من same-attr-chip المفعَّلة
        document.querySelectorAll('#replSameAttrs .same-attr-chip.active').forEach(function(b){
            finalAttrs[b.getAttribute('data-attr')] = b.getAttribute('data-val');
        });
        document.querySelectorAll('#replSameAttrs .same-attr-input').forEach(function(inp){
            if (inp.value.trim()) finalAttrs[inp.getAttribute('data-attr')] = inp.value.trim();
        });
        // variant من hidden أو select
        var sameVarHidden = document.getElementById('sameVariantHidden');
        var sameVarSelect = document.getElementById('sameVariantSelect');
        if (sameVarHidden) newVariantId = sameVarHidden.value;
        if (sameVarSelect && sameVarSelect.value) newVariantId = sameVarSelect.value;
        newProductName = item.product_name;
    } else {
        // منتج آخر: جمع من other-attr-chip وother-attr-input
        document.querySelectorAll('#replVariantContent .other-attr-chip.active').forEach(function(b){
            finalAttrs[b.getAttribute('data-attr')] = b.getAttribute('data-val');
        });
        document.querySelectorAll('#replVariantContent .other-attr-input').forEach(function(inp){
            if (inp.value.trim()) finalAttrs[inp.getAttribute('data-attr')] = inp.value.trim();
        });
        if (!newProductName) { alert('يرجى اختيار المنتج البديل'); return; }
    }

    if (newQty < 1)  { alert('الكمية يجب أن تكون 1 على الأقل'); return; }
    if (newPrice < 0) { alert('السعر غير صحيح'); return; }
    if (!confirm('تأكيد تسجيل الاستبدال؟\n\nالأصلي: '+item.product_name+'\nالبديل: '+newProductName)) return;

    // إرسال Form
    var f = document.createElement('form');
    f.method = 'POST';
    f.style.display = 'none';

    var fields = {
        save_replacement: '1',
        order_id: _replState.orderId,
        original_item_id: item.id,
        original_product_name: item.product_name,
        original_variant_id: item.product_variant_id || '',
        original_attributes: item.selected_attribute_value || '[]',
        original_quantity: item.quantity,
        original_unit_price: item.unit_price,
        new_product_name: newProductName,
        new_variant_id: newVariantId || '',
        new_attributes: JSON.stringify(finalAttrs),
        new_quantity: newQty,
        new_unit_price: newPrice,
        notes: notes,
    };

    Object.keys(fields).forEach(function(k){
        var inp = document.createElement('input');
        inp.type = 'hidden';
        inp.name = k;
        inp.value = fields[k];
        f.appendChild(inp);
    });

    document.body.appendChild(f);
    f.submit();
}

// ════════════════════════════════════════════
// تحديث openDetailsModal لإضافة زر الاستبدال وسجل الاستبدالات
// (استبدل الدالة openDetailsModal الموجودة بهذه)
// ════════════════════════════════════════════
function openDetailsModal(orderId) {
    var order   = orders.find(function(o){ return o.id == orderId; });
    var items   = orderItems[orderId]   || [];
    var total   = orderTotals[orderId]  || 0;
    var delivery = deliveryPrices[orderId] || 0;
    var commune = communeNames[orderId]  || '--';

    var statusMap = {1:'⏳ قيد الانتظار', 2:'🚚 تم الإرسال', 3:'✅ تم التسليم', 4:'❌ ملغي'};
    var deliveryLabel = order.delivery_type == 'home' ? '🏠 للمنزل' : '🏢 للمكتب';

    var html = '<div class="customer-info-section"><h3 style="margin:0 0 14px">👤 معلومات العميل</h3><div class="customer-info-grid">';
    html += infoRow('الاسم', order.customer_name || '--');
    html += infoRow('الهاتف', order.phone || '--');
    if (order.phone2) html += infoRow('هاتف إضافي', order.phone2);
    html += infoRow('الولاية', order.wilaya_name || '--');
    html += infoRow('البلدية', commune);
    html += infoRow('العنوان', order.address || '--');
    html += infoRow('نوع التوصيل', deliveryLabel);
    html += infoRow('الحالة', statusMap[order.status_id] || '--');
    html += infoRow('التاريخ', order.order_date || '--');
    html += infoRow('شركة التوصيل', order.delivery_company_name || '--');
    if (order.tracking_code) html += infoRow('رمز التتبع', order.tracking_code);
    html += '</div></div>';

    if (items.length) {
        html += '<h3 style="margin:16px 0 12px;font-weight:800">📦 المنتجات</h3>';
        html += '<table class="products-table"><thead><tr><th>المنتج</th><th>الخصائص</th><th>الكمية</th><th>السعر</th><th>الإجمالي</th></tr></thead><tbody>';
        items.forEach(function(item) {
            html += '<tr><td>' + escapeHtml(item.product_name || 'منتج') + '</td>' +
                    '<td>' + formatAttributes(item.selected_attribute_value) + '</td>' +
                    '<td>' + item.quantity + '</td>' +
                    '<td>' + Number(item.unit_price).toFixed(2) + ' دج</td>' +
                    '<td>' + (item.quantity * item.unit_price).toFixed(2) + ' دج</td></tr>';
        });
        html += '</tbody></table>';
    }

    html += '<div class="summary-section"><h3>ملخص الطلب</h3>';
    html += '<div class="summary-row"><span>إجمالي المنتجات</span><span>' + total.toFixed(2) + ' دج</span></div>';
    html += '<div class="summary-row"><span>التوصيل</span><span>' + (delivery == 0 ? 'مجاني' : delivery.toFixed(2) + ' دج') + '</span></div>';
    html += '<div class="summary-row total"><span>الإجمالي الكلي</span><span>' + (total + delivery).toFixed(2) + ' دج</span></div></div>';

    // ── زر الاستبدال (فقط إذا كانت الحالة "تم التسليم" = 3) ──
    if (parseInt(order.status_id) === 3 && items.length > 0) {
        html += '<div style="margin-top:16px;text-align:center">' +
            '<button onclick="openReplModal(' + orderId + ')" ' +
            'style="background:linear-gradient(135deg,#7C3AED,#4F46E5);color:white;border:none;border-radius:12px;padding:13px 28px;font-size:14px;font-weight:900;cursor:pointer;font-family:Tajawal,sans-serif;display:inline-flex;align-items:center;gap:8px;box-shadow:0 6px 20px rgba(124,58,237,0.35);transition:all 0.2s" ' +
            'onmouseover="this.style.transform=\'translateY(-2px)\'" onmouseout="this.style.transform=\'\'">' +
            '🔄 استبدال منتج' +
            '</button>' +
        '</div>';
    }

    // ── سجل الاستبدالات ──
    // تحقق إذا كان orderReplacements معرَّفاً
    var repls = (typeof orderReplacements !== 'undefined' && orderReplacements[orderId]) ? orderReplacements[orderId] : [];

    if (repls.length > 0) {
        html += '<div class="repl-log-section">';
        html += '<div class="repl-log-header"><h3>🔄 سجل الاستبدالات ('+repls.length+')</h3></div>';
        html += '<div class="repl-log-body">';

        repls.forEach(function(r) {
            var statusLabel = { pending:'⏳ في الانتظار', sent:'🚚 تم الإرسال', received:'✅ تم الاستلام' }[r.status] || r.status;
            var statusClass = { pending:'repl-status-pending', sent:'repl-status-sent', received:'repl-status-received' }[r.status] || 'repl-status-pending';

            var origAttrs = {};
            var newAttrs  = {};
            try { origAttrs = JSON.parse(r.original_attributes || '{}') || {}; } catch(e){}
            try { newAttrs  = JSON.parse(r.new_attributes || '{}') || {};      } catch(e){}

            var origAttrsStr = Object.keys(origAttrs).filter(function(k){ return origAttrs[k]; }).map(function(k){ return k+': '+origAttrs[k]; }).join(' | ');
            var newAttrsStr  = Object.keys(newAttrs ).filter(function(k){ return newAttrs[k];  }).map(function(k){ return k+': '+newAttrs[k];  }).join(' | ');

            html += '<div class="repl-log-card">';
            html += '<div class="repl-log-top">';
            html += '<div class="repl-log-arrow">' +
                '<span class="repl-log-orig">'+escapeHtml(r.original_product_name)+(origAttrsStr?' ('+escapeHtml(origAttrsStr)+')':'')+'</span>' +
                '<span class="repl-arrow-icon">←</span>' +
                '<span class="repl-log-new">'+escapeHtml(r.new_product_name)+(newAttrsStr?' ('+escapeHtml(newAttrsStr)+')':'')+'</span>' +
            '</div>';
            html += '<div class="repl-log-status-wrap"><span class="repl-status-badge '+statusClass+'">'+statusLabel+'</span></div>';
            html += '</div>';

            html += '<div class="repl-log-details">' +
                '<span class="repl-log-detail">📦 الكمية: <strong>'+r.new_quantity+'</strong></span>' +
                '<span class="repl-log-detail">💰 السعر: <strong>'+Number(r.new_unit_price).toFixed(2)+' دج</strong></span>' +
            '</div>';

            html += '<div class="repl-log-actions">';
            if (r.status === 'pending') {
                html += '<form method="POST" style="display:contents">' +
                    '<input type="hidden" name="update_replacement_status" value="1">' +
                    '<input type="hidden" name="replacement_id" value="'+r.id+'">' +
                    '<input type="hidden" name="replacement_status" value="sent">' +
                    '<button type="submit" class="btn-repl-status btn-repl-sent">🚚 تم إرسال البديل</button>' +
                '</form>';
            }
            if (r.status === 'sent') {
                html += '<form method="POST" style="display:contents">' +
                    '<input type="hidden" name="update_replacement_status" value="1">' +
                    '<input type="hidden" name="replacement_id" value="'+r.id+'">' +
                    '<input type="hidden" name="replacement_status" value="received">' +
                    '<button type="submit" class="btn-repl-status btn-repl-received">✅ تم استلام البديل</button>' +
                '</form>';
            }
            html += '<form method="POST" style="display:contents">' +
                '<input type="hidden" name="delete_replacement" value="1">' +
                '<input type="hidden" name="replacement_id" value="'+r.id+'">' +
                '<button type="submit" class="btn-repl-status btn-repl-delete" onclick="return confirm(\'حذف هذا السجل؟\')">🗑️ حذف</button>' +
            '</form>';
            html += '</div>';

            if (r.notes) {
                html += '<div class="repl-log-notes">📝 '+escapeHtml(r.notes)+'</div>';
            }
            html += '<div class="repl-log-date">📅 '+r.created_at+'</div>';
            html += '</div>';
        });

        html += '</div></div>';
    }

    document.getElementById('detailsContent').innerHTML = html;
    document.getElementById('detailsModal').style.display = 'flex';
}
</script>