<div class="hero">
    <div>
        <h2 style="margin:0 0 6px;">Katalog Reward</h2>
        <p style="margin:0; opacity:0.95;">Tentukan promo apa saja yang bisa ditukar member dengan poin mereka.</p>
    </div>
</div>

<div class="panel">
    <div style="display:flex; justify-content:space-between; align-items:center; gap:12px; flex-wrap:wrap;">
        <h3 style="margin:0;">Daftar Reward</h3>
        <button class="btn-primary" type="button" onclick="openRewardModal()" style="max-width:180px;">Tambah Baru</button>
    </div>
</div>

<?php
$iconEdit = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h9"></path><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4Z"></path></svg>';
$iconDelete = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"></path><path d="M10 11v6"></path><path d="M14 11v6"></path><path d="M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2"></path></svg>';
$iconToggleOn = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="1" y="5" width="22" height="14" rx="7"></rect><circle cx="16" cy="12" r="3"></circle></svg>';
$iconToggleOff = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="1" y="5" width="22" height="14" rx="7"></rect><circle cx="8" cy="12" r="3"></circle></svg>';
?>
<div class="panel">
    <h3>Daftar Reward</h3>
    <div class="table-wrap">
        <table>
            <thead>
                <tr><th>Nama Promo</th><th>Layanan/Produk</th><th>Diskon</th><th>Poin Dibutuhkan</th><th>Periode</th><th>Status</th><th>Aksi</th></tr>
            </thead>
            <tbody>
                <?php foreach ($rewards as $reward) : ?>
                    <?php $isActive = (int) $reward['is_active'] === 1; ?>
                    <tr>
                        <td><?= esc($reward['name']) ?></td>
                        <td><?= esc($reward['item_name'] ?? '-') ?></td>
                        <td><?= $reward['discount_type'] === 'percent' ? esc($reward['discount_value']) . '%' : 'Rp ' . esc(number_format((int) $reward['discount_value'], 0, ',', '.')) ?></td>
                        <td><span class="pill" style="margin:0;"><?= esc(number_format((int) $reward['points_required'], 0, ',', '.')) ?> poin</span></td>
                        <td>
                            <?php if (!empty($reward['start_date']) || !empty($reward['end_date'])) : ?>
                                <?= $reward['start_date'] ? esc(date('d/m/Y', strtotime($reward['start_date']))) : '-' ?>
                                s/d
                                <?= $reward['end_date'] ? esc(date('d/m/Y', strtotime($reward['end_date']))) : '-' ?>
                            <?php else : ?>
                                <span class="muted">Selalu berlaku</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <span class="pill" style="margin:0; background:<?= $isActive ? '#dcfce7' : '#fee2e2' ?>; color:<?= $isActive ? '#166534' : '#991b1b' ?>;"><?= $isActive ? 'Aktif' : 'Nonaktif' ?></span>
                        </td>
                        <td>
                            <div class="action-cell">
                                <a class="icon-btn" href="#" title="<?= $isActive ? 'Nonaktifkan' : 'Aktifkan' ?>" onclick="toggleReward('/owner/toggle-reward/<?= esc($reward['id']) ?>'); return false;"><?= $isActive ? $iconToggleOn : $iconToggleOff ?></a>
                                <a class="icon-btn icon-edit" href="#" title="Edit" data-id="<?= esc($reward['id']) ?>" data-name="<?= esc($reward['name']) ?>" data-item-id="<?= esc($reward['item_id']) ?>" data-discount-type="<?= esc($reward['discount_type']) ?>" data-discount-value="<?= esc($reward['discount_value']) ?>" data-points-required="<?= esc($reward['points_required']) ?>" data-start-date="<?= esc($reward['start_date']) ?>" data-end-date="<?= esc($reward['end_date']) ?>" onclick="openRewardModal(this); return false;"><?= $iconEdit ?></a>
                                <a class="icon-btn icon-delete" href="#" title="Hapus" onclick="confirmDelete('/owner/delete-reward/<?= esc($reward['id']) ?>'); return false;"><?= $iconDelete ?></a>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <?php if (empty($rewards)) : ?>
                    <tr><td colspan="7" class="muted">Belum ada reward. Tambahkan promo pertama Anda.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<div class="modal" id="rewardModal" tabindex="-1" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,0.45); z-index:9999; align-items:center; justify-content:center;">
    <div style="background:white; width:min(560px, 92vw); border-radius:16px; padding:20px;">
        <h3 id="rewardModalTitle" style="margin-top:0;">Tambah Reward</h3>
        <form id="rewardForm" method="post" action="/owner/save-reward">
            <input type="hidden" name="id" id="rewardId">
            <div class="form-grid">
                <input type="text" name="name" id="rewardName" placeholder="Nama Promo (misal: Gunting Rambut Diskon 50%)" required style="grid-column:1/-1;">
                <select name="item_id" id="rewardItemId" required>
                    <option value="">Pilih Layanan/Produk</option>
                    <?php foreach ($items as $item) : ?>
                        <option value="<?= esc($item['id']) ?>"><?= esc($item['name']) ?> - Rp <?= number_format($item['price'], 0, ',', '.') ?></option>
                    <?php endforeach; ?>
                </select>
                <select name="discount_type" id="rewardDiscountType">
                    <option value="percent">Diskon Persen (%)</option>
                    <option value="fixed">Diskon Nominal (Rp)</option>
                </select>
                <input type="number" name="discount_value" id="rewardDiscountValue" placeholder="Nilai Diskon" min="1" required>
                <input type="number" name="points_required" id="rewardPointsRequired" placeholder="Poin Dibutuhkan" min="1" required>
                <div>
                    <label style="font-size:12px; opacity:0.75;">Tanggal Mulai (opsional)</label>
                    <input type="date" name="start_date" id="rewardStartDate">
                </div>
                <div>
                    <label style="font-size:12px; opacity:0.75;">Tanggal Selesai (opsional)</label>
                    <input type="date" name="end_date" id="rewardEndDate">
                </div>
            </div>
            <p class="muted" style="font-size:12px; margin:4px 0 0;">Kosongkan tanggal jika promo berlaku terus-menerus.</p>
            <div class="form-grid">
                <button class="btn-primary" type="submit">Simpan</button>
                <button class="btn-secondary" type="button" onclick="closeRewardModal();">Batal</button>
            </div>
        </form>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<style>
.swal2-container { z-index: 10050 !important; }
</style>
<script>
function openRewardModal(el) {
    const modal = document.getElementById('rewardModal');
    const form = document.getElementById('rewardForm');
    document.getElementById('rewardModalTitle').textContent = el ? 'Edit Reward' : 'Tambah Reward';
    document.getElementById('rewardId').value = el ? el.dataset.id : '';
    document.getElementById('rewardName').value = el ? el.dataset.name : '';
    document.getElementById('rewardItemId').value = el ? el.dataset.itemId : '';
    document.getElementById('rewardDiscountType').value = el ? el.dataset.discountType : 'percent';
    document.getElementById('rewardDiscountValue').value = el ? el.dataset.discountValue : '';
    document.getElementById('rewardPointsRequired').value = el ? el.dataset.pointsRequired : '';
    document.getElementById('rewardStartDate').value = el && el.dataset.startDate ? el.dataset.startDate : '';
    document.getElementById('rewardEndDate').value = el && el.dataset.endDate ? el.dataset.endDate : '';
    form.action = el ? '/owner/update-reward' : '/owner/save-reward';
    modal.style.display = 'flex';
}
function closeRewardModal() { document.getElementById('rewardModal').style.display = 'none'; }
function confirmDelete(url) {
    Swal.fire({ title: 'Apakah Anda yakin?', text: 'Reward ini akan dihapus permanen.', icon: 'warning', showCancelButton: true, confirmButtonText: 'Ya, hapus', cancelButtonText: 'Batal' }).then((result) => {
        if (result.isConfirmed) {
            fetch(url, { headers: { 'X-Requested-With': 'XMLHttpRequest' } }).then(r => r.json()).then(() => { Swal.fire('Berhasil', 'Data Berhasil Dihapus', 'success').then(() => location.reload()); });
        }
    });
}
function toggleReward(url) {
    fetch(url, { headers: { 'X-Requested-With': 'XMLHttpRequest' } }).then(r => r.json()).then(() => { location.reload(); });
}
document.getElementById('rewardForm').addEventListener('submit', function (e) {
    e.preventDefault();
    const formData = new FormData(this);
    fetch(this.action, { method: 'POST', body: formData, headers: { 'X-Requested-With': 'XMLHttpRequest' } })
        .then(r => r.json())
        .then(() => { closeRewardModal(); Swal.fire('Berhasil', 'Data Berhasil Disimpan', 'success').then(() => location.reload()); });
});
</script>
