<?php
session_start();
include 'config.php';

// Cek Login
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php"); exit();
}

$user_id = $_SESSION['user_id'];
$sql = "SELECT username FROM users WHERE id = $user_id";
$user = $conn->query($sql)->fetch_assoc();

// Set Menu Aktif
$active_menu = 'qris'; 
?>

<!DOCTYPE html>
<html lang="id" class="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>QRIS Receive & Scan</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = { darkMode: 'class', theme: { extend: { colors: { primary: '#10b981', darkbg: '#0f172a' } } } }
    </script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <script src="https://unpkg.com/html5-qrcode" type="text/javascript"></script>
</head>
<body class="bg-gray-100 dark:bg-darkbg text-gray-800 dark:text-gray-200 transition-colors duration-300">

    <div class="max-w-md mx-auto min-h-screen relative shadow-2xl bg-white dark:bg-slate-900 pb-24">
        
        <div class="bg-slate-800 p-6 rounded-b-[2rem] text-white shadow-lg text-center relative z-10">
            <h1 class="font-bold text-xl mb-1">QRIS / Scan</h1>
            <p class="text-xs text-gray-400">Terima dana atau scan member lain</p>
        </div>

        <div class="p-6 flex flex-col items-center justify-center mt-2 space-y-6">
            
            <div class="bg-white p-4 rounded-3xl shadow-xl border-4 border-primary/20 relative group">
                <img src="https://api.qrserver.com/v1/create-qr-code/?size=250x250&data=<?php echo $user['username']; ?>" alt="QR Code" class="w-56 h-56 object-contain">
                <div class="absolute -bottom-4 left-1/2 transform -translate-x-1/2 bg-primary text-white px-4 py-1 rounded-full text-xs font-bold shadow-lg">
                    MY QR CODE
                </div>
            </div>

            <div class="text-center w-full">
                <div class="bg-gray-50 dark:bg-slate-800 p-3 rounded-xl flex justify-between items-center border border-gray-200 dark:border-slate-700 max-w-xs mx-auto">
                    <span class="font-mono font-bold text-xl text-primary tracking-wide pl-2" id="usernameText"><?php echo $user['username']; ?></span>
                    <button onclick="copyUsername()" class="bg-white dark:bg-slate-700 w-10 h-10 rounded-lg shadow-sm text-gray-500 hover:text-primary hover:bg-emerald-50 transition flex items-center justify-center">
                        <i class="fas fa-copy"></i>
                    </button>
                </div>
            </div>

            <div class="w-full max-w-xs">
                <button onclick="openScanner()" class="w-full bg-slate-800 hover:bg-slate-700 text-white font-bold py-4 rounded-2xl shadow-lg flex items-center justify-center gap-3 transition transform active:scale-95 border border-slate-600">
                    <div class="bg-white/10 p-2 rounded-full"><i class="fas fa-camera text-xl"></i></div>
                    <div class="text-left">
                        <p class="text-sm">Scan Kamera</p>
                        <p class="text-[10px] text-gray-400 font-normal">Transfer ke Member Lain</p>
                    </div>
                </button>
            </div>

            <div class="p-4 bg-yellow-50 dark:bg-yellow-900/20 rounded-xl text-xs text-yellow-700 dark:text-yellow-500 w-full flex gap-3 items-start border border-yellow-100 dark:border-yellow-900/30">
                <i class="fas fa-info-circle text-lg mt-0.5"></i>
                <p>Gunakan tombol <b>Scan Kamera</b> untuk memindai QR Code member lain dan melakukan transfer saldo secara instan.</p>
            </div>

        </div>

        <?php if(file_exists('footer_nav.php')) include 'footer_nav.php'; ?>

    </div>

    <div id="scannerModal" class="fixed inset-0 z-50 bg-black/90 hidden flex-col items-center justify-center">
        <div class="absolute top-5 right-5 z-50">
            <button onclick="closeScanner()" class="bg-white/20 text-white w-10 h-10 rounded-full flex items-center justify-center hover:bg-red-500 transition"><i class="fas fa-times"></i></button>
        </div>
        <div class="text-white mb-4 font-bold text-lg">Arahkan ke QR Code Member</div>
        
        <div id="reader" class="w-full max-w-sm bg-black border-2 border-primary rounded-xl overflow-hidden shadow-2xl"></div>
        
        <p class="text-gray-400 text-xs mt-4">Pastikan cahaya cukup terang</p>
    </div>

    <script>
        // --- LOGIC COPY USERNAME ---
        function copyUsername() {
            const text = document.getElementById('usernameText').innerText;
            navigator.clipboard.writeText(text).then(() => {
                Swal.fire({
                    icon: 'success', title: 'Disalin!', text: text,
                    timer: 1000, showConfirmButton: false, toast: true, position: 'top',
                    background: '#10b981', color: '#fff', iconColor: '#fff'
                });
            });
        }

        // --- LOGIC SCANNER ---
        let html5QrcodeScanner;

        function openScanner() {
            document.getElementById('scannerModal').classList.remove('hidden');
            document.getElementById('scannerModal').classList.add('flex');

            // Inisialisasi Scanner
            html5QrcodeScanner = new Html5QrcodeScanner(
                "reader", { fps: 10, qrbox: {width: 250, height: 250} }
            );
            
            html5QrcodeScanner.render(onScanSuccess, onScanFailure);
        }

        function closeScanner() {
            document.getElementById('scannerModal').classList.add('hidden');
            document.getElementById('scannerModal').classList.remove('flex');
            
            // Matikan Kamera
            if(html5QrcodeScanner) {
                html5QrcodeScanner.clear().catch(error => {
                    console.error("Failed to clear html5QrcodeScanner. ", error);
                });
            }
        }

        function onScanSuccess(decodedText, decodedResult) {
            // Hentikan scan setelah berhasil
            html5QrcodeScanner.clear();
            closeScanner();

            // LOGIKA REDIRECT SETELAH SCAN
            // decodedText = Username dari QR yang discan
            Swal.fire({
                title: 'QR Terdeteksi!',
                text: 'Username: ' + decodedText,
                icon: 'success',
                showCancelButton: true,
                confirmButtonText: 'Lanjut Transfer',
                cancelButtonText: 'Batal',
                confirmButtonColor: '#10b981'
            }).then((result) => {
                if (result.isConfirmed) {
                    // ARAHKAN KE HALAMAN TRANSFER
                    // Ganti 'transfer.php' dengan nama file transfer anda yang sebenarnya
                    window.location.href = "transfer.php?to=" + encodeURIComponent(decodedText);
                }
            });
        }

        function onScanFailure(error) {
            // handle scan failure, usually better to ignore and keep scanning.
            // console.warn(`Code scan error = ${error}`);
        }
    </script>
</body>
</html>