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

<div class="page-header">
    <div><h1><?= $isEdit ? 'Edit Deal' : 'Create Deal' ?></h1></div>
    <a href="<?= url('deals') ?>" class="btn btn-outline-secondary"><i class="bi bi-arrow-left me-1"></i> Back</a>
</div>

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

<div class="row g-4">
<div class="col-12 col-lg-8">

    <div class="card mb-4">
        <div class="card-header"><i class="bi bi-gift text-accent"></i><h6 class="card-title">Deal Details</h6></div>
        <div class="card-body">
            <div class="row g-3">
                <div class="col-12">
                    <label class="form-label">Deal Title <span class="text-danger">*</span></label>
                    <input type="text" name="title" class="form-control"
                           placeholder="e.g. Family Feast Deal"
                           value="<?= e($isEdit ? $deal['title'] : '') ?>" required>
                </div>
                <div class="col-12">
                    <label class="form-label">Description</label>
                    <textarea name="description" class="form-control" rows="2"
                              placeholder="Brief description of this deal…"><?= e($isEdit ? $deal['description'] : '') ?></textarea>
                </div>
                <div class="col-6 col-md-4">
                    <label class="form-label">Deal Price <span class="text-danger">*</span></label>
                    <input type="number" name="deal_price" class="form-control"
                           placeholder="0.00" min="0.01" step="0.01"
                           value="<?= e($isEdit ? number_format((float)$deal['deal_price'],2,'.','') : '') ?>" required>
                </div>
                <div class="col-6 col-md-4">
                    <label class="form-label">Start Date <span class="text-danger">*</span></label>
                    <input type="datetime-local" name="starts_at" class="form-control"
                           value="<?= e($isEdit ? date('Y-m-d\TH:i',strtotime($deal['starts_at'])) : date('Y-m-d\TH:i')) ?>" required>
                </div>
                <div class="col-6 col-md-4">
                    <label class="form-label">Expiry Date <span class="text-danger">*</span></label>
                    <input type="datetime-local" name="expires_at" class="form-control"
                           value="<?= e($isEdit ? date('Y-m-d\TH:i',strtotime($deal['expires_at'])) : '') ?>" required>
                </div>
                <div class="col-6 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_active" name="is_active" value="1"
                               <?= (!$isEdit || $deal['is_active']) ? 'checked' : '' ?>>
                        <label class="form-check-label fw-600" for="is_active">Active</label>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Items -->
    <div class="card mb-4">
        <div class="card-header">
            <i class="bi bi-list-check text-accent"></i>
            <h6 class="card-title">Deal Items <span class="text-danger">*</span></h6>
            <button type="button" id="addItemBtn" class="btn btn-sm btn-outline-accent ms-auto">
                <i class="bi bi-plus-lg me-1"></i> Add Item
            </button>
        </div>
        <div class="card-body" id="dealItemsContainer">

            <?php if (empty($dealItems)): ?>
            <div id="noItemsMsg" class="text-center py-3 text-secondary">
                <p class="mb-0" style="font-size:.85rem;">No items added. Click <strong>Add Item</strong> to include menu items in this deal.</p>
            </div>
            <?php else: ?>
            <div id="noItemsMsg" class="d-none"></div>
            <?php endif; ?>

            <?php foreach ($dealItems as $di): ?>
            <div class="row g-2 mb-2 deal-item-row align-items-center">
                <div class="col-12 col-md-7">
                    <select name="item_ids[]" class="form-select form-select-sm" required>
                        <option value="">Select item…</option>
                        <?php foreach ($menuItems as $mi): ?>
                        <option value="<?= $mi['id'] ?>"
                                <?= $mi['id'] == $di['menu_item_id'] ? 'selected' : '' ?>>
                            <?= e($mi['category_name']) ?> — <?= e($mi['name']) ?>
                            (<?= money((float)$mi['base_price']) ?>)
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-4 col-md-3">
                    <div class="input-group input-group-sm">
                        <span class="input-group-text">Qty</span>
                        <input type="number" name="item_qtys[]" class="form-control"
                               min="1" max="20" value="<?= $di['quantity'] ?>">
                    </div>
                </div>
                <div class="col-2 col-md-2 text-end">
                    <button type="button" class="btn btn-sm btn-outline-danger remove-deal-item">
                        <i class="bi bi-x-lg"></i>
                    </button>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

</div>
<div class="col-12 col-lg-4">

    <!-- Image -->
    <div class="card mb-4">
        <div class="card-header"><i class="bi bi-image text-accent"></i><h6 class="card-title">Deal Image</h6></div>
        <div class="card-body text-center">
            <div style="position:relative;display:inline-block;margin-bottom:12px;">
                <img id="dealImgPreview"
                     src="<?= $isEdit && $deal['deal_image'] ? e(upload_url($deal['deal_image'])) : 'https://placehold.co/200x160/f4f6fc/adb5bd?text=Deal+Photo' ?>"
                     style="width:100%;max-width:200px;height:140px;object-fit:cover;border-radius:12px;border:2px solid var(--border-color);">
                <?php if ($isEdit && $deal['deal_image']): ?>
                <button type="button" id="removeDealImg"
                        style="position:absolute;top:-8px;right:-8px;width:26px;height:26px;padding:0;border-radius:50%;"
                        class="btn btn-danger btn-sm"><i class="bi bi-x"></i></button>
                <input type="hidden" name="remove_image" id="removeDealImgFlag" value="0">
                <?php endif; ?>
            </div>
            <label class="img-upload-wrap d-block" for="deal_image">
                <i class="bi bi-cloud-upload fs-3 text-secondary d-block mb-1"></i>
                <div style="font-size:.8rem;">Click to upload · JPG PNG WebP · Max <?= UPLOAD_MAX_SIZE ?> KB</div>
                <input type="file" id="deal_image" name="deal_image"
                       class="d-none img-upload-input" accept="image/jpeg,image/png,image/webp"
                       data-preview="dealImgPreview">
            </label>
        </div>
    </div>

</div>
</div>

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

</form>

<?php ob_start(); ?>
<script>
const menuItemsData = <?= json_encode($menuItems) ?>;

function itemRowHtml() {
    let opts = '<option value="">Select item…</option>';
    menuItemsData.forEach(m => {
        opts += `<option value="${m.id}">${m.category_name} — ${m.name} (Rs. ${parseFloat(m.base_price).toFixed(2)})</option>`;
    });
    return `
    <div class="row g-2 mb-2 deal-item-row align-items-center">
        <div class="col-12 col-md-7">
            <select name="item_ids[]" class="form-select form-select-sm" required>${opts}</select>
        </div>
        <div class="col-4 col-md-3">
            <div class="input-group input-group-sm">
                <span class="input-group-text">Qty</span>
                <input type="number" name="item_qtys[]" class="form-control" min="1" max="20" value="1">
            </div>
        </div>
        <div class="col-2 col-md-2 text-end">
            <button type="button" class="btn btn-sm btn-outline-danger remove-deal-item">
                <i class="bi bi-x-lg"></i>
            </button>
        </div>
    </div>`;
}

document.getElementById('addItemBtn').addEventListener('click', function () {
    document.getElementById('noItemsMsg').classList.add('d-none');
    document.getElementById('dealItemsContainer').insertAdjacentHTML('beforeend', itemRowHtml());
});

document.getElementById('dealItemsContainer').addEventListener('click', function (e) {
    const btn = e.target.closest('.remove-deal-item');
    if (btn) {
        btn.closest('.deal-item-row').remove();
        if (!document.querySelector('.deal-item-row')) {
            document.getElementById('noItemsMsg').classList.remove('d-none');
        }
    }
});

const removeImg = document.getElementById('removeDealImg');
if (removeImg) {
    removeImg.addEventListener('click', function () {
        document.getElementById('removeDealImgFlag').value = '1';
        document.getElementById('dealImgPreview').src = 'https://placehold.co/200x160/f4f6fc/adb5bd?text=Deal+Photo';
        this.style.display = 'none';
    });
}
</script>
<?php $extraJs = ob_get_clean(); ?>
