<?php
// Nama file: halaman_pembayaran.php (dengan notifikasi expired)

require_once('setting/database.php'); // Sesuaikan path

// 1. Ambil ID Invoice dari URL
$nomor_invoice = isset($_GET['invoice']) ? htmlspecialchars($_GET['invoice']) : '';
if (empty($nomor_invoice)) {
    die("Error: Nomor Invoice tidak ditemukan.");
}

// 2. Ambil data transaksi dari database
$sql_get = "SELECT * FROM transaksi_qris WHERE nomor_invoice = ? LIMIT 1";
$stmt_get = mysqli_prepare($link, $sql_get);
mysqli_stmt_bind_param($stmt_get, "s", $nomor_invoice);
mysqli_stmt_execute($stmt_get);
$result_get = mysqli_stmt_get_result($stmt_get);
$transaksi = mysqli_fetch_assoc($result_get);
mysqli_stmt_close($stmt_get);

if (!$transaksi) { die("Transaksi tidak ditemukan."); }

// --- 3. LOGIKA VALIDASI SERVER-SIDE (YANG DIPERBARUI) ---
$status_db = $transaksi['status'];
$waktu_kedaluwarsa_db = $transaksi['waktu_kedaluwarsa'];

// Hanya cek waktu jika status masih 'pending'
if ($status_db === 'pending') {
    $waktu_sekarang = new DateTime();
    $waktu_kedaluwarsa = new DateTime($waktu_kedaluwarsa_db);

    if ($waktu_sekarang > $waktu_kedaluwarsa) {
        // Jika waktu sudah lewat, UPDATE status menjadi 'expired'
        $sql_update = "UPDATE transaksi_qris SET status = 'expired' WHERE nomor_invoice = ? AND status = 'pending'";
        $stmt_update = mysqli_prepare($link, $sql_update);
        mysqli_stmt_bind_param($stmt_update, "s", $nomor_invoice);
        mysqli_stmt_execute($stmt_update);
        mysqli_stmt_close($stmt_update);

        // Perbarui variabel status lokal agar tampilan sesuai
        $status_db = 'expired';
    }
}

// Siapkan variabel untuk ditampilkan di HTML
$qrisResultString = $transaksi['qris_string'];
$total_topup = $transaksi['total_topup'];

?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pembayaran</title>
    <?php if ($status_db === 'pending'): ?>
    <script type="text/javascript" src="https://unpkg.com/qr-code-styling@1.5.0/lib/qr-code-styling.js"></script>
    <?php endif; ?>
    <style>
        body { font-family: system-ui, -apple-system, sans-serif; display: flex; justify-content: center; align-items: center; min-height: 100vh; background-color: #f4f5f7; margin: 0; padding: 20px; }
        .card { background: white; padding: 30px; border-radius: 16px; box-shadow: 0 8px 30px rgba(0,0,0,0.1); text-align: center; max-width: 400px; width: 100%; }
        h2 { margin-top: 0; }
        .total-amount { font-size: 2em; font-weight: bold; }
        .invoice-id { font-size: 0.9em; color: #888; margin-top: 15px; }
        #countdown { margin-top: 20px; font-size: 1.1em; font-weight: bold; color: #d9534f; }
        .status-box { font-size: 1.2em; font-weight: bold; padding: 15px; border-radius: 8px; margin: 20px 0; }
        .status-paid { color: #155724; background-color: #d4edda; }
        .status-expired { color: #721c24; background-color: #f8d7da; }
        .btn-kembali { display: inline-block; text-decoration: none; background-color: #007bff; color: white; padding: 10px 20px; border-radius: 8px; margin-top: 20px; font-weight: bold; }
    </style>
</head>
<body>
    <div class="card">
        
        <?php if ($status_db === 'pending'): ?>
            <h2>Scan untuk Membayar</h2>
            <div id="qrcodeContainer" style="margin:20px 0;"></div>
            <div id="countdown"></div>
            <div class="total-amount" style="color:#333;">Rp <?= number_format($total_topup, 0, ',', '.'); ?></div>
            <div class="invoice-id">Order ID: <?= htmlspecialchars($nomor_invoice); ?></div>

        <?php elseif ($status_db === 'paid'): ?>
            <h2>Pembayaran Berhasil</h2>
            <div class="status-box status-paid">Transaksi ini sudah lunas.</div>
            <div class="total-amount" style="color:#28a745;">Rp <?= number_format($total_topup, 0, ',', '.'); ?></div>
            <div class="invoice-id">Order ID: <?= htmlspecialchars($nomor_invoice); ?></div>
        
        <?php elseif ($status_db === 'expired' || $status_db === 'canceled'): ?>
            <h2>Transaksi Kedaluwarsa</h2>
            <div class="status-box status-expired">Waktu pembayaran untuk transaksi ini telah habis.</div>
            <div class="invoice-id">Order ID: <?= htmlspecialchars($nomor_invoice); ?></div>
            <a href="/" class="btn-kembali">Kembali ke Beranda</a>
        
        <?php endif; ?>

    </div>

    <?php if ($status_db === 'pending'): ?>
    <script>
        const expiryTime = new Date("<?= $waktu_kedaluwarsa_db; ?>".replace(" ", "T")).getTime();
        const countdownElement = document.getElementById('countdown');

        const countdownInterval = setInterval(function() {
            const distance = expiryTime - new Date().getTime();
            if (distance < 0) {
                // Jika waktu habis saat halaman dibuka, refresh halaman
                // agar PHP bisa mengubah status dan menampilkan pesan expired.
                clearInterval(countdownInterval);
                window.location.reload(); 
                return;
            }
            const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((distance % (1000 * 60)) / 1000);
            countdownElement.innerHTML = `Selesaikan pembayaran dalam: ${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
        }, 1000);

        // Tampilkan QR Code
        const qrCode = new QRCodeStyling({
            width: 260, height: 260, data: "<?= $qrisResultString; ?>",
            dotsOptions: { color: "#000", type: "rounded" }
        });
        qrCode.append(document.getElementById("qrcodeContainer"));
    </script>
    <?php endif; ?>
</body>
</html>
