<!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>Member App (Vue.js)</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">
    <link rel="stylesheet" href="member.css">
    <style>
    </style>
</head>
<body>

<div id="app">
    <div class="app-container" ref="appContainer">
        <div class="header">
            <button v-if="activeSection !== 'dashboard' && activeSection !== 'login'" @click="changeSection('dashboard')" class="back-btn">
                <i class="fas fa-arrow-left"></i>
            </button>
            <h1>{{ pageTitle }}</h1>
            <p class="subtitle">{{ pageSubtitle }}</p>
        </div>

        <transition name="page" mode="out-in">
            <div :key="activeSection">
                <section v-if="activeSection === 'login'" class="login-form">
                    <div class="form-group">
                        <label>No. HP</label>
                        <input type="tel" v-model="loginForm.phone" class="form-control" placeholder="Masukkan nomor HP">
                    </div>
                    <div class="form-group">
                        <label>Password</label>
                        <input type="password" v-model="loginForm.password" class="form-control" placeholder="Masukkan password">
                    </div>
                    <button class="btn btn-primary" @click="login">Masuk</button>
                </section>

                <section v-else-if="activeSection === 'dashboard' && currentUser" class="dashboard">
                    <div class="member-card">
                        <div class="member-name">{{ currentUser.nama }}</div>
                        <div class="point-balance">
                            <span>Saldo Poin</span>
                            <span class="point-value">{{ currentUser.point || 0 }}</span>
                        </div>
                    </div>
                    <div class="menu-grid">
                        <div class="menu-item" @click="changeSection('history')"><div class="menu-icon"><i class="fas fa-history"></i></div><div>Riwayat</div></div>
                        <div class="menu-item" @click="changeSection('addPoint')"><div class="menu-icon"><i class="fas fa-plus-circle"></i></div><div>Tambah Poin</div></div>
                        <div class="menu-item" @click="changeSection('rewards')"><div class="menu-icon"><i class="fas fa-gift"></i></div><div>Hadiah</div></div>
                        <div class="menu-item" @click="changeSection('info')"><div class="menu-icon"><i class="fas fa-info-circle"></i></div><div>Info & Promo</div></div>
                    </div>
                    <button class="btn btn-secondary" @click="logout"><i class="fas fa-sign-out-alt"></i> Keluar</button>
                </section>
                
                <section v-else-if="activeSection === 'history'" class="content-section">
                    <div v-if="isLoading" class="loading"><div class="spinner"></div><p>Memuat riwayat...</p></div>
                    <div v-else>
                        <div v-if="history.length === 0"><p>Belum ada riwayat transaksi.</p></div>
                        <div v-for="item in history" :key="item.id" class="history-item" :class="item.point > 0 ? 'add-point' : 'redeem'">
                            <div class="history-header">
                                <span>{{ item.point > 0 ? 'Tambah Poin' : 'Tukar Hadiah' }}</span>
                                <span style="font-size: 12px;">{{ formatDate(item.tanggal) }}</span>
                            </div>
                            <div class="history-points">{{ item.point > 0 ? '+' : '' }}{{ item.point }} Poin</div>
                        </div>
                    </div>
                </section>

                <section v-else-if="activeSection === 'addPoint'" class="content-section">
                    <div class="qr-container">
                        <h3>QR Code Tambah Poin</h3>
                        <p style="margin-bottom: 20px;">Tunjukkan QR code ini ke kasir</p>
                        <div ref="addPointQrContainer" class="qr-code"></div>
                    </div>
                </section>

                <section v-else-if="activeSection === 'rewards'" class="content-section">
                    <div v-if="isLoading" class="loading"><div class="spinner"></div><p>Memuat hadiah...</p></div>
                    <div v-else>
                         <div v-for="reward in rewards" :key="reward.id" class="reward-card">
                            <img :src="getImageUrl(reward.image)" class="reward-image">
                            <div class="reward-details">
                                <h3 class="reward-title">{{ reward.nama }}</h3>
                                <p class="reward-product">{{ reward.nama_menu }}</p>
                                <div style="margin-top: auto;">
                                    <div v-if="reward.harga > 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>
                </section>
                
                <section v-else-if="activeSection === 'info'" class="content-section">
                    <div v-for="promo in promos" :key="promo.id" class="promo-card">
                        <img :src="getImageUrl(promo.image)" class="promo-image">
                    </div>
                    <div class="info-card">
                        <div class="info-title"><i class="fas fa-store"></i> Informasi Restoran</div>
                        <p><strong>Alamat:</strong> Jl. Contoh No. 123, Banjar</p>
                        <p><strong>Telepon:</strong> (0265) 123-4567</p>
                    </div>
                </section>
            </div>
        </transition>

        <div v-if="selectedReward" class="modal-overlay" @click.self="selectedReward = null">
            <div class="modal-content">
                <h3>Tukarkan Hadiah</h3>
                <p>Tunjukkan QR Code ini kepada kasir.</p>
                <div ref="rewardQrContainer" class="qr-code"></div>
                <button class="btn" @click="selectedReward = null" style="background: #eef1f4; color: #555; margin-top:15px;">Tutup</button>
            </div>
        </div>
    </div>
</div>

<script>
    // Konfigurasi Global
    const BASE_URL = 'http://localhost/bener/pos2/'; 
    const xbrand = '001';
    const xcab = '002';

    const { createApp } = Vue;

    createApp({
        data() {
            return {
                activeSection: 'login',
                currentUser: null,
                isLoading: false,
                loginForm: { phone: '', password: '' },
                history: [],
                rewards: [],
                promos: [
                    { id: 1, image: 'image/promo1.jpg' }, { id: 2, image: 'image/promo2.jpg' },
                    { id: 3, image: 'image/promo3.jpg' }, { id: 4, image: 'image/promo4.jpg' },
                    { id: 5, image: 'image/promo5.jpg' },
                ],
                selectedReward: null,
                encryptionKey: 'MySecretKey12345'
            };
        },
        computed: {
            pageTitle() {
                const titles = {
                    login: 'Member Login', dashboard: 'Dashboard', history: 'Riwayat Poin',
                    addPoint: 'Tambah Poin', rewards: 'Tukar Hadiah', info: 'Info & Promo'
                };
                return titles[this.activeSection] || 'Member App';
            },
            pageSubtitle() {
                 return this.activeSection === 'dashboard' && this.currentUser ? `Selamat datang, ${this.currentUser.nama}` : 'Aplikasi Member Restoran Anda';
            }
        },
        mounted() {
            const savedUser = localStorage.getItem('currentUser');
            if (savedUser) {
                this.currentUser = JSON.parse(savedUser);
                this.activeSection = 'dashboard';
            }
        },
        methods: {
            async changeSection(section) {
                this.activeSection = section;
                this.$refs.appContainer.scrollTop = 0;

                if (section === 'history') await this.fetchHistory();
                if (section === 'rewards') await this.fetchRewards();
                if (section === 'addPoint') {
                    // Panggil fungsi generate QR. Fungsi ini sekarang sudah pintar dan akan menunggu sendiri.
                    this.generateAddPointQR();
                }
            },
            
            async login() {
                if (!this.loginForm.phone || !this.loginForm.password) return alert('Mohon isi semua field.');
                this.isLoading = true;
                const sql = `SELECT * FROM member WHERE no_hp='${this.loginForm.phone}' AND password='${this.loginForm.password}' LIMIT 1`;
                try {
                    const result = JSON.parse(yambil_select('member', sql));
                    if (result && result.length > 0) {
                        this.currentUser = result[0];
                        localStorage.setItem('currentUser', JSON.stringify(this.currentUser));
                        this.activeSection = 'dashboard';
                    } else {
                        alert('No. HP atau password salah.');
                    }
                } catch (e) {
                    alert('Gagal login, terjadi kesalahan.');
                } finally {
                    this.isLoading = false;
                }
            },
            
            logout() {
                if (confirm('Yakin ingin keluar?')) {
                    this.currentUser = null;
                    localStorage.removeItem('currentUser');
                    this.activeSection = 'login';
                    this.loginForm = { phone: '', password: '' };
                }
            },

            async fetchHistory() {
                this.isLoading = true;
                const sql = `SELECT * FROM trx_member WHERE member='${this.currentUser.id}' ORDER BY tanggal DESC LIMIT 50`;
                this.history = JSON.parse(yambil_select('trx_member', sql));
                this.isLoading = false;
            },

            async fetchRewards() {
                this.isLoading = true;
                const sql = "SELECT * FROM reward WHERE aktif = 1 ORDER BY poin_tukar ASC";
                this.rewards = JSON.parse(yambil_select('reward', sql));
                this.isLoading = false;
            },

            // --- FUNGSI FINAL DENGAN MEKANISME MENUNGGU ---
            generateAddPointQR(retryCount = 0) {
                if (!this.currentUser) return;
                
                const MAX_RETRIES = 10; // Maksimal 10x percobaan (total 500ms)
                if (retryCount >= MAX_RETRIES) {
                    console.error("Gagal menemukan container QR setelah beberapa kali percobaan.");
                    return;
                }

                const container = this.$refs.addPointQrContainer;

                // Jika container ditemukan, jalankan kode QR
                if (container) {
                    try {
                        container.innerHTML = '';
                        const qrData = `${this.currentUser.id}_${new Date().getTime()}`;
                        const qr = qrcode(0, 'M');
                        qr.addData(qrData);
                        qr.make();
                        container.innerHTML = qr.createImgTag(5, 10);
                    } catch (error) {
                        console.error("Error saat membuat QR Code:", error);
                        container.innerHTML = "Gagal memuat QR Code.";
                    }
                } 
                // Jika container BELUM ditemukan, tunggu 50ms lalu coba lagi
                else {
                    setTimeout(() => {
                        this.generateAddPointQR(retryCount + 1);
                    }, 50);
                }
            },
            
            selectReward(reward) {
                if (this.currentUser.point < reward.poin_tukar) {
                    return alert('Poin Anda tidak mencukupi untuk menukar hadiah ini.');
                }
                this.selectedReward = reward;
                this.$nextTick(() => {
                    const dataString = `${this.currentUser.id},${reward.id},${reward.kode},${new Date().toISOString()}`;
                    const encryptedData = CryptoJS.AES.encrypt(dataString, this.encryptionKey).toString();
                    const finalQrData = encryptedData.substring(0, 16);
                    const qr = qrcode(0, 'M');
                    qr.addData(finalQrData);
                    qr.make();
                    this.$refs.rewardQrContainer.innerHTML = qr.createImgTag(5, 10);
                });
            },

            formatNumber(value) { return new Intl.NumberFormat('id-ID').format(value); },
            formatDate(dateString) {
                const d = new Date(dateString);
                return `${d.getDate()}/${d.getMonth()+1}/${d.getFullYear()} ${d.getHours()}:${d.getMinutes()}`;
            },
            getImageUrl(imagePath) {
                return imagePath ? BASE_URL + imagePath : 'https://via.placeholder.com/150/eee/99_Img';
            }
        }
    }).mount('#app');
</script>
</body>
</html>