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

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

<div class="row justify-content-center">
<div class="col-12 col-lg-8">

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

    <div class="card mb-4">
        <div class="card-header"><i class="bi bi-percent text-accent"></i><h6 class="card-title">Discount Details</h6></div>
        <div class="card-body">
            <div class="row g-3">
                <div class="col-12">
                    <label class="form-label">Title <span class="text-danger">*</span></label>
                    <input type="text" name="title" class="form-control"
                           placeholder="e.g. Weekend 20% Off on Pizzas"
                           value="<?= e($isEdit ? $discount['title'] : '') ?>" required>
                </div>

                <div class="col-6 col-md-4">
                    <label class="form-label">Discount Type <span class="text-danger">*</span></label>
                    <select name="discount_type" id="discType" class="form-select">
                        <option value="percentage" <?= ($isEdit ? $discount['discount_type'] : 'percentage') === 'percentage' ? 'selected':'' ?>>Percentage (%)</option>
                        <option value="fixed"      <?= ($isEdit ? $discount['discount_type'] : '') === 'fixed' ? 'selected':'' ?>>Fixed Amount</option>
                    </select>
                </div>
                <div class="col-6 col-md-4">
                    <label class="form-label">Value <span class="text-danger">*</span></label>
                    <div class="input-group">
                        <input type="number" name="discount_value" class="form-control"
                               min="0.01" step="0.01" placeholder="0"
                               value="<?= e($isEdit ? $discount['discount_value'] : '') ?>" required>
                        <span class="input-group-text" id="discUnit">%</span>
                    </div>
                </div>
                <div class="col-6 col-md-4">
                    <label class="form-label">Min Order Amount</label>
                    <input type="number" name="min_order_amt" class="form-control"
                           min="0" step="0.01" placeholder="0"
                           value="<?= e($isEdit ? $discount['min_order_amt'] : '0') ?>">
                    <div class="form-text">Discount applies only above this subtotal.</div>
                </div>

                <div class="col-6 col-md-4">
                    <label class="form-label">Max Discount <span class="text-secondary">(cap)</span></label>
                    <input type="number" name="max_discount" class="form-control"
                           min="0" step="0.01" placeholder="0 = no cap"
                           value="<?= e($isEdit ? ($discount['max_discount'] ?? '') : '') ?>">
                    <div class="form-text">Caps a percentage discount (0/blank = no cap).</div>
                </div>

                <div class="col-12">
                    <label class="form-label">Applies To <span class="text-danger">*</span></label>
                    <div class="d-flex gap-3 flex-wrap">
                        <?php foreach (['order' => 'Whole Order', 'category' => 'Category', 'item' => 'Specific Item'] as $val => $label): ?>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="applies_to"
                                   id="applies_<?= $val ?>" value="<?= $val ?>"
                                   <?= ($isEdit ? $discount['applies_to'] : 'order') === $val ? 'checked' : '' ?>>
                            <label class="form-check-label" for="applies_<?= $val ?>"><?= $label ?></label>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Category target -->
                <div class="col-12" id="targetCategoryWrap" style="display:none;">
                    <label class="form-label">Select Category <span class="text-danger">*</span></label>
                    <select name="target_id" class="form-select" id="targetCategorySelect">
                        <option value="">Choose category…</option>
                        <?php foreach ($categories as $cat): ?>
                        <option value="<?= $cat['id'] ?>"
                            <?= ($isEdit && $discount['applies_to']==='category' && $discount['target_id']==$cat['id']) ? 'selected':'' ?>>
                            <?= e($cat['name']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- Item target -->
                <div class="col-12" id="targetItemWrap" style="display:none;">
                    <label class="form-label">Select Item <span class="text-danger">*</span></label>
                    <select name="target_id" class="form-select" id="targetItemSelect">
                        <option value="">Choose item…</option>
                        <?php foreach ($menuItems as $mi): ?>
                        <option value="<?= $mi['id'] ?>"
                            <?= ($isEdit && $discount['applies_to']==='item' && $discount['target_id']==$mi['id']) ? 'selected':'' ?>>
                            <?= e($mi['category_name']) ?> — <?= e($mi['name']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </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($discount['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($discount['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 || $discount['is_active']) ? 'checked' : '' ?>>
                        <label class="form-check-label fw-600" for="is_active">Active</label>
                    </div>
                </div>
            </div>
        </div>
    </div>

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

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

<?php ob_start(); ?>
<script>
// Discount type
const discType = document.getElementById('discType');
const discUnit = document.getElementById('discUnit');
discType.addEventListener('change', () => { discUnit.textContent = discType.value === 'percentage' ? '%' : 'Rs.'; });
discUnit.textContent = discType.value === 'percentage' ? '%' : 'Rs.';

// Applies-to toggle
function updateTarget() {
    const val = document.querySelector('input[name="applies_to"]:checked')?.value;
    document.getElementById('targetCategoryWrap').style.display = val === 'category' ? '' : 'none';
    document.getElementById('targetItemWrap').style.display     = val === 'item'     ? '' : 'none';
    // Disable irrelevant selects so they don't submit
    document.getElementById('targetCategorySelect').disabled = val !== 'category';
    document.getElementById('targetItemSelect').disabled     = val !== 'item';
}
document.querySelectorAll('input[name="applies_to"]').forEach(r => r.addEventListener('change', updateTarget));
updateTarget();
</script>
<?php $extraJs = ob_get_clean(); ?>
