<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Daftar Hadiah</title>
    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://unpkg.com/vue@3.2.36/dist/vue.global.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcode-generator/1.4.4/qrcode.min.js"></script>
    
    <script src="crud.js"></script>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary-color: #4a90e2;
            --accent-color: #ff6b6b;
            --dark-color: #333;
            --light-color: #f8f9fa;
            --success-color: #28a745;
            --shadow: 0 4px 20px rgba(0,0,0,0.08);
            --radius: 12px;
        }
        body {
            margin: 0;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
            background-color: var(--light-color);
            color: var(--dark-color);
            -webkit-tap-highlight-color: transparent;
        }
        #app {
            max-width: 420px;
            margin: 0 auto;
            background-color: #fff;
            min-height: 100vh;
        }
        .header {
            background: linear-gradient(135deg, var(--primary-color), #357abd);
            color: white;
            padding: 20px;
            text-align: center;
            font-size: 1.2rem;
            font-weight: 600;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            position: sticky;
            top: 0;
            z-index: 10;
        }
        .rewards-list { padding: 15px; }
        .reward-card {
            display: flex;
            background: #fff;
            border-radius: var(--radius);
            margin-bottom: 15px;
            box-shadow: var(--shadow);
            overflow: hidden;
            border: 1px solid #eef1f4;
        }
        .reward-image {
            width: 100px;
            height: 120px;
            object-fit: cover;
            flex-shrink: 0;
            background-color: #f0f0f0;
        }
        .reward-details {
            padding: 12px;
            flex-grow: 1;
            display: flex;
            flex-direction: column;
        }
        .reward-title {
            font-weight: 600;
            font-size: 0.95rem;
            margin: 0;
            line-height: 1.3;
        }
        .reward-product {
            font-size: 0.8rem;
            color: #666;
            margin-bottom: 8px;
        }
        .reward-pricing { margin-top: auto; }
        .price-normal {
            text-decoration: line-through;
            color: #999;
            font-size: 0.8rem;
            margin-right: 5px;
        }
        .price-offer {
            font-weight: 700;
            color: var(--accent-color);
            font-size: 1rem;
        }
        .points-badge, .free-badge {
            background-color: #eaf3ff;
            color: var(--primary-color);
            font-weight: 600;
            padding: 4px 8px;
            border-radius: 20px;
            font-size: 0.8rem;
            display: inline-block;
        }
        .free-badge {
            background-color: #d4edda;
            color: var(--success-color);
        }
        .redeem-button {
            margin-top: 10px;
            background: var(--primary-color);
            color: white;
            border: none;
            width: 100%;
            padding: 10px;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
        }
        .loading, .no-rewards {
            text-align: center;
            padding: 50px 20px;
            color: #888;
        }
        .spinner {
            width: 30px; height: 30px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid var(--primary-color);
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 15px;
        }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
        
        /* Modal Styles */
        .modal-overlay {
            position: fixed; top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(0, 0, 0, 0.6); display: flex; align-items: center;
            justify-content: center; z-index: 1000;
        }
        .modal-content {
            background: white; padding: 25px; border-radius: var(--radius);
            text-align: center; width: 80%; max-width: 300px;
        }
        .qr-code-container { padding: 15px; border: 1px solid #eee; border-radius: 8px; display: inline-block; margin-bottom: 15px; }
        .close-button { background: #eef1f4; color: #555; border: none; width: 100%; padding: 12px; border-radius: 8px; font-weight: 600; }
    </style>
</head>
<body>

<div id="app">
    <div class="header">Daftar Hadiah</div>

    <div v-if="isLoading" class="loading">
        <div class="spinner"></div>
        <p>Memuat hadiah...</p>
    </div>

    <div v-else-if="rewards.length > 0" class="rewards-list">
        <div v-for="reward in rewards" :key="reward.id" class="reward-card">
            <img :src="getImageUrl(reward.image)" :alt="reward.nama_menu" class="reward-image">
            <div class="reward-details">
                <h3 class="reward-title">{{ reward.nama }}</h3>
                <p class="reward-product">{{ reward.nama_menu }}</p>

                <div class="reward-pricing">
                    <div v-if="reward.harga > 0 && reward.poin_tukar > 0">
                        <span class="price-normal">Rp {{ formatNumber(reward.harga_normal) }}</span>
                        <span class="price-offer">Rp {{ formatNumber(reward.harga) }}</span>
                        + <span class="points-badge">{{ reward.poin_tukar }} Poin</span>
                    </div>
                    <div v-else-if="reward.harga == 0 && reward.poin_tukar > 0">
                        <span class="price-normal">Rp {{ formatNumber(reward.harga_normal) }}</span>
                        <span class="points-badge">{{ reward.poin_tukar }} Poin</span>
                    </div>
                    <div v-else>
                        <span class="price-normal">Rp {{ formatNumber(reward.harga_normal) }}</span>
                        <span class="free-badge"><i class="fas fa-gift"></i> Hadiah Spesial</span>
                    </div>
                </div>

                <button class="redeem-button" @click="selectReward(reward)">Tukar Hadiah</button>
            </div>
        </div>
    </div>

    <div v-else class="no-rewards">
        <p>Saat ini belum ada hadiah yang tersedia.</p>
    </div>

    <div v-if="selectedReward" class="modal-overlay" @click.self="closeModal">
        <div class="modal-content">
            <h3>Tukarkan Hadiah Anda</h3>
            <p>Tunjukkan QR Code ini kepada kasir untuk klaim hadiah.</p>
            <div class="qr-code-container" ref="qrCodeContainer"></div>
            <button class="close-button" @click="closeModal">Tutup</button>
        </div>
    </div>
</div>

<script>
    // =================================================================
    // PENTING: Konfigurasi variabel global dari crud.js
    // Sesuaikan URL ini dengan lokasi server Anda
    const BASE_URL = 'http://localhost/bener/pos2/'; 
    const xbrand = '001'; // Sesuaikan dengan brand Anda
    const xcab = '002';   // Sesuaikan dengan cabang Anda
    // =================================================================

    const { createApp } = Vue;

    createApp({
        data() {
            return {
                rewards: [], // PERBAIKAN: Mulai dengan array kosong
                isLoading: true, // State untuk menampilkan loading
                selectedReward: null,
                encryptionKey: 'MySecretKey12345' 
            };
        },

        // PERBAIKAN: Menambahkan lifecycle hook `mounted`
        mounted() {
            // Panggil fungsi untuk mengambil data dari database saat komponen siap
            this.fetchRewards();
        },
        
        methods: {
            // PERBAIKAN BARU: Fungsi untuk mengambil data dari database
            fetchRewards() {
                this.isLoading = true;
                try {
                    // SQL untuk mengambil semua reward aktif yang umum atau khusus untuk member 1 (dummy)
                    const sql = "SELECT * FROM reward WHERE aktif = 1 ORDER BY poin_tukar ASC";
                    
                    // Memanggil fungsi dari crud.js
                    const resultJsonString = yambil_select('reward', sql);
                    
                    // Mengubah hasil string JSON menjadi array JavaScript
                    const dataFromServer = JSON.parse(resultJsonString);

                    this.rewards = dataFromServer;
                } catch (error) {
                    console.error("Gagal mengambil data rewards:", error);
                    // Jika ada error, tampilkan pesan di console
                } finally {
                    this.isLoading = false;
                }
            },
            
            // PERBAIKAN BARU: Fungsi untuk membuat URL gambar yang benar
            getImageUrl(imagePath) {
                if (!imagePath) {
                    // Jika path gambar kosong, gunakan placeholder
                    return 'https://via.placeholder.com/100x120/eee/999?text=No+Img';
                }
                // Menggabungkan BASE_URL dengan path dari database
                return BASE_URL + imagePath;
            },

            formatNumber(value) {
                return new Intl.NumberFormat('id-ID').format(value);
            },
            
            selectReward(reward) {
                this.selectedReward = reward;
                this.$nextTick(() => {
                    this.generateEncryptedQRCode();
                });
            },

            closeModal() {
                this.selectedReward = null;
            },

            generateEncryptedQRCode() {
                if (!this.selectedReward) return;
                const memberId = 1; // Dummy member ID
                const dataString = `${memberId},${this.selectedReward.id},${this.selectedReward.kode},${new Date().toISOString()}`;
                const encryptedData = CryptoJS.AES.encrypt(dataString, this.encryptionKey).toString();
                const finalQrData = encryptedData.substring(0, 16);
                
                try {
                    const qr = qrcode(0, 'M');
                    qr.addData(finalQrData);
                    qr.make();
                    const container = this.$refs.qrCodeContainer;
                    if (container) {
                        container.innerHTML = qr.createImgTag(5, 10);
                    }
                } catch (e) {
                    console.error("Gagal membuat QR Code:", e);
                }
            }
        }
    }).mount('#app');
</script>

</body>
</html>