<?php

use Core\App\Models\HomeSections;
use Core\App\Models\CategoryModel;

$categories    = (new CategoryModel())->getAll();
$sectionsModel = new HomeSections();
$sections      = $sectionsModel->getAll();

$hasTopBar = $hasHero = $hasProducts = $hasAds = $hasFaq = false;
foreach ($sections as $s) {
    if ($s['section_type'] === 'top_bar')         $hasTopBar   = true;
    if ($s['section_type'] === 'hero_slider')      $hasHero     = true;
    if ($s['section_type'] === 'products_section') $hasProducts = true;
    if ($s['section_type'] === 'ads_section')      $hasAds      = true;
    if ($s['section_type'] === 'faq_section')      $hasFaq      = true;
}

include __DIR__ . '/../header.php';
?>

<div class="admin-page container-fluid py-3" style="max-width:860px;">

    <div class="d-flex align-items-center gap-3 mb-4">
        <a href="/admin/home-sections" class="btn btn-sm btn-outline-secondary">
            <i class="bi bi-arrow-right"></i>
        </a>
        <h1 class="h5 mb-0 fw-bold"><?= __('homepage.add_section', 'Add Section') ?></h1>
    </div>

    <form method="post"
          action="/admin/home-sections/store"
          enctype="multipart/form-data"
          id="hsCreateForm">
        <?= \Core\System\Csrf::field(); ?>

        <!-- ══ Section Type + Enable (card) ══════════════════════════════ -->
        <div class="card mb-4 shadow-sm">
            <div class="card-body">
                <div class="row g-3 align-items-end">
                    <div class="col-md-8">
                        <label class="form-label fw-semibold mb-1">
                            <?= __('homepage.section_type', 'Section Type') ?>
                        </label>
                        <select name="section_type" class="form-select" id="hsTypeSelect" required>
                            <option value="top_bar"          <?= $hasTopBar   ? 'disabled' : '' ?>>
                                <?= __('homepage.section.top_bar',  'Top Bar') ?><?= $hasTopBar   ? ' — (مضاف مسبقاً)' : '' ?>
                            </option>
                            <option value="hero_slider"      <?= $hasHero     ? 'disabled' : '' ?>>
                                <?= __('homepage.section.hero',     'Hero / Slider') ?><?= $hasHero     ? ' — (مضاف مسبقاً)' : '' ?>
                            </option>
                            <option value="products_section" <?= $hasProducts ? 'disabled' : '' ?>>
                                <?= __('homepage.section.products', 'Products Section') ?><?= $hasProducts ? ' — (مضاف مسبقاً)' : '' ?>
                            </option>
                            <option value="ads_section"      <?= $hasAds      ? 'disabled' : '' ?>>
                                <?= __('homepage.section.ads',      'Ads Section') ?><?= $hasAds      ? ' — (مضاف مسبقاً)' : '' ?>
                            </option>
                            <option value="faq_section"      <?= $hasFaq      ? 'disabled' : '' ?>>
                                <?= __('homepage.section.faq',      'FAQ Section') ?><?= $hasFaq      ? ' — (مضاف مسبقاً)' : '' ?>
                            </option>
                        </select>
                        <?php if ($hasTopBar || $hasHero || $hasProducts || $hasAds || $hasFaq): ?>
                            <div class="form-text"><?= __('homepage.section.limit_note', 'Only one instance of each section type is allowed.') ?></div>
                        <?php endif; ?>
                    </div>
                    <div class="col-md-4">
                        <div class="form-check form-switch mt-2">
                            <input class="form-check-input" type="checkbox" name="is_enabled" value="1" id="hsEnabled" checked>
                            <label class="form-check-label fw-semibold" for="hsEnabled">
                                <?= __('homepage.section_enabled', 'Enable Section') ?>
                            </label>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- ══ TOP BAR ═══════════════════════════════════════════════════ -->
        <div class="hs-panel" data-panel="top_bar">
            <div class="card shadow-sm mb-4">
                <div class="card-header fw-semibold bg-light">
                    <i class="bi bi-bar-chart-steps me-2 text-primary"></i>
                    <?= __('homepage.top_bar.settings', 'Top Bar Settings') ?>
                </div>
                <div class="card-body">
                    <label class="form-label">
                        <?= __('homepage.top_bar.messages', 'Messages (one per line)') ?>
                        <span class="text-muted fw-normal small ms-1"><?= __('homepage.top_bar.messages_hint','Each line = one scrolling message') ?></span>
                    </label>
                    <textarea name="settings[messages]" class="form-control font-monospace" rows="5"
                              placeholder="شحن سريع&#10;الدفع عند الاستلام&#10;دعم 24/7"></textarea>
                </div>
            </div>
        </div>

        <!-- ══ HERO / SLIDER ═════════════════════════════════════════════ -->
        <div class="hs-panel" data-panel="hero_slider" hidden>
            <div class="card shadow-sm mb-4">
                <div class="card-header fw-semibold bg-light">
                    <i class="bi bi-images me-2 text-primary"></i>
                    <?= __('homepage.hero.settings', 'Hero / Slider Slides') ?>
                </div>
                <div class="card-body p-3">

                    <div id="hsSlidesList"></div>

                    <button type="button" class="btn btn-outline-primary btn-sm" id="hsAddSlide">
                        <i class="bi bi-plus-lg me-1"></i><?= __('homepage.hero.add_slide', 'Add Slide') ?>
                    </button>

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

        <!-- ══ PRODUCTS SECTION ══════════════════════════════════════════ -->
        <div class="hs-panel" data-panel="products_section" hidden>
            <div class="card shadow-sm mb-4">
                <div class="card-header fw-semibold bg-light">
                    <i class="bi bi-grid me-2 text-primary"></i>
                    <?= __('homepage.products.settings', 'Products Section Settings') ?>
                </div>
                <div class="card-body">

                    <div class="mb-3">
                        <label class="form-label"><?= __('homepage.products.title', 'Section Title') ?></label>
                        <input type="text" name="settings[title]" class="form-control"
                               placeholder="<?= __('homepage.products.title_placeholder','e.g. Latest Arrivals') ?>">
                    </div>

                    <div class="mb-3">
                        <label class="form-label"><?= __('homepage.products.subtitle', 'Section Subtitle') ?></label>
                        <input type="text" name="settings[subtitle]" class="form-control">
                    </div>

                    <div class="mb-3">
                        <label class="form-label"><?= __('homepage.products.source', 'Products Source') ?></label>
                        <select name="settings[source]" class="form-select" id="hsProdSource">
                            <option value="latest"><?= __('homepage.products.source.latest', 'Latest Products') ?></option>
                            <option value="featured"><?= __('homepage.products.source.featured', 'Featured Products') ?></option>
                            <option value="category"><?= __('homepage.products.source.category', 'From Category') ?></option>
                        </select>
                    </div>

                    <div class="mb-3" id="hsProdCategoryWrap" hidden>
                        <label class="form-label"><?= __('homepage.products.category', 'Category') ?></label>
                        <select name="settings[category_id]" class="form-select" id="hsProdCategorySelect">
                            <option value=""><?= __('homepage.products.category_optional', 'Select category') ?></option>
                            <?php foreach ($categories as $cat): ?>
                                <?php if (($cat['status'] ?? 'active') !== 'active') continue; ?>
                                <option value="<?= (int)$cat['id'] ?>"><?= htmlspecialchars($cat['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

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

        <!-- ══ ADS SECTION ══════════════════════════════════════════════ -->
        <div class="hs-panel" data-panel="ads_section" hidden>
            <div class="card shadow-sm mb-4">
                <div class="card-header fw-semibold bg-light">
                    <i class="bi bi-megaphone me-2 text-primary"></i>
                    <?= __('homepage.ads.settings', 'Ads Section Settings') ?>
                </div>
                <div class="card-body p-3">

                    <!-- Ad #1 -->
                    <div class="border rounded p-3 mb-3 hs-ad-block">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <span class="fw-semibold"><?= __('homepage.ads.ad', 'Ad') ?> #1</span>
                        </div>
                        <?= hs_ad_fields(0) ?>
                    </div>

                    <!-- زر إضافة الإعلان الثاني -->
                    <div id="hsAddAd2Wrap">
                        <button type="button" class="btn btn-outline-secondary btn-sm" id="hsAddAd2">
                            <i class="bi bi-plus-lg me-1"></i><?= __('homepage.ads.add_second', 'Add second ad') ?>
                        </button>
                    </div>

                    <!-- Ad #2 (مخفي في البداية) -->
                    <div id="hsAd2Block" hidden>
                        <div class="border rounded p-3 mt-3 hs-ad-block">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <span class="fw-semibold"><?= __('homepage.ads.ad', 'Ad') ?> #2</span>
                                <button type="button" class="btn btn-sm btn-outline-danger" id="hsRemoveAd2">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </div>
                            <?= hs_ad_fields(1) ?>
                        </div>
                    </div>

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

        <!-- ══ FAQ SECTION ══════════════════════════════════════════════ -->
        <div class="hs-panel" data-panel="faq_section" hidden>
            <div class="card shadow-sm mb-4">
                <div class="card-header fw-semibold bg-light">
                    <i class="bi bi-question-circle me-2 text-primary"></i>
                    <?= __('homepage.faq.settings', 'FAQ Settings') ?>
                </div>
                <div class="card-body">

                    <div class="mb-3">
                        <label class="form-label"><?= __('homepage.faq.subtitle', 'Section Description') ?></label>
                        <input type="text" name="settings[subtitle]" class="form-control">
                    </div>

                    <div id="hsFaqList"></div>

                    <button type="button" class="btn btn-outline-primary btn-sm" id="hsAddFaq">
                        <i class="bi bi-plus-lg me-1"></i><?= __('homepage.faq.add_question', 'Add Question') ?>
                    </button>

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

        <!-- ══ Buttons ═══════════════════════════════════════════════════ -->
        <div class="d-flex gap-2 mt-2">
            <button type="submit" class="btn btn-primary px-4">
                <i class="bi bi-check-lg me-1"></i><?= __('common.save', 'Save') ?>
            </button>
            <a href="/admin/home-sections" class="btn btn-outline-secondary">
                <?= __('common.cancel', 'Cancel') ?>
            </a>
        </div>

    </form>
</div>

<?php
/* ── helper: حقول إعلان واحد ──────────────────────────────────────── */
function hs_ad_fields(int $i, array $ad = []): string {
    $headline      = htmlspecialchars($ad['headline'] ?? '', ENT_QUOTES);
    $image         = htmlspecialchars($ad['image'] ?? '', ENT_QUOTES);
    $animated      = htmlspecialchars(implode("\n", $ad['animated_texts'] ?? []), ENT_QUOTES);
    $btn_url       = htmlspecialchars($ad['button_url'] ?? '#', ENT_QUOTES);
    $img_label     = __('homepage.ads.image', 'Image');
    $img_url_ph    = __('homepage.ads.image_url', 'Or image URL');
    $headline_label= __('homepage.ads.headline', 'Headline');
    $anim_label    = __('homepage.ads.animated_texts', 'Animated Texts (one per line)');
    $btn_label     = __('homepage.ads.button_url', 'Button URL');
    $has_img       = !empty($ad['image']);

    return "
        <div class='mb-3'>
            <label class='form-label'>{$headline_label}</label>
            <input type='text' name='settings[ads][{$i}][headline]' class='form-control' value='{$headline}'>
        </div>
        <div class='mb-3'>
            <label class='form-label'>{$img_label}</label>
            <div class='hs-img-wrap mb-2'" . ($has_img ? '' : " style='display:none'") . ">
                <img src='{$image}' class='hs-preview rounded' style='max-height:100px;border:1px solid #dee2e6;padding:3px;'>
            </div>
            <input type='file' name='ads_images[{$i}]' class='form-control mb-2 hs-file' accept='image/*' data-preview-index='{$i}'>
            <input type='text' name='settings[ads][{$i}][image]' class='form-control hs-url' value='{$image}' placeholder='{$img_url_ph}'>
        </div>
        <div class='mb-3'>
            <label class='form-label'>{$anim_label}</label>
            <textarea name='settings[ads][{$i}][animated_texts]' class='form-control' rows='3'>{$animated}</textarea>
        </div>
        <div class='mb-3'>
            <label class='form-label'>{$btn_label}</label>
            <input type='text' name='settings[ads][{$i}][button_url]' class='form-control' value='{$btn_url}'>
        </div>
    ";
}
?>

<script>
(function () {
'use strict';

/* ══════════════════════════════════════════════════════════════════
   1. ضغط الصورة client-side (max 4 MB, max 1920px)
══════════════════════════════════════════════════════════════════ */
function compressImage(file, cb) {
    var MAX = 4 * 1024 * 1024;
    if (file.size <= MAX) { cb(file); return; }

    var reader = new FileReader();
    reader.onload = function (e) {
        var img = new Image();
        img.onload = function () {
            var D = 1920, w = img.width, h = img.height;
            if (w > D || h > D) {
                if (w > h) { h = Math.round(h * D / w); w = D; }
                else       { w = Math.round(w * D / h); h = D; }
            }
            var c = document.createElement('canvas');
            c.width = w; c.height = h;
            c.getContext('2d').drawImage(img, 0, 0, w, h);
            (function tryQ(q) {
                c.toBlob(function (blob) {
                    if (!blob) { cb(file); return; }
                    if (blob.size > MAX && q > 0.4) { tryQ(+(q - 0.08).toFixed(2)); return; }
                    cb(new File([blob], file.name, { type: blob.type, lastModified: Date.now() }));
                }, 'image/jpeg', q);
            })(0.82);
        };
        img.src = e.target.result;
    };
    reader.readAsDataURL(file);
}

/* ══════════════════════════════════════════════════════════════════
   2. ربط المعاينة + الضغط لأي file input
      يجد .hs-img-wrap و .hs-url داخل نفس .mb-3 الأب
══════════════════════════════════════════════════════════════════ */
function bindFileInput(input) {
    if (input._hsBound) return;
    input._hsBound = true;

    var mb3     = input.closest('.mb-3');
    var wrap    = mb3 && mb3.querySelector('.hs-img-wrap');
    var preview = wrap && wrap.querySelector('.hs-preview');
    var urlInp  = mb3 && mb3.querySelector('.hs-url');

    function show(src) {
        if (!wrap || !preview) return;
        if (src) { preview.src = src; wrap.style.display = ''; }
        else     { wrap.style.display = 'none'; preview.src = ''; }
    }

    input.addEventListener('change', function () {
        var f = this.files && this.files[0];
        if (!f) { show(urlInp ? urlInp.value.trim() : ''); return; }
        if (urlInp) urlInp.value = '';

        compressImage(f, function (compressed) {
            if (compressed !== f) {
                var dt = new DataTransfer();
                dt.items.add(compressed);
                input.files = dt.files;
            }
            var r = new FileReader();
            r.onload = function (ev) { show(ev.target.result); };
            r.readAsDataURL(compressed);
        });
    });

    if (urlInp) {
        urlInp.addEventListener('input', function () {
            if (!input.files || !input.files[0]) show(this.value.trim());
        });
        if (urlInp.value.trim()) show(urlInp.value.trim());
    }
}

/* ربط كل ملفات الصفحة الحالية + المضافة لاحقاً */
function bindAll(root) {
    (root || document).querySelectorAll('.hs-file').forEach(bindFileInput);
}

/* ══════════════════════════════════════════════════════════════════
   3. إظهار/إخفاء الأقسام — بدون disabled كلي
      نُخفي الـ fieldset وبس، ونتحقق في submit من النوع الصحيح
══════════════════════════════════════════════════════════════════ */
var typeSelect = document.getElementById('hsTypeSelect');
var panels     = document.querySelectorAll('.hs-panel');

function showPanel() {
    var active = typeSelect.value;
    panels.forEach(function (p) {
        p.hidden = p.dataset.panel !== active;
    });
}
typeSelect.addEventListener('change', showPanel);
showPanel();

/* ══════════════════════════════════════════════════════════════════
   4. Products: إظهار قائمة التصنيف
══════════════════════════════════════════════════════════════════ */
var prodSource  = document.getElementById('hsProdSource');
var prodCatWrap = document.getElementById('hsProdCategoryWrap');
var prodCatSel  = document.getElementById('hsProdCategorySelect');

if (prodSource) {
    function toggleCat() {
        var isCat = prodSource.value === 'category';
        prodCatWrap.hidden = !isCat;
        if (isCat) { prodCatSel.setAttribute('required','required'); }
        else       { prodCatSel.removeAttribute('required'); prodCatSel.value = ''; }
    }
    prodSource.addEventListener('change', toggleCat);
    toggleCat();
}

/* ══════════════════════════════════════════════════════════════════
   5. Hero Slides: إضافة + حذف — يبني HTML مباشرة
      الـ slide الأول يُبنى بـ JS أيضاً حتى لا يكون هناك فرق بين الأول والباقي
══════════════════════════════════════════════════════════════════ */
var slideList  = document.getElementById('hsSlidesList');
var addSlideBtn = document.getElementById('hsAddSlide');
var slideCount = 0;

function slideTitle(i) {
    return '<?= __('homepage.hero.slide','Slide') ?> #' + (i + 1);
}

function buildSlideHTML(i) {
    return '<div class="border rounded p-3 mb-3 hs-slide" data-si="' + i + '">' +
        '<div class="d-flex justify-content-between align-items-center mb-3">' +
            '<span class="fw-semibold small">' + slideTitle(i) + '</span>' +
            '<button type="button" class="btn btn-sm btn-outline-danger hs-rm-slide"><i class="bi bi-trash"></i></button>' +
        '</div>' +
        '<div class="row g-3">' +
            '<div class="col-md-6">' +
                '<label class="form-label"><?= __('homepage.hero.title','Title') ?></label>' +
                '<input type="text" name="settings[slides][' + i + '][title]" class="form-control">' +
            '</div>' +
            '<div class="col-md-6">' +
                '<label class="form-label"><?= __('homepage.hero.image','Image') ?></label>' +
                '<div class="mb-3">' +
                    '<div class="hs-img-wrap mb-2" style="display:none"><img src="" class="hs-preview rounded" style="max-height:90px;border:1px solid #dee2e6;padding:3px;"></div>' +
                    '<input type="file" name="slides_images[' + i + ']" class="form-control mb-2 hs-file" accept="image/*">' +
                    '<input type="text" name="settings[slides][' + i + '][image]" class="form-control hs-url" placeholder="<?= __('homepage.hero.image_url','Or image URL') ?>">' +
                '</div>' +
            '</div>' +
            '<div class="col-12">' +
                '<label class="form-label"><?= __('homepage.hero.subtitle','Subtitle') ?></label>' +
                '<textarea name="settings[slides][' + i + '][subtitle]" class="form-control" rows="2"></textarea>' +
            '</div>' +
            '<div class="col-md-6">' +
                '<label class="form-label"><?= __('homepage.hero.button_text','Button Text') ?></label>' +
                '<input type="text" name="settings[slides][' + i + '][button_text]" class="form-control">' +
            '</div>' +
            '<div class="col-md-6">' +
                '<label class="form-label"><?= __('homepage.hero.button_url','Button URL') ?></label>' +
                '<input type="text" name="settings[slides][' + i + '][button_url]" class="form-control">' +
            '</div>' +
        '</div>' +
    '</div>';
}

function addSlide() {
    var i = slideCount++;
    var div = document.createElement('div');
    div.innerHTML = buildSlideHTML(i);
    var node = div.firstElementChild;
    slideList.appendChild(node);
    bindAll(node);
}

// ابدأ بـ slide واحد تلقائياً
addSlide();

if (addSlideBtn) {
    addSlideBtn.addEventListener('click', addSlide);
}

slideList.addEventListener('click', function (e) {
    var btn = e.target.closest('.hs-rm-slide');
    if (btn) btn.closest('.hs-slide').remove();
});

/* ══════════════════════════════════════════════════════════════════
   6. Ads: إظهار/إخفاء الإعلان الثاني
══════════════════════════════════════════════════════════════════ */
var addAd2Btn   = document.getElementById('hsAddAd2');
var ad2Block    = document.getElementById('hsAd2Block');
var addAd2Wrap  = document.getElementById('hsAddAd2Wrap');
var removeAd2   = document.getElementById('hsRemoveAd2');

if (addAd2Btn) {
    addAd2Btn.addEventListener('click', function () {
        ad2Block.hidden = false;
        addAd2Wrap.hidden = true;
        bindAll(ad2Block);
    });
}
if (removeAd2) {
    removeAd2.addEventListener('click', function () {
        ad2Block.hidden = true;
        addAd2Wrap.hidden = false;
        // نفرّغ حقول الإعلان الثاني
        ad2Block.querySelectorAll('input[type=text], textarea').forEach(function(el){ el.value = ''; });
        ad2Block.querySelectorAll('input[type=file]').forEach(function(el){ el.value = ''; });
        ad2Block.querySelectorAll('.hs-img-wrap').forEach(function(el){ el.style.display='none'; });
    });
}

/* ══════════════════════════════════════════════════════════════════
   7. FAQ: إضافة + حذف
══════════════════════════════════════════════════════════════════ */
var faqList  = document.getElementById('hsFaqList');
var addFaqBtn = document.getElementById('hsAddFaq');
var faqCount = 0;

function buildFaqHTML(i) {
    return '<div class="border rounded p-3 mb-3 hs-faq">' +
        '<div class="d-flex justify-content-between align-items-center mb-3">' +
            '<span class="fw-semibold small"><?= __('homepage.faq.question','Question') ?> #' + (i + 1) + '</span>' +
            '<button type="button" class="btn btn-sm btn-outline-danger hs-rm-faq"><i class="bi bi-trash"></i></button>' +
        '</div>' +
        '<div class="mb-3">' +
            '<label class="form-label"><?= __('homepage.faq.question','Question') ?></label>' +
            '<input type="text" name="settings[items][' + i + '][question]" class="form-control">' +
        '</div>' +
        '<div class="mb-3">' +
            '<label class="form-label"><?= __('homepage.faq.answer','Answer') ?></label>' +
            '<textarea name="settings[items][' + i + '][answer]" class="form-control" rows="4"></textarea>' +
        '</div>' +
    '</div>';
}

function addFaq() {
    var div = document.createElement('div');
    div.innerHTML = buildFaqHTML(faqCount++);
    faqList.appendChild(div.firstElementChild);
}

// سؤال واحد تلقائياً
addFaq();

if (addFaqBtn) addFaqBtn.addEventListener('click', addFaq);

faqList.addEventListener('click', function (e) {
    var btn = e.target.closest('.hs-rm-faq');
    if (btn) btn.closest('.hs-faq').remove();
});

/* ══════════════════════════════════════════════════════════════════
   8. ربط file inputs الموجودة الآن (ads_section المبنية بـ PHP)
══════════════════════════════════════════════════════════════════ */
bindAll();

/* ══════════════════════════════════════════════════════════════════
   9. Validation عند الإرسال
══════════════════════════════════════════════════════════════════ */
document.getElementById('hsCreateForm').addEventListener('submit', function (e) {
    var type = typeSelect.value;

    if (type === 'hero_slider') {
        var hasImg = false;
        slideList.querySelectorAll('.hs-file').forEach(function(fi){ if (fi.files && fi.files.length) hasImg = true; });
        slideList.querySelectorAll('.hs-url').forEach(function(ui){ if (ui.value.trim()) hasImg = true; });
        if (!hasImg) {
            e.preventDefault();
            alert('<?= __('homepage.hero.validation_image_required', 'Please add at least one slide image (upload or URL).') ?>');
            return;
        }
    }

    if (type === 'ads_section') {
        var ad1File = document.querySelector('[name="ads_images[0]"]');
        var ad1Url  = document.querySelector('[name="settings[ads][0][image]"]');
        if ((!ad1File || !ad1File.files.length) && (!ad1Url || !ad1Url.value.trim())) {
            e.preventDefault();
            alert('<?= __('homepage.ads.validation_image_required', 'Please add an ad image (upload or URL).') ?>');
            return;
        }
    }

    if (type === 'products_section' && prodSource && prodSource.value === 'category' && prodCatSel && !prodCatSel.value) {
        e.preventDefault();
        alert('<?= __('homepage.products.validation_category_required', 'Please select a category.') ?>');
    }
});

})();
</script>

<?php include __DIR__ . '/../footer.php'; ?>
