<?php
require_once '../includes/auth.php';
require_once 'functions.php';
require_once '../product_import_catalog/functions.php';
require_once '../includes/header.php';
require_once '../includes/sidebar.php';

if (!function_exists('e')) {
    function e($value) {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

$categories = [];
$brands = [];
$productTypes = [];
$tiers = prd_get_customer_tiers($conn);
prd_ensure_access_schema($conn);
pic_ensure_schema($conn);

$catRes = $conn->query("SELECT id, name FROM categories WHERE status = 1 ORDER BY sort_order ASC, id DESC");
if ($catRes) {
    while ($row = $catRes->fetch_assoc()) {
        $categories[] = $row;
    }
}

$brandRes = $conn->query("SELECT id, name FROM brands WHERE status = 1 ORDER BY sort_order ASC, name ASC");
if ($brandRes) {
    while ($row = $brandRes->fetch_assoc()) {
        $brands[] = $row;
    }
}

$typeRes = $conn->query("SELECT id, category_id, name FROM product_types WHERE status = 1 ORDER BY sort_order ASC, id DESC");
if ($typeRes) {
    while ($row = $typeRes->fetch_assoc()) {
        $productTypes[] = $row;
    }
}

$old = $_SESSION['product_form_old'] ?? [];
$errors = $_SESSION['product_form_errors'] ?? [];
unset($_SESSION['product_form_old'], $_SESSION['product_form_errors']);
?>

<style>
    .products-create-page{
        padding:24px;
        direction:rtl;
    }
    .products-create-wrap{
        max-width:1400px;
        margin:0 auto;
    }
    .page-topbar{
        display:flex;
        justify-content:space-between;
        align-items:center;
        gap:16px;
        margin-bottom:24px;
        flex-wrap:wrap;
    }
    .page-title-box h1{
        margin:0 0 8px;
        font-size:30px;
        font-weight:800;
        color:#17324d;
    }
    .page-title-box p{
        margin:0;
        color:#6b7c93;
        font-size:14px;
    }
    .top-actions{
        display:flex;
        gap:10px;
        flex-wrap:wrap;
    }
    .btn-modern{
        border:none;
        border-radius:14px;
        padding:12px 18px;
        font-size:14px;
        font-weight:700;
        cursor:pointer;
        text-decoration:none;
        display:inline-flex;
        align-items:center;
        justify-content:center;
        gap:8px;
        transition:.2s ease;
    }
    .btn-modern.primary{
        background:linear-gradient(135deg,#2f80ed,#56ccf2);
        color:#fff;
        box-shadow:0 10px 25px rgba(47,128,237,.20);
    }
    .btn-modern.primary:hover{
        transform:translateY(-1px);
    }
    .btn-modern.light{
        background:#fff;
        color:#24415c;
        border:1px solid #d9e6f2;
    }
    .grid-layout{
        display:grid;
        grid-template-columns:1.15fr .85fr;
        gap:20px;
    }
    .stack{
        display:grid;
        gap:20px;
    }
    .card-box{
        background:#fff;
        border-radius:24px;
        box-shadow:0 12px 35px rgba(16,24,40,.06);
        border:1px solid #edf2f7;
        overflow:hidden;
    }
    .card-head{
        padding:20px 22px;
        border-bottom:1px solid #eef3f8;
        display:flex;
        justify-content:space-between;
        align-items:center;
        gap:12px;
        flex-wrap:wrap;
    }
    .card-head h3{
        margin:0;
        font-size:18px;
        color:#17324d;
        font-weight:800;
    }
    .card-head span{
        color:#7c8da1;
        font-size:13px;
    }
    .card-body{
        padding:22px;
    }
    .form-grid{
        display:grid;
        grid-template-columns:repeat(2,minmax(0,1fr));
        gap:16px;
    }
    .form-grid-3{
        display:grid;
        grid-template-columns:repeat(3,minmax(0,1fr));
        gap:16px;
    }
    .field{
        display:flex;
        flex-direction:column;
        gap:8px;
    }
    .field.full{
        grid-column:1 / -1;
    }
    .field label{
        font-size:13px;
        font-weight:800;
        color:#26425c;
    }
    .field input[type="text"],
    .field input[type="number"],
    .field input[type="file"],
    .field select,
    .field textarea{
        width:100%;
        border:1px solid #d8e4ef;
        background:#f9fcff;
        border-radius:16px;
        padding:14px 15px;
        font-size:14px;
        color:#17324d;
        outline:none;
        transition:.2s ease;
        box-sizing:border-box;
    }
    .field textarea{
        min-height:110px;
        resize:vertical;
    }
    .field input:focus,
    .field select:focus,
    .field textarea:focus{
        border-color:#67b4ff;
        background:#fff;
        box-shadow:0 0 0 4px rgba(103,180,255,.12);
    }
    .helper{
        font-size:12px;
        color:#7c8da1;
    }
    .error-box{
        background:#fff0f0;
        color:#b42318;
        border:1px solid #f7c3c3;
        padding:14px 16px;
        border-radius:16px;
        margin-bottom:18px;
    }
    .chips-box{
        display:grid;
        grid-template-columns:repeat(auto-fill,minmax(180px,1fr));
        gap:12px;
    }
    .chip-option{
        position:relative;
    }
    .chip-option input{
        position:absolute;
        opacity:0;
        pointer-events:none;
    }
    .chip-option label{
        display:flex;
        align-items:center;
        justify-content:center;
        gap:8px;
        min-height:50px;
        text-align:center;
        border-radius:16px;
        border:1px solid #dbe7f1;
        background:#f8fbfe;
        cursor:pointer;
        font-size:14px;
        font-weight:700;
        color:#274560;
        padding:10px 12px;
        transition:.2s ease;
    }
    .chip-option input:checked + label{
        background:linear-gradient(135deg,#e6f4ff,#f3fbff);
        border-color:#67b4ff;
        color:#0f5ca8;
        box-shadow:0 10px 25px rgba(103,180,255,.12);
    }
    .switch-row{
        display:flex;
        align-items:center;
        justify-content:space-between;
        gap:16px;
        padding:16px 18px;
        border:1px solid #e4edf5;
        border-radius:18px;
        background:#fbfdff;
        margin-bottom:14px;
    }
    .switch-info strong{
        display:block;
        color:#17324d;
        font-size:14px;
        margin-bottom:4px;
    }
    .switch-info span{
        font-size:12px;
        color:#7b8ca0;
    }
    .toggle{
        position:relative;
        width:60px;
        height:32px;
        flex:0 0 auto;
    }
    .toggle input{
        opacity:0;
        width:0;
        height:0;
    }
    .toggle-slider{
        position:absolute;
        inset:0;
        background:#d7e3ee;
        border-radius:999px;
        transition:.2s;
        cursor:pointer;
    }
    .toggle-slider:before{
        content:"";
        position:absolute;
        width:24px;
        height:24px;
        right:4px;
        top:4px;
        border-radius:50%;
        background:#fff;
        transition:.2s;
        box-shadow:0 4px 10px rgba(0,0,0,.12);
    }
    .toggle input:checked + .toggle-slider{
        background:linear-gradient(135deg,#2f80ed,#56ccf2);
    }
    .toggle input:checked + .toggle-slider:before{
        transform:translateX(-28px);
    }
    .variants-wrapper{
        display:none;
        margin-top:16px;
    }
    .variants-wrapper.active{
        display:block;
    }
    .variant-card{
        border:1px solid #e4edf5;
        border-radius:22px;
        padding:18px;
        background:#fcfeff;
        margin-bottom:16px;
        position:relative;
    }
    .variant-top{
        display:flex;
        justify-content:space-between;
        align-items:center;
        gap:10px;
        margin-bottom:14px;
        flex-wrap:wrap;
    }
    .variant-top h4{
        margin:0;
        font-size:16px;
        color:#17324d;
        font-weight:800;
    }
    .variant-remove{
        background:#fff1f1;
        color:#c62828;
        border:1px solid #ffd2d2;
        border-radius:12px;
        padding:10px 14px;
        cursor:pointer;
        font-weight:800;
    }
    .preview-box{
        background:linear-gradient(135deg,#f6fbff,#edf7ff);
        border:1px dashed #b9d7f3;
        border-radius:20px;
        padding:18px;
        display:grid;
        gap:14px;
    }
    .preview-item{
        background:#fff;
        border-radius:16px;
        padding:14px;
        border:1px solid #e8f0f7;
    }
    .preview-item strong{
        display:block;
        font-size:12px;
        color:#7390a9;
        margin-bottom:8px;
    }
    .preview-item div{
        font-size:15px;
        color:#17324d;
        font-weight:800;
        word-break:break-word;
    }
    .submit-bar{
        position:sticky;
        bottom:18px;
        z-index:5;
        margin-top:20px;
        background:rgba(255,255,255,.85);
        backdrop-filter:blur(12px);
        border:1px solid #e6eef7;
        border-radius:22px;
        padding:14px;
        display:flex;
        justify-content:space-between;
        align-items:center;
        gap:16px;
        flex-wrap:wrap;
    }
    .submit-note{
        color:#6f8398;
        font-size:13px;
        font-weight:700;
    }
    .hidden{
        display:none !important;
    }

    .catalog-search-box{position:relative}
    .catalog-results{position:absolute;top:100%;right:0;left:0;background:#fff;border:1px solid #d8e4ef;border-radius:16px;margin-top:8px;max-height:320px;overflow:auto;z-index:20;box-shadow:0 18px 40px rgba(16,24,40,.12);display:none}
    .catalog-results.active{display:block}
    .catalog-item{padding:12px 14px;border-bottom:1px solid #edf2f7;cursor:pointer;display:flex;justify-content:space-between;gap:12px;align-items:center}
    .catalog-item:hover{background:#f8fbfe}
    .catalog-item.used{background:#fff5f5;color:#b42318}
    .catalog-item strong{display:block;font-size:13px}
    .catalog-item small{display:block;color:#7c8da1;margin-top:3px;direction:ltr;text-align:right}
    .catalog-badge{font-size:11px;font-weight:900;border-radius:999px;padding:5px 8px;white-space:nowrap}
    .catalog-badge.used{background:#ffe1e1;color:#b42318}
    .catalog-badge.free{background:#dcfae6;color:#027a48}
    .catalog-selected-warning{display:none;margin-top:10px;background:#fff1f1;color:#b42318;border:1px solid #fecaca;border-radius:14px;padding:10px 12px;font-weight:900;font-size:13px}
    .catalog-selected-warning.active{display:block}

    @media (max-width: 1100px){
        .grid-layout{
            grid-template-columns:1fr;
        }
    }
    @media (max-width: 768px){
        .products-create-page{
            padding:14px;
        }
        .form-grid,
        .form-grid-3{
            grid-template-columns:1fr;
        }
        .page-title-box h1{
            font-size:24px;
        }
        .submit-bar{
            position:static;
        }
    }

.server-image-selected{margin-top:8px;font-size:12px;color:#0f766e}.server-image-selected img{width:64px;height:64px;object-fit:cover;border-radius:12px;border:1px solid #dbeafe;margin-inline-end:8px;vertical-align:middle}.image-picker-btn{margin-top:8px;border:1px solid #d7e8ef;background:#f8fcff;color:#1f4b5c;border-radius:10px;padding:8px 12px;cursor:pointer}.server-image-modal{position:fixed;inset:0;background:rgba(15,23,42,.42);display:none;align-items:center;justify-content:center;z-index:9999;padding:20px}.server-image-modal.active{display:flex}.server-image-box{background:#fff;border-radius:20px;max-width:900px;width:100%;max-height:82vh;overflow:hidden;box-shadow:0 20px 60px rgba(15,23,42,.25);direction:rtl}.server-image-head{display:flex;align-items:center;justify-content:space-between;padding:16px 18px;border-bottom:1px solid #eef2f7}.server-image-head strong{font-size:16px}.server-image-close{border:0;background:#f1f5f9;border-radius:10px;padding:8px 12px;cursor:pointer}.server-image-grid{padding:16px;display:grid;grid-template-columns:repeat(auto-fill,minmax(110px,1fr));gap:12px;overflow:auto;max-height:62vh}.server-image-item{border:1px solid #e5edf5;border-radius:14px;padding:8px;background:#fbfdff;cursor:pointer;text-align:center;transition:.15s}.server-image-item:hover{border-color:#8ccfe3;transform:translateY(-1px)}.server-image-folder{background:linear-gradient(180deg,#f8fcff,#ffffff)}.server-image-folder.selected-brand{border-color:#ef4444;background:#fff7f7}.server-image-folder.selected-brand small:first-of-type{color:#b91c1c;font-weight:700}.server-image-item img{width:100%;height:86px;object-fit:cover;border-radius:10px}.server-image-item small{display:block;margin-top:6px;font-size:10px;color:#64748b;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.server-image-empty{padding:24px;text-align:center;color:#64748b}
</style>

<div class="products-create-page">
    <div class="products-create-wrap">

        <div class="page-topbar">
            <div class="page-title-box">
                <h1>إضافة منتج جديد</h1>
                <p>أدخل بيانات المنتج بشكل مرتب، والفورم راح يرتب الاسم والسلاج والـ SKU تلقائياً.</p>
            </div>

            <div class="top-actions">
                <a href="index.php" class="btn-modern light">رجوع</a>
                <button type="submit" form="productCreateForm" class="btn-modern primary">حفظ المنتج</button>
            </div>
        </div>

        <?php if (!empty($errors)): ?>
            <div class="error-box">
                <?php foreach ($errors as $err): ?>
                    <div>• <?= e($err) ?></div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <form id="productCreateForm" action="save.php" method="post" enctype="multipart/form-data">
            <div class="grid-layout">

                <div class="stack">
                    <div class="card-box">
                        <div class="card-head">
                            <h3>البيانات الأساسية</h3>
                            <span>الاسم الكامل يتكوّن تلقائياً من البراند + اسم المنتج</span>
                        </div>
                        <div class="card-body">
                            <div class="form-grid">
                                <div class="field full catalog-search-box">
                                    <label>اختيار المنتج من الكتالوج الداخلي / Slug</label>
                                    <input type="hidden" name="import_catalog_id" id="import_catalog_id" value="<?= e($old['import_catalog_id'] ?? '') ?>">
                                    <input type="hidden" name="internal_name" id="internal_name" value="<?= e($old['internal_name'] ?? '') ?>">
                                    <input type="text" id="catalog_search" autocomplete="off" placeholder="اكتب الاسم الداخلي أو الباركود من ملف Excel..." value="<?= e($old['internal_name'] ?? '') ?>">
                                    <div class="catalog-results" id="catalog_results"></div>
                                    <div class="helper">اختيار المادة يملأ الـ Barcode والسعر تلقائياً. إذا المادة مستخدمة مسبقاً تظهر بالأحمر.</div>
                                    <div class="catalog-selected-warning" id="catalog_warning">⚠️ هذه المادة مستخدمة مسبقاً في منتج آخر. انتبه حتى لا يتكرر المنتج.</div>
                                </div>

                                <div class="field">
                                    <label>التصنيف الرئيسي</label>
                                    <select name="category_id" id="category_id" required>
                                        <option value="">اختر التصنيف</option>
                                        <?php foreach ($categories as $cat): ?>
                                            <option value="<?= (int)$cat['id'] ?>" <?= (($old['category_id'] ?? '') == $cat['id']) ? 'selected' : '' ?>>
                                                <?= e($cat['name']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>

                                <div class="field">
                                    <label>البراند</label>
                                    <select id="brand_select" required>
                                        <option value="">اختر البراند</option>
                                        <?php foreach ($brands as $brand): ?>
                                            <option value="<?= e($brand['name']) ?>" <?= (($old['brand_part'] ?? '') === $brand['name']) ? 'selected' : '' ?>>
                                                <?= e($brand['name']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <input type="hidden" name="brand_part" id="brand_part" value="<?= e($old['brand_part'] ?? '') ?>">
                                </div>

                                <div class="field">
                                    <label>اسم المنتج</label>
                                    <input type="text" name="product_part" id="product_part" value="<?= e($old['product_part'] ?? '') ?>" placeholder="مثلاً: افكلار مات" required>
                                </div>

                                <div class="field">
                                    <label>اسم المنتج الكامل</label>
                                    <input type="text" name="name" id="name" value="<?= e($old['name'] ?? '') ?>" readonly>
                                    <div class="helper">يتكوّن تلقائياً من البراند + اسم المنتج</div>
                                </div>

                                <div class="field">
                                    <label>Slug / الاسم الداخلي داخل السيستم</label>
                                    <input type="text" name="slug" id="slug" value="<?= e($old['slug'] ?? '') ?>" readonly>
                                </div>

                                <div class="field">
                                    <label>باركود المنتج</label>
                                    <input type="text" name="sku" id="sku" value="<?= e($old['barcode'] ?? $old['sku'] ?? '') ?>" inputmode="numeric" autocomplete="off" placeholder="امسح/اكتب باركود المادة">
                                    <div class="helper">يتعبأ من الكتالوج الداخلي عند الاختيار، وتكدر تعدّله يدوياً قبل الحفظ.</div>
                                </div>

                                <div class="field full">
                                    <label>وصف مختصر</label>
                                    <textarea name="short_description" placeholder="نبذة مختصرة عن المنتج"><?= e($old['short_description'] ?? '') ?></textarea>
                                </div>                                <div class="field">
                                    <label>الصورة الرئيسية</label>
                                    <input type="file" name="main_image" accept=".jpg,.jpeg,.png,.webp">
                                    <input type="hidden" name="existing_main_image" id="existing_main_image" value="">
                                    <button type="button" class="btn-light image-picker-btn" data-target="existing_main_image" data-preview="main_image_existing_preview">اختيار من الصور الموجودة</button>
                                    <div class="helper">إذا اخترت صورة موجودة ورفعت صورة جديدة، الصورة الجديدة تكون المعتمدة.</div>
                                    <div id="main_image_existing_preview" class="server-image-selected"></div>
                                </div>

                                <div class="field">
                                    <label>صورة إضافية</label>
                                    <input type="file" name="extra_image" accept=".jpg,.jpeg,.png,.webp">
                                    <input type="hidden" name="existing_extra_image" id="existing_extra_image" value="">
                                    <button type="button" class="btn-light image-picker-btn" data-target="existing_extra_image" data-preview="extra_image_existing_preview">اختيار من الصور الموجودة</button>
                                    <div id="extra_image_existing_preview" class="server-image-selected"></div>
                                </div>

                            </div>
                        </div>
                    </div>

                    <div class="card-box">
                        <div class="card-head">
                            <h3>أنواع المنتج الفرعية</h3>
                            <span>تقدر تربطه بأكثر من Product Type</span>
                        </div>
                        <div class="card-body">
                            <div class="chips-box" id="productTypesBox">
                                <?php foreach ($productTypes as $type): ?>
                                    <div class="chip-option" data-category-id="<?= (int)$type['category_id'] ?>">
                                        <input
                                            type="checkbox"
                                            name="product_type_ids[]"
                                            value="<?= (int)$type['id'] ?>"
                                            id="ptype_<?= (int)$type['id'] ?>"
                                            <?= (!empty($old['product_type_ids']) && in_array($type['id'], (array)$old['product_type_ids'])) ? 'checked' : '' ?>
                                        >
                                        <label for="ptype_<?= (int)$type['id'] ?>"><?= e($type['name']) ?></label>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            <div class="helper" style="margin-top:12px;">الأنواع راح تنفلتر تلقائياً حسب التصنيف المختار.</div>
                        </div>
                    </div>

                    <div class="card-box">
                        <div class="card-head">
                            <h3>التسعير والمخزون</h3>
                            <span>إما منتج بسيط أو منتج بفاريانتات فقط</span>
                        </div>
                        <div class="card-body">
                            <div class="switch-row">
                                <div class="switch-info">
                                    <strong>هذا المنتج يحتوي على Variants</strong>
                                    <span>مثل الأحجام أو الألوان أو الأنواع المختلفة</span>
                                </div>
                                <label class="toggle">
                                    <input type="checkbox" name="has_variants" id="has_variants" value="1" <?= !empty($old['has_variants']) ? 'checked' : '' ?>>
                                    <span class="toggle-slider"></span>
                                </label>
                            </div>

                            <div id="simpleProductFields">
                                <div class="form-grid-3">
                                    <div class="field">
                                        <label>السعر الأساسي</label>
                                        <input type="number" step="0.01" min="0" name="price" id="base_price" value="<?= e($old['price'] ?? '0') ?>">
                                    </div>
                                    <div class="field">
                                        <label>الكمية</label>
                                        <input type="number" min="0" name="stock_qty" id="base_stock_qty" value="<?= e($old['stock_qty'] ?? '0') ?>">
                                    </div>
                                    <div class="field">
                                        <label>تنبيه انخفاض المخزون</label>
                                        <input type="number" min="0" name="low_stock_alert" id="base_low_stock_alert" value="<?= e($old['low_stock_alert'] ?? '0') ?>">
                                    </div>
                                </div>
                                <div class="switch-row" style="margin-top:16px;">
                                    <div class="switch-info">
                                        <strong>السماح بالحجز المسبق لهذا المنتج</strong>
                                        <span>إذا نفد المخزون يبقى المنتج قابل للطلب كحجز مسبق، بشرط تفعيل السماح بالحجز المسبق للمنتجات النافدة من الإعدادات العامة.</span>
                                    </div>
                                    <label class="toggle">
                                        <input type="checkbox" name="allow_preorder" id="allow_preorder" value="1" <?= !empty($old['allow_preorder']) ? 'checked' : '' ?>>
                                        <span class="toggle-slider"></span>
                                    </label>
                                </div>
                            </div>

                            <div id="variantsSection" class="variants-wrapper">
                                <div class="switch-row">
                                    <div class="switch-info">
                                        <strong>كل الـ Variants بنفس السعر</strong>
                                        <span>إذا فعلته راح يظهر سعر واحد عام فقط</span>
                                    </div>
                                    <label class="toggle">
                                        <input type="checkbox" name="variants_same_price" id="variants_same_price" value="1" <?= isset($old['variants_same_price']) ? (!empty($old['variants_same_price']) ? 'checked' : '') : 'checked' ?>>
                                        <span class="toggle-slider"></span>
                                    </label>
                                </label>
                                </div>

                                <div id="samePriceBox">
                                    <div class="form-grid-3">
                                        <div class="field">
                                            <label>السعر العام لكل الفاريانتات</label>
                                            <input type="number" step="0.01" min="0" name="price_variants_shared" id="price_variants_shared" value="<?= e($old['price_variants_shared'] ?? $old['price'] ?? '0') ?>">
                                        </div>
                                    </div>
                                </div>

                                <div style="margin-top:18px; margin-bottom:16px;">
                                    <button type="button" class="btn-modern light" id="addVariantBtn">+ إضافة Variant</button>
                                </div>

                                <div id="variantsContainer"></div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="stack">
                    <div class="card-box">
                        <div class="card-head">
                            <h3>منطق الإتاحة الذكي</h3>
                            <span>ربط المنتج بالمستويات أو حد أدنى للسلة أو عند انخفاض الكمية</span>
                        </div>
                        <div class="card-body">
                            <div class="form-grid">
                                <div class="field">
                                    <label>وضع الإتاحة</label>
                                    <select name="access_mode" id="access_mode">
                                        <?php foreach (prd_access_modes() as $modeKey => $modeLabel): ?>
                                            <option value="<?= e($modeKey) ?>" <?= (($old['access_mode'] ?? 'all') === $modeKey) ? 'selected' : '' ?>><?= e($modeLabel) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="field">
                                    <label>نطاق التطبيق</label>
                                    <select name="access_scope" id="access_scope">
                                        <?php foreach (prd_access_scopes() as $scopeKey => $scopeLabel): ?>
                                            <option value="<?= e($scopeKey) ?>" <?= (($old['access_scope'] ?? 'always') === $scopeKey) ? 'selected' : '' ?>><?= e($scopeLabel) ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="field">
                                    <label>الحد الأدنى للسلة</label>
                                    <input type="number" step="0.01" min="0" name="access_min_subtotal" id="access_min_subtotal" value="<?= e($old['access_min_subtotal'] ?? '0') ?>">
                                </div>
                                <div class="field">
                                    <label>تفعيل بوابة الكمية المحدودة</label>
                                    <select name="low_stock_gate_enabled" id="low_stock_gate_enabled">
                                        <option value="0" <?= (($old['low_stock_gate_enabled'] ?? '0') == '0') ? 'selected' : '' ?>>لا</option>
                                        <option value="1" <?= (($old['low_stock_gate_enabled'] ?? '0') == '1') ? 'selected' : '' ?>>نعم</option>
                                    </select>
                                </div>
                                <div class="field">
                                    <label>يبدأ التقييد عندما تكون الكمية ≤</label>
                                    <input type="number" min="0" name="low_stock_gate_qty" id="low_stock_gate_qty" value="<?= e($old['low_stock_gate_qty'] ?? '0') ?>">
                                </div>
                                <div class="field full">
                                    <label>المستويات المسموحة</label>
                                    <div class="chips-box">
                                        <?php $selectedTierIds = array_map('intval', (array)($old['access_tier_ids'] ?? [])); ?>
                                        <?php foreach ($tiers as $tier): ?>
                                            <div class="chip-option">
                                                <input type="checkbox" name="access_tier_ids[]" value="<?= (int)$tier['id'] ?>" id="tier_access_<?= (int)$tier['id'] ?>" <?= in_array((int)$tier['id'], $selectedTierIds, true) ? 'checked' : '' ?>>
                                                <label for="tier_access_<?= (int)$tier['id'] ?>"><?= e($tier['title']) ?></label>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                    <div class="helper" style="margin-top:12px">للوضعين tiers / tiers_or_subtotal / tiers_and_subtotal. إذا خليت المنتج للجميع، تجاهل هذا الحقل.</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="card-box">
                        <div class="card-head">
                            <h3>إعدادات العرض</h3>
                            <span>الحالة والترتيب</span>
                        </div>
                        <div class="card-body">
                            <div class="form-grid">
                                <div class="field">
                                    <label>الحالة</label>
                                    <select name="status">
                                        <option value="1" <?= (($old['status'] ?? '1') == '1') ? 'selected' : '' ?>>مفعل</option>
                                        <option value="0" <?= (($old['status'] ?? '') == '0') ? 'selected' : '' ?>>غير مفعل</option>
                                    </select>
                                </div>

                                <div class="field">
                                    <label>الترتيب</label>
                                    <input type="number" min="0" name="sort_order" value="<?= e($old['sort_order'] ?? '0') ?>">
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="card-box">
                        <div class="card-head">
                            <h3>معاينة سريعة</h3>
                            <span>تنسيق تلقائي قبل الحفظ</span>
                        </div>
                        <div class="card-body">
                            <div class="preview-box">
                                <div class="preview-item">
                                    <strong>اسم المنتج النهائي</strong>
                                    <div id="previewName">—</div>
                                </div>
                                <div class="preview-item">
                                    <strong>Slug</strong>
                                    <div id="previewSlug">—</div>
                                </div>
                                <div class="preview-item">
                                    <strong>باركود</strong>
                                    <div id="previewSku">—</div>
                                </div>
                                <div class="preview-item">
                                    <strong>نوع المنتج</strong>
                                    <div id="previewMode">منتج بسيط</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="submit-bar">
                        <div class="submit-note">
                            تأكد من الصور والـ variants قبل الحفظ.
                        </div>
                        <div class="top-actions">
                            <a href="index.php" class="btn-modern light">إلغاء</a>
                            <button type="submit" class="btn-modern primary">حفظ المنتج</button>
                        </div>
                    </div>
                </div>

            </div>
        </form>

    </div>
</div>

<script>
    const brandSelect = document.getElementById('brand_select');
    const brandPartInput = document.getElementById('brand_part');
    const productPartInput = document.getElementById('product_part');
    const nameInput = document.getElementById('name');
    const slugInput = document.getElementById('slug');
    const skuInput = document.getElementById('sku');
    const hasVariantsInput = document.getElementById('has_variants');
    const variantsSamePriceInput = document.getElementById('variants_same_price');
    const variantsSection = document.getElementById('variantsSection');
    const simpleProductFields = document.getElementById('simpleProductFields');
    const samePriceBox = document.getElementById('samePriceBox');
    const addVariantBtn = document.getElementById('addVariantBtn');
    const variantsContainer = document.getElementById('variantsContainer');
    const categoryInput = document.getElementById('category_id');

    const previewName = document.getElementById('previewName');
    const previewSlug = document.getElementById('previewSlug');
    const previewSku = document.getElementById('previewSku');
    const previewMode = document.getElementById('previewMode');

    let variantIndex = 0;

    function normalizeArabicSlug(text) {
        return (text || '')
            .toString()
            .trim()
            .replace(/\s+/g, '-')
            .replace(/[^\u0600-\u06FFa-zA-Z0-9\-_]+/g, '-')
            .replace(/-+/g, '-')
            .replace(/^-|-$/g, '')
            .toLowerCase();
    }

    function syncProductIdentity() {
        const brand = brandSelect.value.trim();
        const product = productPartInput.value.trim();

        brandPartInput.value = brand;

        let fullName = '';
        if (brand && product) {
            fullName = brand + ' - ' + product;
        } else if (brand) {
            fullName = brand;
        } else if (product) {
            fullName = product;
        }

        nameInput.value = fullName;
        slugInput.value = normalizeArabicSlug(fullName);

        previewName.textContent = nameInput.value || '—';
        previewSlug.textContent = slugInput.value || '—';
        previewSku.textContent = skuInput.value || '—';

        document.querySelectorAll('.variant-card').forEach(updateVariantAutoFields);
    }

    function toggleMode() {
        const hasVariants = hasVariantsInput.checked;

        if (hasVariants) {
            variantsSection.classList.add('active');
            simpleProductFields.classList.add('hidden');
            previewMode.textContent = 'منتج بفاريانتات';
        } else {
            variantsSection.classList.remove('active');
            simpleProductFields.classList.remove('hidden');
            previewMode.textContent = 'منتج بسيط';
        }

        toggleVariantPriceMode();
    }

    function toggleVariantPriceMode() {
        if (!variantsSamePriceInput) return;

        const samePrice = variantsSamePriceInput.checked;
        samePriceBox.style.display = samePrice ? 'block' : 'none';

        document.querySelectorAll('.variant-price-col').forEach(col => {
            col.style.display = samePrice ? 'none' : 'block';
        });
    }

    function filterProductTypes() {
        const categoryId = categoryInput.value;
        const items = document.querySelectorAll('#productTypesBox .chip-option');

        items.forEach(item => {
            const itemCategory = item.getAttribute('data-category-id');
            if (!categoryId || itemCategory === categoryId) {
                item.style.display = '';
            } else {
                item.style.display = 'none';
                const checkbox = item.querySelector('input[type="checkbox"]');
                if (checkbox) checkbox.checked = false;
            }
        });
    }

    function createVariantCard(data = {}) {
        variantIndex++;

        const card = document.createElement('div');
        card.className = 'variant-card';
        card.innerHTML = `
            <div class="variant-top">
                <h4>Variant #${variantIndex}</h4>
                <button type="button" class="variant-remove">حذف</button>
            </div>

            <div class="form-grid-3">
                <div class="field">
                    <label>اسم الـ Variant</label>
                    <input type="text" name="variants[${variantIndex}][variant_name]" class="variant-name" placeholder="مثلاً: 40 مل / أحمر / كبير" value="${escapeHtml(data.variant_name || '')}">
                </div>

                <div class="field">
                    <label>باركود Variant</label>
                    <input type="text" name="variants[${variantIndex}][sku]" class="variant-sku" inputmode="numeric" autocomplete="off" value="${escapeHtml(data.barcode || data.sku || '')}">
                </div>

                <div class="field variant-price-col">
                    <label>السعر</label>
                    <input type="number" step="0.01" min="0" name="variants[${variantIndex}][price]" class="variant-price" value="${escapeHtml(data.price || '0')}">
                </div>

                <div class="field">
                    <label>الكمية</label>
                    <input type="number" min="0" name="variants[${variantIndex}][stock_qty]" value="${escapeHtml(data.stock_qty || '0')}">
                </div>

                <div class="field">
                    <label>تنبيه انخفاض المخزون</label>
                    <input type="number" min="0" name="variants[${variantIndex}][low_stock_alert]" value="${escapeHtml(data.low_stock_alert || '0')}">
                </div>

                <div class="field">
                    <label>الترتيب</label>
                    <input type="number" min="0" name="variants[${variantIndex}][sort_order]" value="${escapeHtml(data.sort_order || (variantIndex - 1))}">
                </div>

                <div class="field">
                    <label>صورة الـ Variant</label>
                    <input type="file" name="variant_images_${variantIndex}" accept=".jpg,.jpeg,.png,.webp">
                </div>

                <div class="field">
                    <label>الحالة</label>
                    <select name="variants[${variantIndex}][status]">
                        <option value="1" ${(String(data.status ?? '1') === '1') ? 'selected' : ''}>مفعل</option>
                        <option value="0" ${(String(data.status ?? '') === '0') ? 'selected' : ''}>غير مفعل</option>
                    </select>
                </div>
            </div>
        `;

        const removeBtn = card.querySelector('.variant-remove');
        const nameField = card.querySelector('.variant-name');

        removeBtn.addEventListener('click', function () {
            card.remove();
        });

        nameField.addEventListener('input', function () {
            updateVariantAutoFields(card);
        });

        variantsContainer.appendChild(card);
        updateVariantAutoFields(card);
        toggleVariantPriceMode();
    }

    function updateVariantAutoFields(card) {
        const variantNameField = card.querySelector('.variant-name');
        const variantSkuField = card.querySelector('.variant-sku');

        const baseName = nameInput.value.trim();
        const variantName = variantNameField.value.trim();

        if (variantSkuField.value.trim()) {
            return;
        }
        if (baseName && variantName) {
            variantSkuField.value = normalizeArabicSlug(baseName + ' ' + variantName);
        } else if (variantName) {
            variantSkuField.value = normalizeArabicSlug(variantName);
        } else {
            variantSkuField.value = normalizeArabicSlug(baseName);
        }
    }

    function escapeHtml(str) {
        return String(str).replace(/[&<>"']/g, function(m) {
            return ({
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            })[m];
        });
    }

    brandSelect.addEventListener('change', syncProductIdentity);
    productPartInput.addEventListener('input', syncProductIdentity);
    if (skuInput) {
        skuInput.addEventListener('input', function() {
            previewSku.textContent = skuInput.value || '—';
        });
    }
    hasVariantsInput.addEventListener('change', toggleMode);
    categoryInput.addEventListener('change', filterProductTypes);

    if (variantsSamePriceInput) {
        variantsSamePriceInput.addEventListener('change', toggleVariantPriceMode);
    }

    addVariantBtn.addEventListener('click', function() {
        createVariantCard();
    });

    syncProductIdentity();
    toggleMode();
    filterProductTypes();

    <?php
    $oldVariants = $old['variants'] ?? [];
    if (!empty($oldVariants) && is_array($oldVariants)):
        foreach ($oldVariants as $ov):
    ?>
        createVariantCard({
            variant_name: <?= json_encode($ov['variant_name'] ?? '', JSON_UNESCAPED_UNICODE) ?>,
            sku: <?= json_encode($ov['barcode'] ?? $ov['sku'] ?? '', JSON_UNESCAPED_UNICODE) ?>,
            price: <?= json_encode($ov['price'] ?? '0', JSON_UNESCAPED_UNICODE) ?>,
            stock_qty: <?= json_encode($ov['stock_qty'] ?? '0', JSON_UNESCAPED_UNICODE) ?>,
            low_stock_alert: <?= json_encode($ov['low_stock_alert'] ?? '0', JSON_UNESCAPED_UNICODE) ?>,
            sort_order: <?= json_encode($ov['sort_order'] ?? '0', JSON_UNESCAPED_UNICODE) ?>,
            status: <?= json_encode($ov['status'] ?? '1', JSON_UNESCAPED_UNICODE) ?>
        });
    <?php
        endforeach;
    else:
    ?>
        createVariantCard();
    <?php endif; ?>
</script>

<?php require_once '../includes/footer.php'; ?>
<script>
(function(){
    const search = document.getElementById('catalog_search');
    const results = document.getElementById('catalog_results');
    const importId = document.getElementById('import_catalog_id');
    const internalName = document.getElementById('internal_name');
    const slugInput = document.getElementById('slug');
    const skuInput = document.getElementById('sku');
    const priceInput = document.querySelector('input[name="price"]');
    const sharedPriceInput = document.querySelector('input[name="price_variants_shared"]');
    const warning = document.getElementById('catalog_warning');
    let timer = null;
    function esc(v){ return String(v ?? '').replace(/[&<>'"]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;',"'":'&#039;','"':'&quot;'}[c])); }
    function closeResults(){ results?.classList.remove('active'); }
    function applyItem(item){
        if (!item) return;
        importId.value = item.id || '';
        internalName.value = item.internal_name || '';
        search.value = item.internal_name || '';
        if (slugInput) slugInput.value = item.internal_slug || '';
        if (skuInput) skuInput.value = item.barcode || '';
        if (priceInput && Number(item.price) >= 0) priceInput.value = Math.round(Number(item.price));
        if (sharedPriceInput && Number(item.price) >= 0) sharedPriceInput.value = Math.round(Number(item.price));
        if (warning) warning.classList.toggle('active', !!item.is_used);
        closeResults();
        if (typeof updatePreview === 'function') updatePreview();
    }
    function render(items){
        if (!results) return;
        if (!items || !items.length) {
            results.innerHTML = '<div class="catalog-item"><div><strong>لا توجد نتائج</strong><small>ارفع ملف الكتالوج أو غيّر كلمة البحث</small></div></div>';
            results.classList.add('active');
            return;
        }
        results.innerHTML = items.map(item => `
            <div class="catalog-item ${item.is_used ? 'used' : ''}" data-id="${esc(item.id)}">
                <div><strong>${esc(item.internal_name)}</strong><small>${esc(item.internal_slug)} · ${esc(item.barcode)} · ${Number(item.price||0).toLocaleString()} د.ع</small></div>
                <span class="catalog-badge ${item.is_used ? 'used' : 'free'}">${item.is_used ? 'مستخدم' : 'متاح'}</span>
            </div>`).join('');
        Array.from(results.querySelectorAll('.catalog-item[data-id]')).forEach((el, idx) => el.addEventListener('click', () => applyItem(items[idx])));
        results.classList.add('active');
    }
    async function doSearch(q){
        try{
            const r = await fetch('../product_import_catalog/search.php?q=' + encodeURIComponent(q || ''), {headers:{'Accept':'application/json'}});
            const data = await r.json();
            render(data.items || []);
        }catch(e){
            if(results){ results.innerHTML = '<div class="catalog-item used"><div><strong>تعذر البحث</strong><small>راجع اتصال السيرفر</small></div></div>'; results.classList.add('active'); }
        }
    }
    if (search) {
        search.addEventListener('input', () => { clearTimeout(timer); importId.value=''; internalName.value=''; if(warning) warning.classList.remove('active'); timer=setTimeout(()=>doSearch(search.value), 250); });
        search.addEventListener('focus', () => doSearch(search.value));
        document.addEventListener('click', (e) => { if (!e.target.closest('.catalog-search-box')) closeResults(); });
    }
})();
</script>
<div class="server-image-modal" id="serverImageModal">
    <div class="server-image-box">
        <div class="server-image-head">
            <strong>اختيار صورة من الملفات</strong>
            <button type="button" class="server-image-close" id="serverImageClose">إغلاق</button>
        </div>
        <div class="server-image-grid" id="serverImageGrid"><div class="server-image-empty">جاري تحميل الصور...</div></div>
    </div>
</div>
<script>
(function(){
    const modal = document.getElementById('serverImageModal');
    const grid = document.getElementById('serverImageGrid');
    const closeBtn = document.getElementById('serverImageClose');
    const brandInput = document.getElementById('brand_part');
    let targetInputId = '';
    let previewId = '';
    function esc(v){ return String(v ?? '').replace(/[&<>'"]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;',"'":'&#039;','"':'&quot;'}[c])); }
    function openModal(){ modal?.classList.add('active'); }
    function closeModal(){ modal?.classList.remove('active'); }
    function renderFolders(folders){
        if (!folders.length) {
            grid.innerHTML = '<div class="server-image-empty">لا توجد فولدرات صور حالياً. ارفع أول صورة وسيتم إنشاء فولدر البراند تلقائياً.</div>';
            return;
        }
        grid.innerHTML = folders.map(folder => `
            <div class="server-image-item server-image-folder ${folder.is_selected_brand ? 'selected-brand' : ''}" data-folder="${esc(folder.slug)}">
                <div style="font-size:42px;line-height:78px">📁</div>
                <small>${esc(folder.name)}${folder.is_selected_brand ? ' · البراند المحدد' : ''}</small>
                <small>${Number(folder.count || 0).toLocaleString()} صورة</small>
            </div>`).join('');
        Array.from(grid.querySelectorAll('.server-image-folder')).forEach(el => {
            el.addEventListener('click', () => loadImages(el.getAttribute('data-folder') || ''));
        });
    }
    function renderImages(items, folder){
        const back = `<div class="server-image-item server-image-folder" id="serverImageBack"><div style="font-size:38px;line-height:78px">↩️</div><small>رجوع للفولدرات</small></div>`;
        if (!items.length) {
            grid.innerHTML = back + '<div class="server-image-empty">لا توجد صور داخل هذا الفولدر.</div>';
            document.getElementById('serverImageBack')?.addEventListener('click', loadFolders);
            return;
        }
        grid.innerHTML = back + items.map(item => `<div class="server-image-item" data-path="${esc(item.path)}" data-url="${esc(item.url)}"><img src="${esc(item.url)}" alt=""><small>${esc(item.name || item.path)}</small></div>`).join('');
        document.getElementById('serverImageBack')?.addEventListener('click', loadFolders);
        Array.from(grid.querySelectorAll('.server-image-item[data-path]')).forEach(el => {
            el.addEventListener('click', () => {
                const input = document.getElementById(targetInputId);
                const preview = document.getElementById(previewId);
                const path = el.getAttribute('data-path') || '';
                const url = el.getAttribute('data-url') || '';
                if (input) input.value = path;
                if (preview) preview.innerHTML = `<img src="${esc(url)}" alt=""> تم اختيار: ${esc(path)}`;
                closeModal();
            });
        });
    }
    async function loadFolders(){
        if (!grid) return;
        grid.innerHTML = '<div class="server-image-empty">جاري تحميل الفولدرات...</div>';
        try{
            const brand = brandInput ? brandInput.value : '';
            const res = await fetch('image_library.php?mode=folders&brand=' + encodeURIComponent(brand), {headers:{'Accept':'application/json'}});
            const data = await res.json();
            renderFolders(data.folders || []);
        }catch(e){
            grid.innerHTML = '<div class="server-image-empty">تعذر تحميل فولدرات الصور من السيرفر.</div>';
        }
    }
    async function loadImages(folder){
        if (!grid) return;
        grid.innerHTML = '<div class="server-image-empty">جاري تحميل صور الفولدر...</div>';
        try{
            const brand = brandInput ? brandInput.value : '';
            const res = await fetch('image_library.php?mode=images&brand=' + encodeURIComponent(brand) + '&folder=' + encodeURIComponent(folder), {headers:{'Accept':'application/json'}});
            const data = await res.json();
            renderImages(data.items || [], folder);
        }catch(e){
            grid.innerHTML = '<div class="server-image-empty">تعذر تحميل الصور من السيرفر.</div>';
        }
    }
    Array.from(document.querySelectorAll('.image-picker-btn')).forEach(btn => {
        btn.addEventListener('click', () => {
            targetInputId = btn.getAttribute('data-target') || '';
            previewId = btn.getAttribute('data-preview') || '';
            openModal();
            loadFolders();
        });
    });
    closeBtn?.addEventListener('click', closeModal);
    modal?.addEventListener('click', e => { if (e.target === modal) closeModal(); });
})();
</script>
