<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cek Voucher - Voucher App</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css"/>
    <meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">
</head>
<body class="bg-gradient-to-br from-indigo-50 via-white to-purple-50 min-h-screen">

<div class="min-h-screen flex flex-col">
    
    <header class="bg-white shadow-sm">
        <div class="max-w-2xl mx-auto px-4 py-4 flex items-center justify-between">
            <div class="flex items-center gap-2">
                <i class="fa-solid fa-ticket text-indigo-600 text-2xl"></i>
                <span class="font-bold text-gray-800 text-lg">Voucher App</span>
            </div>
        </div>
    </header>

    
    <main class="flex-1 flex items-center justify-center px-4 py-12">
        <div class="w-full max-w-md">

            <div class="text-center mb-8">
                <div class="inline-flex items-center justify-center w-20 h-20 bg-indigo-100 rounded-full mb-4">
                    <i class="fa-solid fa-tag text-indigo-600 text-4xl"></i>
                </div>
                <h1 class="text-3xl font-bold text-gray-800">Cek Kode Voucher</h1>
                <p class="text-gray-500 mt-2">Masukkan kode voucher untuk melihat promo atau diskon yang tersedia</p>
            </div>

            
            <div class="bg-white rounded-2xl shadow-lg p-6 mb-4">
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-2">Kode Voucher</label>
                    <div class="flex gap-2">
                        <input type="text" id="voucher-code"
                               placeholder="Masukkan kode voucher..."
                               class="flex-1 border border-gray-300 rounded-xl px-4 py-3 text-sm font-mono uppercase focus:ring-2 focus:ring-indigo-400 focus:border-indigo-400 outline-none tracking-widest"
                               style="text-transform:uppercase"
                               maxlength="50">
                        <button onclick="checkVoucher()"
                                id="check-btn"
                                class="bg-indigo-600 hover:bg-indigo-700 text-white px-5 py-3 rounded-xl font-semibold transition text-sm whitespace-nowrap">
                            <i class="fa-solid fa-search mr-1"></i> Cek
                        </button>
                    </div>
                </div>

                <div class="border-t border-gray-100 pt-4">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                        Total Belanja <span class="text-gray-400 font-normal">(opsional)</span>
                    </label>
                    <div class="relative">
                        <span class="absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 font-medium text-sm">Rp</span>
                        <input type="number" id="purchase-amount"
                               placeholder="0"
                               class="w-full border border-gray-300 rounded-xl pl-12 pr-4 py-3 text-sm focus:ring-2 focus:ring-indigo-400 focus:border-indigo-400 outline-none"
                               min="0" step="1000">
                    </div>
                    <p class="text-xs text-gray-400 mt-1">Isi untuk melihat estimasi potongan harga</p>
                </div>
            </div>

            
            <div id="result" class="hidden"></div>

            
            <div id="loading" class="hidden text-center py-6">
                <div class="inline-flex items-center gap-2 text-indigo-600">
                    <svg class="animate-spin h-5 w-5" fill="none" viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    <span class="text-sm font-medium">Memeriksa voucher...</span>
                </div>
            </div>
        </div>
    </main>

    <footer class="text-center py-4 text-xs text-gray-400">
        &copy; <?php echo e(date('Y')); ?> Voucher App
    </footer>
</div>

<script>
const csrfToken = document.querySelector('meta[name="csrf-token"]').content;

document.getElementById('voucher-code').addEventListener('keydown', (e) => {
    if (e.key === 'Enter') checkVoucher();
});

async function checkVoucher() {
    const code = document.getElementById('voucher-code').value.trim();
    const amount = document.getElementById('purchase-amount').value;
    const resultEl = document.getElementById('result');
    const loadingEl = document.getElementById('loading');
    const btn = document.getElementById('check-btn');

    if (!code) {
        showError('Masukkan kode voucher terlebih dahulu.');
        return;
    }

    resultEl.classList.add('hidden');
    loadingEl.classList.remove('hidden');
    btn.disabled = true;

    try {
        const resp = await fetch('<?php echo e(route("voucher.check.post")); ?>', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': csrfToken,
                'Accept': 'application/json',
            },
            body: JSON.stringify({ code, purchase_amount: amount || 0 }),
        });

        const data = await resp.json();
        loadingEl.classList.add('hidden');
        btn.disabled = false;

        if (data.valid) {
            showSuccess(data);
        } else {
            showError(data.message);
        }
    } catch (err) {
        loadingEl.classList.add('hidden');
        btn.disabled = false;
        showError('Terjadi kesalahan. Silakan coba lagi.');
    }
}

function showError(msg) {
    const el = document.getElementById('result');
    el.innerHTML = `
        <div class="bg-red-50 border border-red-200 rounded-2xl p-5 text-center">
            <div class="inline-flex items-center justify-center w-12 h-12 bg-red-100 rounded-full mb-3">
                <i class="fa-solid fa-circle-xmark text-red-500 text-2xl"></i>
            </div>
            <h3 class="font-bold text-red-700 mb-1">Voucher Tidak Valid</h3>
            <p class="text-red-600 text-sm">${msg}</p>
        </div>`;
    el.classList.remove('hidden');
}

function showSuccess(data) {
    const v = data.voucher;
    const el = document.getElementById('result');

    let discountText = v.type === 'percentage'
        ? `${v.discount_value}%${v.max_discount ? ' (maks Rp ' + fmt(v.max_discount) + ')' : ''}`
        : `Rp ${fmt(v.discount_value)}`;

    let discountRow = data.discount_amount !== null ? `
        <div class="mt-4 pt-4 border-t border-green-200">
            <div class="flex justify-between text-sm mb-1">
                <span class="text-gray-600">Potongan Harga</span>
                <span class="font-bold text-green-600">- Rp ${fmt(data.discount_amount)}</span>
            </div>
            ${data.final_price !== null ? `
            <div class="flex justify-between text-sm">
                <span class="text-gray-600">Harga Setelah Diskon</span>
                <span class="font-bold text-gray-800 text-base">Rp ${fmt(data.final_price)}</span>
            </div>` : ''}
        </div>` : '';

    el.innerHTML = `
        <div class="bg-green-50 border border-green-200 rounded-2xl p-5">
            <div class="text-center mb-4">
                <div class="inline-flex items-center justify-center w-12 h-12 bg-green-100 rounded-full mb-3">
                    <i class="fa-solid fa-circle-check text-green-500 text-2xl"></i>
                </div>
                <h3 class="font-bold text-green-700">Voucher Valid!</h3>
            </div>

            <div class="bg-white rounded-xl p-4 text-sm space-y-2">
                <div class="flex justify-between">
                    <span class="text-gray-500">Kode</span>
                    <code class="font-mono font-bold text-indigo-700 bg-indigo-50 px-2 py-0.5 rounded">${v.code}</code>
                </div>
                <div class="flex justify-between">
                    <span class="text-gray-500">Nama</span>
                    <span class="font-medium text-gray-800">${v.name}</span>
                </div>
                ${v.description ? `<div><span class="text-gray-500 text-xs">${v.description}</span></div>` : ''}
                <div class="flex justify-between">
                    <span class="text-gray-500">Diskon</span>
                    <span class="font-bold text-green-600 text-base">${discountText}</span>
                </div>
                ${v.min_purchase > 0 ? `
                <div class="flex justify-between">
                    <span class="text-gray-500">Min. Belanja</span>
                    <span class="font-medium text-gray-800">Rp ${fmt(v.min_purchase)}</span>
                </div>` : ''}
                ${v.valid_until ? `
                <div class="flex justify-between">
                    <span class="text-gray-500">Berlaku s/d</span>
                    <span class="font-medium text-gray-800">${v.valid_until}</span>
                </div>` : ''}
                ${v.remaining_uses !== null ? `
                <div class="flex justify-between">
                    <span class="text-gray-500">Sisa Penggunaan</span>
                    <span class="font-medium text-gray-800">${v.remaining_uses}x</span>
                </div>` : ''}
                ${discountRow}
            </div>

            <button onclick="useVoucher('${v.code}')" 
                    id="use-voucher-btn"
                    class="w-full mt-4 bg-green-600 hover:bg-green-700 text-white px-4 py-3 rounded-xl font-semibold transition text-sm">
                <i class="fa-solid fa-check-circle mr-2"></i> Gunakan Voucher
            </button>
        </div>`;
    el.classList.remove('hidden');
}

function fmt(num) {
    return new Intl.NumberFormat('id-ID').format(Math.round(num));
}

async function useVoucher(code) {
    const btn = document.getElementById('use-voucher-btn');
    const purchaseAmount = document.getElementById('purchase-amount').value;
    
    btn.disabled = true;
    btn.innerHTML = '<svg class="animate-spin h-4 w-4 inline-block mr-2" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg> Memproses...';

    try {
        const resp = await fetch('<?php echo e(route("voucher.use")); ?>', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': csrfToken,
                'Accept': 'application/json',
            },
            body: JSON.stringify({ 
                code, 
                purchase_amount: purchaseAmount || 0,
                user_identifier: localStorage.getItem('user_identifier') || null,
            }),
        });

        const data = await resp.json();

        if (data.success) {
            showVoucherUsed(data);
        } else {
            showError(data.message);
            btn.disabled = false;
            btn.innerHTML = '<i class="fa-solid fa-check-circle mr-2"></i> Gunakan Voucher';
        }
    } catch (err) {
        console.error(err);
        showError('Terjadi kesalahan saat menggunakan voucher. Silakan coba lagi.');
        btn.disabled = false;
        btn.innerHTML = '<i class="fa-solid fa-check-circle mr-2"></i> Gunakan Voucher';
    }
}

function showVoucherUsed(data) {
    const el = document.getElementById('result');
    el.innerHTML = `
        <div class="bg-blue-50 border border-blue-200 rounded-2xl p-5 text-center">
            <div class="inline-flex items-center justify-center w-12 h-12 bg-blue-100 rounded-full mb-3">
                <i class="fa-solid fa-check text-blue-500 text-2xl"></i>
            </div>
            <h3 class="font-bold text-blue-700 mb-2">Voucher Berhasil Digunakan!</h3>
            
            <div class="bg-white rounded-xl p-4 text-sm space-y-2 mb-4 text-left">
                <div class="flex justify-between">
                    <span class="text-gray-500">Kode Voucher</span>
                    <code class="font-mono font-bold text-blue-700 bg-blue-50 px-2 py-0.5 rounded">${data.voucher.code}</code>
                </div>
                <div class="flex justify-between">
                    <span class="text-gray-500">Nama Voucher</span>
                    <span class="font-medium text-gray-800">${data.voucher.name}</span>
                </div>
                <div class="flex justify-between pt-2 border-t border-blue-200">
                    <span class="text-gray-600 font-medium">Potongan Harga</span>
                    <span class="font-bold text-blue-600">Rp ${fmt(data.discount_applied)}</span>
                </div>
                ${data.final_price > 0 ? `
                <div class="flex justify-between">
                    <span class="text-gray-600 font-medium">Total Akhir</span>
                    <span class="font-bold text-gray-800 text-base">Rp ${fmt(data.final_price)}</span>
                </div>` : ''}
            </div>

            <p class="text-blue-600 text-sm mb-4">Voucher telah berhasil diterapkan pada pembelian Anda.</p>
            
            <button onclick="resetForm()" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg font-semibold transition text-sm">
                <i class="fa-solid fa-redo mr-1"></i> Cek Voucher Lain
            </button>
        </div>`;
    el.classList.remove('hidden');
}

function resetForm() {
    document.getElementById('voucher-code').value = '';
    document.getElementById('purchase-amount').value = '';
    document.getElementById('result').classList.add('hidden');
    document.getElementById('voucher-code').focus();
}
</script>
</body>
</html>
<?php /**PATH C:\Users\yasin\OneDrive\Desktop\PROJECT-VOUCHER\resources\views/public/check.blade.php ENDPATH**/ ?>