<!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/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>
        .encrypted-text-display {
            background-color: #f0f2f5;
            padding: 10px 15px;
            border-radius: 8px;
            word-wrap: break-word;
            white-space: pre-wrap;
            font-family: "Courier New", Courier, monospace;
            border: 1px solid #e0e4e8;
            margin-top: 15px;
            text-align: center;
            font-size: 0.9em;
            color: #333;
            width: 100%;
            box-sizing: border-box;
        }
        .section-explanation {
            text-align: center;
            padding: 0 15px 20px 15px;
            color: #555;
            font-size: 0.95em;
            line-height: 1.5;
        }
        .qr-display-card {
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.08);
            padding: 25px;
            margin: 0 auto;
            max-width: 320px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        .modal-qr-card {
            box-shadow: none;
            padding: 15px 0;
            max-width: 100%;
        }
        .qr-validity {
            margin-top: 20px;
            font-size: 0.9em;
            color: #388E3C;
            font-weight: 500;
            background-color: #e8f5e9;
            padding: 8px 15px;
            border-radius: 20px;
        }
        .qr-validity .fa-clock {
            margin-right: 7px;
        }
        .modal-content .btn-close {
            background: #eef1f4;
            color: #555;
            margin-top: 15px;
            width: 100%;
            border: none;
        }
        .qr-code img {
            display: block;
            margin: 0 auto;
        }
        .btn-regenerate {
            margin-top: 20px;
            background-color: transparent;
            border: 1px solid #007bff;
            color: #007bff;
            padding: 8px 16px;
            border-radius: 20px;
            cursor: pointer;
            font-size: 0.9em;
            font-weight: 500;
            transition: all 0.2s;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        .btn-regenerate:hover {
            background-color: #007bff;
            color: #fff;
        }
        .reward-card.disabled {
            opacity: 0.6;
            filter: grayscale(80%);
            background: #f9f9f9;
        }
        .redeem-button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
            border-color: #ccc;
        }
        .redeem-button:disabled:hover {
            background-color: #ccc;
        }
    </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">
                    <p class="section-explanation">Setiap selesai belanja, tunjukkan QR Code di bawah ini kepada kasir untuk menambahkan poin ke akun Anda.</p>
                    <div class="qr-display-card">
                        <div ref="addPointQrContainer" class="qr-code"></div>
                        <pre ref="addPointEncryptedText" class="encrypted-text-display" v-show="this.$refs.addPointEncryptedText && this.$refs.addPointEncryptedText.textContent"></pre>
                        <div class="qr-validity" v-if="qrValidityTime">
                            <i class="fas fa-clock"></i> Valid sampai: {{ qrValidityTime }}
                        </div>
                        <button class="btn-regenerate" @click="generateAddPointQR"><i class="fas fa-sync-alt"></i> Buat Kode Baru</button>
                    </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" :class="{ 'disabled': parseInt(currentUser.point) < parseInt(reward.poin_tukar) }">
                            <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)" :disabled="parseInt(currentUser.point) < parseInt(reward.poin_tukar)">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="closeRewardModal">
             <div class="modal-content">
                <h3>Tukarkan Hadiah</h3>
                <p class="section-explanation">QR Code ini hanya berlaku satu kali untuk penukaran. Tunjukkan kepada kasir untuk verifikasi.</p>
                <div class="qr-display-card modal-qr-card">
                     <div ref="rewardQrContainer" class="qr-code"></div>
                     <pre ref="rewardEncryptedText" class="encrypted-text-display"></pre>
                     <div class="qr-validity" v-if="qrValidityTime">
                        <i class="fas fa-clock"></i> Valid sampai: {{ qrValidityTime }}
                     </div>
                     <button class="btn-regenerate" @click="regenerateRewardQR"><i class="fas fa-sync-alt"></i> Buat Kode Baru</button>
                </div>
                <button class="btn btn-close" @click="closeRewardModal">Tutup</button>
            </div>
        </div>
    </div>
</div>

<script>
                    
    // --- FUNGSI ENKRIPSI VIGENERE CIPHER ---
    const charSet = '0123456789_abcdefghijklmnopqrstuvwxyz';
    const key = 'mjgptwpadahariminggukuturutayahkekota';

    function vigenereCipher(text, key, isEncrypt) {
        let result = '';
        const n = charSet.length;
        for (let i = 0; i < text.length; i++) {
            const textChar = text[i].toLowerCase();
            const keyChar = key[i % key.length];
            const textIndex = charSet.indexOf(textChar);
            const keyIndex = charSet.indexOf(keyChar);
            if (textIndex === -1) {
                result += textChar;
                continue;
            }
            let newIndex;
            if (isEncrypt) {
                newIndex = (textIndex + keyIndex) % n;
            } else {
                newIndex = (textIndex - keyIndex + n) % n;
            }
            result += charSet[newIndex];
        }
        return result;
    }

    function getFormattedTimestamp() {
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const seconds = String(now.getSeconds()).padStart(2, '0');
        return `${year}${month}${day}${hours}${minutes}${seconds}`;
    }
    // --- AKHIR FUNGSI ENKRIPSI ---


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

    // bx = xambil('fungsi', 'kode', '', 'zz');
    


    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,
                qrValidityTime: null,
            };
        },
        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() {
            
            localStorage.removeItem('currentUser');
            this.activeSection = 'login';
            this.loginForm = { phone: '', password: '' };    
            // const savedUser = localStorage.getItem('currentUser');
            this.currentUser ={};
            // if (savedUser) {
            //     this.currentUser = JSON.parse(savedUser);
            //     this.activeSection = 'dashboard';
            // }
        },
        methods: {
// ... di dalam bagian methods:
async refreshPoints() {
    if (!this.currentUser) return;
    const sql = `SELECT point FROM member WHERE id='${this.currentUser.id}' LIMIT 1`;
    try {
        const result = JSON.parse(yambil_select('member', sql));
        if (result && result.length > 0) {
            this.currentUser.point = result[0].point;
        }
    } catch (e) {
        console.error('Gagal refresh poin:', e);
    }
},

// ... di dalam bagian methods:
async changeSection(section) {
    this.activeSection = section;
    this.qrValidityTime = null;
    this.$refs.appContainer.scrollTop = 0;

    // --- TAMBAHAN ---
    if (section === 'dashboard') await this.refreshPoints(); 
    // ---------------

    if (section === 'history') await this.fetchHistory();
    if (section === 'rewards') await this.fetchRewards();
    if (section === 'addPoint') {
        this.$nextTick(() => 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;
            },

            generateAddPointQR(retryCount = 0) {
                if (!this.currentUser) return;
                
                const MAX_RETRIES = 10; 
                if (retryCount >= MAX_RETRIES) {
                    console.error("Gagal menemukan container QR setelah beberapa kali percobaan.");
                    return;
                }

                const container = this.$refs.addPointQrContainer;
                const textContainer = this.$refs.addPointEncryptedText;

                if (container && textContainer) {
                    try {
                        this.setAndFormatValidityTime();
                        const paddedId = String(this.currentUser.id).padStart(6, '0');
                        const timestamp = getFormattedTimestamp();
                        const plainText = `${paddedId}_${timestamp}`;
                        const encryptedText = vigenereCipher(plainText, key, true);
                        
                        container.innerHTML = '';
                        const qr = qrcode(0, 'M');
                        qr.addData(encryptedText);
                        qr.make();
                        container.innerHTML = qr.createImgTag(5, 10);
                        textContainer.textContent = encryptedText;

                    } catch (error) {
                        console.error("Error saat membuat QR Code:", error);
                        container.innerHTML = "Gagal memuat QR Code.";
                        textContainer.textContent = "Error";
                    }
                } 
                else {
                    setTimeout(() => {
                        this.generateAddPointQR(retryCount + 1);
                    }, 50);
                }
            },
            
            selectReward(reward) {
                if (parseInt(this.currentUser.point) < parseInt(reward.poin_tukar)) {
                    return alert('Poin Anda tidak mencukupi untuk menukar hadiah ini.');
                }
                this.selectedReward = reward;
                this.$nextTick(() => {
                    this.regenerateRewardQR();
                });
            },

            regenerateRewardQR() {
                if (!this.selectedReward) return;
                
                this.setAndFormatValidityTime();
                const paddedId = String(this.currentUser.id).padStart(6, '0');
                const timestamp = getFormattedTimestamp();
                const plainText = `${paddedId}_[${this.selectedReward.kode}]=${timestamp}`;
                const encryptedText = vigenereCipher(plainText, key, true);
                
                const qrContainer = this.$refs.rewardQrContainer;
                const textContainer = this.$refs.rewardEncryptedText;
                
                const qr = qrcode(0, 'M');
                qr.addData(encryptedText);
                qr.make();
                qrContainer.innerHTML = qr.createImgTag(5, 10);
                textContainer.textContent = encryptedText;
            },

            closeRewardModal() {
                this.selectedReward = null;
                this.qrValidityTime = null;
            },

            setAndFormatValidityTime() {
                const now = new Date();
                now.setMinutes(now.getMinutes() + 5);
                const d = now;
                const hours = String(d.getHours()).padStart(2, '0');
                const minutes = String(d.getMinutes()).padStart(2, '0');
                const seconds = String(d.getSeconds()).padStart(2, '0');
                this.qrValidityTime = `${d.getDate()}/${d.getMonth()+1}/${d.getFullYear()} ${hours}:${minutes}:${seconds}`;
            },

            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 ?  imagePath : 'https://via.placeholder.com/150/eee/99_Img';
            }
        }
    }).mount('#app');
</script>
</body>
</html>