<?php $isEdit = !is_null($item); ?>

<div class="page-header">
    <div>
        <h1><?= $isEdit ? 'Edit Menu Item' : 'Add Menu Item' ?></h1>
        <p><?= $isEdit ? 'Update item details, pricing and variants.' : 'Add a new item to your menu.' ?></p>
    </div>
    <a href="<?= url('menu') ?>" class="btn btn-outline-secondary">
        <i class="bi bi-arrow-left me-1"></i> Back to Menu
    </a>
</div>

<form method="POST"
      action="<?= $isEdit ? url('menu/' . $item['id'] . '/update') : url('menu/store') ?>"
      enctype="multipart/form-data"
      class="fd-form"
      novalidate>
    <?= csrf_field() ?>

<div class="row g-4">

    <!-- LEFT COLUMN -->
    <div class="col-12 col-lg-8">

        <!-- Basic Info -->
        <div class="card mb-4">
            <div class="card-header">
                <i class="bi bi-info-circle text-accent"></i>
                <h6 class="card-title">Item Details</h6>
            </div>
            <div class="card-body">

                <div class="row g-3">
                    <div class="col-12 col-md-8">
                        <label class="form-label" for="name">Item Name <span class="text-danger">*</span></label>
                        <input type="text" id="name" name="name" class="form-control"
                               placeholder="e.g. Chicken Tikka Pizza"
                               value="<?= e($isEdit ? $item['name'] : \Core\Request::post('name','')) ?>"
                               maxlength="150" required>
                    </div>
                    <div class="col-12 col-md-4">
                        <label class="form-label" for="category_id">Category <span class="text-danger">*</span></label>
                        <select id="category_id" name="category_id" class="form-select" required>
                            <option value="">Select category…</option>
                            <?php foreach ($categories as $cat): ?>
                            <option value="<?= $cat['id'] ?>"
                                <?= ($isEdit ? $item['category_id'] : \Core\Request::post('category_id')) == $cat['id'] ? 'selected' : '' ?>>
                                <?= e($cat['name']) ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-12">
                        <label class="form-label" for="description">Description</label>
                        <textarea id="description" name="description" class="form-control"
                                  rows="3" placeholder="Briefly describe this item…"
                                  maxlength="500"><?= e($isEdit ? $item['description'] : '') ?></textarea>
                    </div>
                </div>

            </div>
        </div>

        <!-- Pricing & Settings -->
        <div class="card mb-4">
            <div class="card-header">
                <i class="bi bi-currency-dollar text-accent"></i>
                <h6 class="card-title">Pricing & Settings</h6>
            </div>
            <div class="card-body">
                <div class="row g-3">
                    <div class="col-12 col-md-4">
                        <label class="form-label" for="base_price">
                            Base Price <span class="text-danger">*</span>
                            <span class="text-secondary fw-400" style="font-size:.75rem;">(<?= e($currencySymbol) ?>)</span>
                        </label>
                        <input type="number" id="base_price" name="base_price" class="form-control"
                               placeholder="0.00" min="0" step="0.01"
                               value="<?= e($isEdit ? number_format((float)$item['base_price'], 2, '.', '') : '0.00') ?>"
                               required>
                        <div class="form-text">Base price before variant modifiers.</div>
                    </div>
                    <div class="col-12 col-md-4">
                        <label class="form-label" for="sort_order">Display Order</label>
                        <input type="number" id="sort_order" name="sort_order" class="form-control"
                               min="0" max="999" value="<?= e($isEdit ? $item['sort_order'] : '0') ?>">
                    </div>
                    <div class="col-12 col-md-4 d-flex align-items-end pb-1">
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" id="is_available"
                                   name="is_available" value="1"
                                   <?= (!$isEdit || $item['is_available']) ? 'checked' : '' ?>>
                            <label class="form-check-label fw-600" for="is_available">
                                Available to order
                            </label>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Variants / Choice Groups -->
        <div class="card mb-4">
            <div class="card-header">
                <i class="bi bi-sliders text-accent"></i>
                <h6 class="card-title">Variants & Choices</h6>
                <span class="text-secondary ms-2" style="font-size:.75rem;">e.g. Size: Small / Medium / Large</span>
                <button type="button" class="btn btn-sm btn-outline-accent ms-auto" id="addGroupBtn">
                    <i class="bi bi-plus-lg me-1"></i> Add Group
                </button>
            </div>
            <div class="card-body" id="choiceGroupsContainer">

                <?php if (empty($groups)): ?>
                <div id="noGroupsMsg" class="text-center py-4 text-secondary">
                    <i class="bi bi-sliders fs-2 d-block mb-2 opacity-25"></i>
                    <p class="mb-0" style="font-size:.85rem;">No variants added. Click <strong>Add Group</strong> to add size, crust type, extras, etc.</p>
                </div>
                <?php else: ?>
                <div id="noGroupsMsg" class="d-none"></div>
                <?php endif; ?>

                <?php foreach ($groups as $gi => $group): ?>
                <div class="choice-group card border mb-3" data-group-index="<?= $gi ?>">
                    <div class="card-body pb-2">
                        <div class="row g-2 mb-3 align-items-center">
                            <div class="col-12 col-md-4">
                                <label class="form-label mb-1" style="font-size:.8rem;">Group Name <span class="text-danger">*</span></label>
                                <input type="text" name="groups[<?= $gi ?>][name]"
                                       class="form-control form-control-sm"
                                       placeholder="e.g. Size, Crust, Extras"
                                       value="<?= e($group['name']) ?>" required>
                            </div>
                            <div class="col-6 col-md-2">
                                <label class="form-label mb-1" style="font-size:.8rem;">Min Select</label>
                                <input type="number" name="groups[<?= $gi ?>][min_select]"
                                       class="form-control form-control-sm" min="0" max="10"
                                       value="<?= $group['min_select'] ?>">
                            </div>
                            <div class="col-6 col-md-2">
                                <label class="form-label mb-1" style="font-size:.8rem;">Max Select</label>
                                <input type="number" name="groups[<?= $gi ?>][max_select]"
                                       class="form-control form-control-sm" min="1" max="10"
                                       value="<?= $group['max_select'] ?>">
                            </div>
                            <div class="col-6 col-md-2 d-flex align-items-end pb-1">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox"
                                           name="groups[<?= $gi ?>][is_required]" value="1"
                                           id="req_<?= $gi ?>"
                                           <?= $group['is_required'] ? 'checked' : '' ?>>
                                    <label class="form-check-label" for="req_<?= $gi ?>" style="font-size:.8rem;">Required</label>
                                </div>
                            </div>
                            <div class="col-6 col-md-2 text-end d-flex align-items-end justify-content-end pb-1">
                                <button type="button" class="btn btn-sm btn-outline-danger remove-group-btn">
                                    <i class="bi bi-trash"></i> Remove
                                </button>
                            </div>
                        </div>

                        <!-- Choices inside this group -->
                        <div class="choices-container">
                            <div class="d-flex align-items-center mb-2">
                                <span style="font-size:.78rem;font-weight:600;color:var(--text-secondary);text-transform:uppercase;letter-spacing:.5px;">
                                    Choices
                                </span>
                                <button type="button" class="btn btn-sm btn-link ms-2 p-0 add-choice-btn"
                                        data-group="<?= $gi ?>" style="font-size:.8rem;">
                                    <i class="bi bi-plus-circle me-1"></i>Add Choice
                                </button>
                            </div>

                            <?php foreach ($group['choices'] as $ci => $choice): ?>
                            <div class="row g-2 mb-2 choice-row align-items-center">
                                <div class="col-12 col-md-4">
                                    <input type="text" name="groups[<?= $gi ?>][choices][<?= $ci ?>][label]"
                                           class="form-control form-control-sm"
                                           placeholder="e.g. Large" value="<?= e($choice['label']) ?>" required>
                                </div>
                                <div class="col-6 col-md-3">
                                    <div class="input-group input-group-sm">
                                        <span class="input-group-text">+</span>
                                        <input type="number" name="groups[<?= $gi ?>][choices][<?= $ci ?>][price_modifier]"
                                               class="form-control" placeholder="0.00"
                                               step="0.01" min="0"
                                               value="<?= number_format((float)$choice['price_modifier'], 2, '.', '') ?>">
                                    </div>
                                </div>
                                <div class="col-4 col-md-3">
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox"
                                               name="groups[<?= $gi ?>][choices][<?= $ci ?>][is_default]"
                                               value="1" <?= $choice['is_default'] ? 'checked' : '' ?>>
                                        <label class="form-check-label" style="font-size:.8rem;">Default</label>
                                    </div>
                                </div>
                                <div class="col-2 col-md-2 text-end">
                                    <button type="button" class="btn btn-sm btn-outline-danger remove-choice-btn p-1">
                                        <i class="bi bi-x-lg"></i>
                                    </button>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>

            </div>
        </div>

    </div>

    <!-- RIGHT COLUMN -->
    <div class="col-12 col-lg-4">

        <!-- Image Upload -->
        <div class="card mb-4">
            <div class="card-header">
                <i class="bi bi-image text-accent"></i>
                <h6 class="card-title">Item Image</h6>
            </div>
            <div class="card-body text-center">
                <div style="position:relative;display:inline-block;margin-bottom:16px;">
                    <img id="itemImgPreview"
                         src="<?= $isEdit && $item['item_image'] ? e(upload_url($item['item_image'])) : 'https://placehold.co/200x200/f4f6fc/adb5bd?text=Photo' ?>"
                         style="width:160px;height:160px;object-fit:cover;border-radius:16px;border:2px solid var(--border-color);">
                    <?php if ($isEdit && $item['item_image']): ?>
                    <button type="button" id="removeItemImg"
                            style="position:absolute;top:-8px;right:-8px;width:26px;height:26px;padding:0;border-radius:50%;font-size:.75rem;"
                            class="btn btn-danger btn-sm">
                        <i class="bi bi-x"></i>
                    </button>
                    <input type="hidden" name="remove_image" id="removeImgFlag" value="0">
                    <?php endif; ?>
                </div>

                <label class="img-upload-wrap d-block" for="item_image">
                    <i class="bi bi-cloud-upload fs-3 text-secondary d-block mb-1"></i>
                    <div class="fw-600 mb-1" style="font-size:.85rem;">Click to upload</div>
                    <div class="text-secondary" style="font-size:.75rem;">JPG, PNG, WebP · Max <?= UPLOAD_MAX_SIZE ?> KB</div>
                    <input type="file" id="item_image" name="item_image"
                           class="d-none img-upload-input" accept="image/jpeg,image/png,image/webp"
                           data-preview="itemImgPreview">
                </label>
            </div>
        </div>

        <!-- Summary -->
        <div class="card mb-4">
            <div class="card-header">
                <i class="bi bi-receipt text-accent"></i>
                <h6 class="card-title">Price Summary</h6>
            </div>
            <div class="card-body">
                <div class="d-flex justify-content-between mb-2">
                    <span class="text-secondary" style="font-size:.85rem;">Base Price</span>
                    <span class="fw-700" id="summaryBasePrice">—</span>
                </div>
                <div class="d-flex justify-content-between">
                    <span class="text-secondary" style="font-size:.85rem;">With Variants</span>
                    <span class="fw-700 text-accent" id="summaryWithVariant">—</span>
                </div>
                <hr>
                <p class="text-secondary mb-0" style="font-size:.75rem;">
                    Final price = Base + variant modifier. Customer selects variant during ordering.
                </p>
            </div>
        </div>

    </div>
</div>

<!-- Submit -->
<div class="d-flex gap-2 mt-2 mb-5">
    <button type="submit" class="btn btn-accent px-5">
        <i class="bi bi-check-lg me-1"></i>
        <?= $isEdit ? 'Update Item' : 'Create Item' ?>
    </button>
    <a href="<?= url('menu') ?>" class="btn btn-outline-secondary px-4">Cancel</a>
</div>

</form>

<?php ob_start(); ?>
<script>
(function () {
    let groupIndex = <?= count($groups) ?>;

    // ── Price summary ─────────────────────────────────────────────────────────
    const basePriceInput  = document.getElementById('base_price');
    const summaryBase     = document.getElementById('summaryBasePrice');
    const summaryVariant  = document.getElementById('summaryWithVariant');

    function updateSummary() {
        const base = parseFloat(basePriceInput.value) || 0;
        summaryBase.textContent = 'Rs. ' + base.toFixed(2);
        // Find max price modifier among defaults
        let maxMod = 0;
        document.querySelectorAll('.choice-row input[name*="[price_modifier]"]').forEach(inp => {
            const v = parseFloat(inp.value) || 0;
            if (v > maxMod) maxMod = v;
        });
        summaryVariant.textContent = 'Rs. ' + (base + maxMod).toFixed(2);
    }
    basePriceInput.addEventListener('input', updateSummary);
    updateSummary();

    // ── Add Group ─────────────────────────────────────────────────────────────
    document.getElementById('addGroupBtn').addEventListener('click', function () {
        document.getElementById('noGroupsMsg').classList.add('d-none');

        const gi  = groupIndex++;
        const tpl = `
        <div class="choice-group card border mb-3" data-group-index="${gi}">
            <div class="card-body pb-2">
                <div class="row g-2 mb-3 align-items-center">
                    <div class="col-12 col-md-4">
                        <label class="form-label mb-1" style="font-size:.8rem;">Group Name <span class="text-danger">*</span></label>
                        <input type="text" name="groups[${gi}][name]"
                               class="form-control form-control-sm" placeholder="e.g. Size, Crust" required>
                    </div>
                    <div class="col-6 col-md-2">
                        <label class="form-label mb-1" style="font-size:.8rem;">Min Select</label>
                        <input type="number" name="groups[${gi}][min_select]"
                               class="form-control form-control-sm" min="0" max="10" value="1">
                    </div>
                    <div class="col-6 col-md-2">
                        <label class="form-label mb-1" style="font-size:.8rem;">Max Select</label>
                        <input type="number" name="groups[${gi}][max_select]"
                               class="form-control form-control-sm" min="1" max="10" value="1">
                    </div>
                    <div class="col-6 col-md-2 d-flex align-items-end pb-1">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox"
                                   name="groups[${gi}][is_required]" value="1" id="req_${gi}" checked>
                            <label class="form-check-label" for="req_${gi}" style="font-size:.8rem;">Required</label>
                        </div>
                    </div>
                    <div class="col-6 col-md-2 text-end d-flex align-items-end justify-content-end pb-1">
                        <button type="button" class="btn btn-sm btn-outline-danger remove-group-btn">
                            <i class="bi bi-trash"></i> Remove
                        </button>
                    </div>
                </div>
                <div class="choices-container">
                    <div class="d-flex align-items-center mb-2">
                        <span style="font-size:.78rem;font-weight:600;color:var(--text-secondary);text-transform:uppercase;letter-spacing:.5px;">Choices</span>
                        <button type="button" class="btn btn-sm btn-link ms-2 p-0 add-choice-btn"
                                data-group="${gi}" style="font-size:.8rem;">
                            <i class="bi bi-plus-circle me-1"></i>Add Choice
                        </button>
                    </div>
                    ${choiceRowHtml(gi, 0)}
                </div>
            </div>
        </div>`;

        document.getElementById('choiceGroupsContainer').insertAdjacentHTML('beforeend', tpl);
    });

    function choiceRowHtml(gi, ci) {
        return `
        <div class="row g-2 mb-2 choice-row align-items-center">
            <div class="col-12 col-md-4">
                <input type="text" name="groups[${gi}][choices][${ci}][label]"
                       class="form-control form-control-sm" placeholder="e.g. Large" required>
            </div>
            <div class="col-6 col-md-3">
                <div class="input-group input-group-sm">
                    <span class="input-group-text">+</span>
                    <input type="number" name="groups[${gi}][choices][${ci}][price_modifier]"
                           class="form-control" placeholder="0.00" step="0.01" min="0" value="0.00">
                </div>
            </div>
            <div class="col-4 col-md-3">
                <div class="form-check">
                    <input class="form-check-input" type="checkbox"
                           name="groups[${gi}][choices][${ci}][is_default]" value="1">
                    <label class="form-check-label" style="font-size:.8rem;">Default</label>
                </div>
            </div>
            <div class="col-2 col-md-2 text-end">
                <button type="button" class="btn btn-sm btn-outline-danger remove-choice-btn p-1">
                    <i class="bi bi-x-lg"></i>
                </button>
            </div>
        </div>`;
    }

    // ── Add Choice (event delegation) ─────────────────────────────────────────
    document.getElementById('choiceGroupsContainer').addEventListener('click', function (e) {

        // Add choice button
        const addBtn = e.target.closest('.add-choice-btn');
        if (addBtn) {
            const gi      = addBtn.dataset.group;
            const container = addBtn.closest('.choices-container');
            const ci      = container.querySelectorAll('.choice-row').length;
            container.insertAdjacentHTML('beforeend', choiceRowHtml(gi, ci));
            updateSummary();
            return;
        }

        // Remove choice button
        const removeChoice = e.target.closest('.remove-choice-btn');
        if (removeChoice) {
            removeChoice.closest('.choice-row').remove();
            updateSummary();
            return;
        }

        // Remove group button
        const removeGroup = e.target.closest('.remove-group-btn');
        if (removeGroup) {
            removeGroup.closest('.choice-group').remove();
            if (!document.querySelector('.choice-group')) {
                document.getElementById('noGroupsMsg').classList.remove('d-none');
            }
            return;
        }
    });

    // ── Remove item image ─────────────────────────────────────────────────────
    const removeImgBtn = document.getElementById('removeItemImg');
    if (removeImgBtn) {
        removeImgBtn.addEventListener('click', function () {
            document.getElementById('removeImgFlag').value = '1';
            document.getElementById('itemImgPreview').src = 'https://placehold.co/200x200/f4f6fc/adb5bd?text=Photo';
            this.style.display = 'none';
        });
    }

    // ── Listen to price modifier changes ──────────────────────────────────────
    document.getElementById('choiceGroupsContainer').addEventListener('input', function(e) {
        if (e.target.name && e.target.name.includes('price_modifier')) updateSummary();
    });

})();
</script>
<?php $extraJs = ob_get_clean(); ?>
