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

<div class="page-header">
    <div>
        <h1><?= $isEdit ? 'Edit Voucher' : 'Create Voucher' ?></h1>
        <p><?= $isEdit ? 'Update voucher details.' : 'Create a new discount coupon code.' ?></p>
    </div>
    <a href="<?= url('vouchers') ?>" 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('vouchers/'.$voucher['id'].'/update') : url('vouchers/store') ?>"
      class="fd-form" novalidate>
    <?= csrf_field() ?>

    <!-- Code & Type -->
    <div class="card mb-4">
        <div class="card-header">
            <i class="bi bi-ticket-perforated text-accent"></i>
            <h6 class="card-title">Voucher Details</h6>
        </div>
        <div class="card-body">
            <div class="row g-3">
                <div class="col-12 col-md-5">
                    <label class="form-label">Voucher Code <span class="text-danger">*</span></label>
                    <input type="text" name="code" class="form-control text-uppercase fw-700"
                           placeholder="e.g. SAVE50" maxlength="30"
                           value="<?= e($isEdit ? $voucher['code'] : strtoupper(\Core\Request::post('code',''))) ?>"
                           style="letter-spacing:2px; font-size:1rem;" required>
                    <div class="form-text">3–30 characters. Letters, numbers, - and _ only.</div>
                </div>
                <div class="col-12 col-md-7">
                    <label class="form-label">Description</label>
                    <input type="text" name="description" class="form-control"
                           placeholder="e.g. 50% off on first order"
                           value="<?= e($isEdit ? $voucher['description'] : '') ?>" maxlength="255">
                </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="discountType" class="form-select">
                        <option value="percentage" <?= ($isEdit ? $voucher['discount_type'] : 'percentage') === 'percentage' ? 'selected':'' ?>>Percentage (%)</option>
                        <option value="fixed"      <?= ($isEdit ? $voucher['discount_type'] : '') === 'fixed' ? 'selected':'' ?>>Fixed Amount</option>
                    </select>
                </div>
                <div class="col-6 col-md-4">
                    <label class="form-label">Discount Value <span class="text-danger">*</span></label>
                    <div class="input-group">
                        <input type="number" name="discount_value" class="form-control"
                               placeholder="0" min="0.01" step="0.01"
                               value="<?= e($isEdit ? $voucher['discount_value'] : '') ?>" required>
                        <span class="input-group-text" id="discountUnit">%</span>
                    </div>
                </div>
                <div class="col-6 col-md-4" id="maxDiscountWrap">
                    <label class="form-label">Max Discount Cap</label>
                    <input type="number" name="max_discount" class="form-control"
                           placeholder="Leave empty for no cap" min="0" step="0.01"
                           value="<?= e($isEdit ? $voucher['max_discount'] : '') ?>">
                    <div class="form-text">Only for percentage type.</div>
                </div>
            </div>
        </div>
    </div>

    <!-- Limits -->
    <div class="card mb-4">
        <div class="card-header">
            <i class="bi bi-sliders text-accent"></i>
            <h6 class="card-title">Usage & Limits</h6>
        </div>
        <div class="card-body">
            <div class="row g-3">
                <div class="col-6 col-md-3">
                    <label class="form-label">Min Order Amount</label>
                    <input type="number" name="min_order_amt" class="form-control"
                           placeholder="0" min="0" step="0.01"
                           value="<?= e($isEdit ? $voucher['min_order_amt'] : '0') ?>">
                </div>
                <div class="col-6 col-md-3">
                    <label class="form-label">Total Usage Limit</label>
                    <input type="number" name="usage_limit" class="form-control"
                           placeholder="∞ unlimited" min="1"
                           value="<?= e($isEdit ? $voucher['usage_limit'] : '') ?>">
                </div>
                <div class="col-6 col-md-3">
                    <label class="form-label">Per User Limit</label>
                    <input type="number" name="per_user_limit" class="form-control"
                           placeholder="1" min="1" max="100"
                           value="<?= e($isEdit ? $voucher['per_user_limit'] : '1') ?>">
                </div>
                <div class="col-6 col-md-3 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 || $voucher['is_active']) ? 'checked' : '' ?>>
                        <label class="form-check-label fw-600" for="is_active">Active</label>
                    </div>
                </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($voucher['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($voucher['expires_at'])) : '') ?>" required>
                </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 Voucher' : 'Create Voucher' ?>
        </button>
        <a href="<?= url('vouchers') ?>" class="btn btn-outline-secondary px-4">Cancel</a>
        <?php if (!$isEdit): ?>
        <button type="button" id="genCodeBtn" class="btn btn-outline-secondary ms-auto">
            <i class="bi bi-shuffle me-1"></i> Generate Code
        </button>
        <?php endif; ?>
    </div>

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

<?php ob_start(); ?>
<script>
// Discount type switch
const typeSelect  = document.getElementById('discountType');
const unitLabel   = document.getElementById('discountUnit');
const maxWrap     = document.getElementById('maxDiscountWrap');

function updateType() {
    const isPercent = typeSelect.value === 'percentage';
    unitLabel.textContent = isPercent ? '%' : 'Rs.';
    maxWrap.style.display = isPercent ? '' : 'none';
}
typeSelect.addEventListener('change', updateType);
updateType();

// Generate random code
const genBtn = document.getElementById('genCodeBtn');
if (genBtn) {
    genBtn.addEventListener('click', function () {
        const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
        let code = '';
        for (let i = 0; i < 8; i++) code += chars[Math.floor(Math.random() * chars.length)];
        document.querySelector('input[name="code"]').value = code;
    });
}
</script>
<?php $extraJs = ob_get_clean(); ?>
