<?php
require_once __DIR__ . '/../../config/database.php';

// --- PHẦN QUAN TRỌNG: LẤY CẤU HÌNH TỪ DATABASE ---
$print_settings = [];
$result = $conn->query("SELECT content FROM cms_templates WHERE id = 1");
if ($result && $result->num_rows > 0) {
    $settings_json = $result->fetch_assoc()['content'];
    $print_settings = json_decode($settings_json, true);
}

// 1. Lấy Logo (nếu có)
$logo_path = $print_settings['company_logo'] ?? '';
if (!empty($logo_path)) {
    $logo_path = '/quanlybanhang/' . htmlspecialchars(stripslashes($logo_path));
}

// 2. Lấy Thông tin Ngân hàng (Từ cấu hình đã lưu)
// Nếu chưa cài đặt thì dùng mặc định (BIDV)
$bank_bin = $print_settings['company_bank_bin'] ?? '970418'; 
$account_no = $print_settings['company_bank_acc_no_raw'] ?? '7370276838';
$account_name = $print_settings['company_bank_acc_name_raw'] ?? 'GIANG THI XUAN HONG';
?>
<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Thông Tin Thanh Toán</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700;900&display=swap');
        body {
            font-family: 'Roboto', sans-serif;
            overflow: hidden;
            background: #f0f2f5;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
        }
        /* --- CÁC HIỆU ỨNG CSS CŨ GIỮ NGUYÊN --- */
        #waiting-state { opacity: 0; transform: scale(0.95); transition: opacity 0.5s ease, transform 0.5s ease; }
        #waiting-state.visible { opacity: 1; transform: scale(1); }
        #paid-state { opacity: 0; transform: scale(1.05); transition: opacity 0.5s ease, transform 0.5s ease; background: linear-gradient(135deg, #0f9b0f, #34d399); }
        #paid-state.visible { opacity: 1; transform: scale(1); }
        .thank-you-title { font-weight: 900; font-size: 3.5rem; line-height: 1.1; color: white; text-shadow: 0 4px 10px rgba(0, 0, 0, 0.2); animation: text-pop-in 1s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards; }
        @keyframes text-pop-in { 0% { transform: translateY(50px) scale(0.8); opacity: 0; } 100% { transform: translateY(0) scale(1); opacity: 1; } }
        .falling-leaves { position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow: hidden; z-index: 10; }
        .leaf { position: absolute; top: -10%; font-size: 1.5rem; color: #fde047; opacity: 0; animation: fall 10s linear infinite; }
        .leaf.leaf-2 { color: #fef08a; }
        .leaf.leaf-3 { color: #fff; }
        .premium-gradient { background: linear-gradient(135deg, #f5f7fa 0%, #e8edf2 100%); }
        .title-gradient { background: linear-gradient(90deg, #D62828 0%, #4B0000 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }
        .falling-coins { position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow: hidden; z-index: 10; }
        .coin { position: absolute; top: -5%; width: 10px; height: 10px; background: radial-gradient(circle, #ffd700, #f7b733); border-radius: 50%; box-shadow: 0 0 4px rgba(255, 215, 0, 0.6); opacity: 0; animation: fall 15s linear infinite; }
        @keyframes fall { 0% { transform: translateY(0) rotateZ(0deg); opacity: 0; } 10% { opacity: 1; } 100% { transform: translateY(110vh) rotateZ(360deg); opacity: 0; } }
    </style>
</head>
<body class="w-full h-screen overflow-hidden">

    <div id="waiting-state" class="w-full h-full flex flex-col items-center justify-center p-6 text-center transition-all duration-500 hidden">
        <h1 class="text-3xl font-bold text-gray-800 mb-2">Thông tin thanh toán</h1>
        <p class="text-xl text-gray-600 mb-4">Quý khách vui lòng kiểm tra và thanh toán</p>
        
        <div class="bg-white p-6 rounded-2xl shadow-xl w-full max-w-sm mb-6">
            <p class="text-lg text-gray-700">Khách hàng:</p>
            <p id="customer-name" class="text-2xl font-bold text-blue-600 mb-2">...</p>
            <p id="customer-phone" class="text-lg text-gray-700 mb-4">...</p>
            
            <p class="text-lg text-gray-700">Số tiền cần thanh toán:</p>
            <p id="total-amount" class="text-5xl font-extrabold text-red-600 mb-4">0 ₫</p>
        </div>

        <div class="qr-code-container">
            <img id="qr-image" src="https://placehold.co/300x300/e0e0e0/ffffff?text=Loading..." alt="Mã QR Thanh toán" class="rounded-2xl shadow-lg w-72 h-72">
        </div>
        <p class="text-lg text-gray-700 mt-4">Quét mã VietQR để thanh toán</p>
        <p class="text-sm text-gray-500 mt-2">Ngân hàng: <?php echo $print_settings['company_bank_info'] ?? 'BIDV'; ?></p>
    </div>

    <div id="paid-state" class="w-full h-full flex flex-col items-center justify-center p-6 text-center transition-all duration-500 hidden">
        <div class="falling-leaves" id="leaf-container"></div>
        <div class="relative z-20">
            <?php if (!empty($logo_path)): ?>
                <img src="<?php echo $logo_path; ?>" alt="Logo" class="w-30 h-30 mx-auto mb-6 rounded-full shadow-lg" id="company-logo">
            <?php endif; ?>
            <h1 class="thank-you-title mb-4">CÁM ƠN VÀ HẸN GẶP LẠI QUÝ KHÁCH !</h1>
        </div>
    </div>

    <div id="idle-state" class="w-full h-full flex flex-col items-center justify-center p-6 text-center transition-all duration-500 premium-gradient relative">
        <div id="idle-coin-container" class="falling-coins"></div>
        <div class="relative z-20">
            <?php if (!empty($logo_path)): ?>
                <img src="<?php echo $logo_path; ?>" alt="Logo" class="w-36 h-36 mx-auto mb-6 rounded-full" id="idle-logo">
            <?php endif; ?>
            <h1 class="text-5xl font-bold title-gradient">Kính chào Quý khách!</h1>
            <p class="text-2xl text-gray-600 mt-3">Vui lòng chờ nhân viên tạo đơn hàng...</p>
        </div>
    </div>

    <script>
        // --- DỮ LIỆU ĐỘNG TỪ PHP (ĐÃ SỬA ĐỂ LẤY TỪ DB) ---
        const BANK_BIN = "<?php echo $bank_bin; ?>";
        const ACCOUNT_NO = "<?php echo $account_no; ?>";
        const ACCOUNT_NAME = "<?php echo $account_name; ?>";
        const QR_TEMPLATE = "compact2";
        const LOGO_URL = "<?php echo $logo_path; ?>";
        
        const el = {
            waitingState: document.getElementById('waiting-state'),
            paidState: document.getElementById('paid-state'),
            idleState: document.getElementById('idle-state'),
            customerName: document.getElementById('customer-name'),
            customerPhone: document.getElementById('customer-phone'),
            totalAmount: document.getElementById('total-amount'),
            qrImage: document.getElementById('qr-image'),
            leafContainer: document.getElementById('leaf-container'),
            idleCoinContainer: document.getElementById('idle-coin-container'),
            companyLogo: document.getElementById('company-logo'),
            idleLogo: document.getElementById('idle-logo')
        };
        
        let currentOrderId = 0;
        let paidTimeout; 
        
        function formatNumber(num) {
            return (parseFloat(num) || 0).toLocaleString('vi-VN');
        }
        
        function encodeRFC3986(str) {
            return encodeURIComponent(str).replace(/[!*'()]/g, (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase());
        }

        // Hàm tạo link VietQR động
        function generateQRUrl(amount, content) {
            const cleanContent = content.normalize("NFD").replace(/[\u0300-\u036f]/g, "").replace(/đ/g, "d").replace(/Đ/g, "D").replace(/[^a-zA-Z0-9\s]/g, '').trim().replace(/\s+/g, ' ');
            const encodedContent = encodeRFC3986(cleanContent);
            const encodedAccountName = encodeRFC3986(ACCOUNT_NAME);
            // Tạo link ảnh QR Code động dựa trên thông tin từ Database
            return `https://img.vietqr.io/image/${BANK_BIN}-${ACCOUNT_NO}-${QR_TEMPLATE}.png?amount=${amount}&addInfo=${encodedContent}&accountName=${encodedAccountName}`;
        }
        
        function updateDisplay(state) {
            const { payment_status, order_id, order_code, customer_name, customer_phone, total_amount } = state;

            if (payment_status === 'waiting') {
                if (currentOrderId !== order_id) {
                    clearTimeout(paidTimeout);
                    currentOrderId = order_id;
                    el.customerName.textContent = customer_name || 'Khách lẻ';
                    el.customerPhone.textContent = customer_phone || '';
                    el.totalAmount.textContent = `${formatNumber(total_amount)} ₫`;
                    
                    // Tạo nội dung chuyển khoản: Tên khách + Mã đơn
                    const transferContent = `${customer_name.replace(/\s/g, '').slice(0, 10)} ${order_code}`;
                    el.qrImage.src = generateQRUrl(total_amount, transferContent);
                    
                    showState('waiting');
                }
            } else if (payment_status === 'paid') {
                // Khi nhân viên bấm Hoàn thành/Thanh toán xong
                if (order_id === currentOrderId && !el.paidState.classList.contains('visible')) {
                    clearTimeout(paidTimeout);
                    showState('paid');
                    createFallingLeaves();
                    // Tự động quay về màn hình chờ sau 5 giây
                    paidTimeout = setTimeout(() => {
                        resetToIdle();
                    }, 5000);
                }
            } else if (payment_status === 'idle') {
                if (!el.paidState.classList.contains('visible')) {
                    currentOrderId = 0;
                    showState('idle');
                }
            }
        }

        function showState(stateToShow) {
            ['waiting', 'paid', 'idle'].forEach(state => {
                const element = el[state + 'State'];
                if (state === stateToShow) {
                    element.classList.remove('hidden');
                    setTimeout(() => element.classList.add('visible'), 20); 
                } else {
                    element.classList.remove('visible');
                    element.classList.add('hidden');
                }
            });
        }
        
        async function resetToIdle() {
            showState('idle');
            el.leafContainer.innerHTML = '';
            el.qrImage.src = "https://placehold.co/300x300/e0e0e0/ffffff?text=Loading...";
            currentOrderId = 0;
            
            try {
                await fetch('../../ajax/reset_payment_status.php');
            } catch (error) {
                console.error('Không thể reset trạng thái server:', error);
            }
        }

        async function pollStatus() {
            try {
                // Gọi file AJAX để lấy trạng thái mới nhất
                const response = await fetch('../../ajax/get_payment_status.php?t=' + new Date().getTime());
                if (!response.ok) return;
                const data = await response.json();
                if (data.status === 'success') {
                    updateDisplay(data);
                }
            } catch (error) {
                console.error("Lỗi kết nối: ", error);
            }
        }
        
        // Hiệu ứng lá rơi
        function createFallingLeaves() {
            el.leafContainer.innerHTML = '';
            const items = ['Tài', 'Lộc', '₫', 'Phát'];
            for (let i = 0; i < 30; i++) {
                const leaf = document.createElement('div');
                leaf.className = `leaf leaf-${(i % 3) + 1}`;
                leaf.textContent = items[i % items.length];
                leaf.style.left = `${Math.random() * 100}vw`;
                leaf.style.animationDelay = `${Math.random() * 10}s`;
                leaf.style.animationDuration = `${5 + Math.random() * 5}s`;
                leaf.style.fontSize = `${1 + Math.random()}rem`;
                el.leafContainer.appendChild(leaf);
            }
        }
        
        function createFallingCoins() {
            el.idleCoinContainer.innerHTML = '';
            for (let i = 0; i < 70; i++) {
                const coin = document.createElement('div');
                coin.className = 'coin';
                coin.style.left = `${Math.random() * 100}vw`;
                coin.style.animationDelay = `${Math.random() * 15}s`;
                coin.style.animationDuration = `${10 + Math.random() * 10}s`;
                coin.style.opacity = Math.random() * 0.5 + 0.3;
                coin.style.transform = `scale(${Math.random() * 0.5 + 0.5})`;
                el.idleCoinContainer.appendChild(coin);
            }
        }
        
        document.addEventListener('DOMContentLoaded', () => {
            if (!LOGO_URL) {
                if(el.companyLogo) el.companyLogo.classList.add('hidden');
                if(el.idleLogo) el.idleLogo.classList.add('hidden');
            }
            createFallingCoins();
            pollStatus();
            setInterval(pollStatus, 2000); // Kiểm tra trạng thái mỗi 2 giây
        });
        
    </script>
</body>
</html>