<?php
// Nama file: payment.php (Versi Lengkap Final)

// --- 1. INISIALISASI & KONEKSI ---
require_once('setting/database.php'); // Pastikan path ini benar
define('YOUR_INTERNAL_SECRET', '27284b9e7047f18d8844572991d6eb4b');

// --- FUNGSI BANTUAN ---
function generateCRC16($str) {
    $crc = 0xFFFF; $strlen = strlen($str);
    for ($c = 0; $c < $strlen; $c++) {
        $crc ^= ord($str[$c]) << 8;
        for ($i = 0; $i < 8; $i++) {
            if ($crc & 0x8000) { $crc = ($crc << 1) ^ 0x1021; } 
            else { $crc = $crc << 1; }
        }
    }
    return strtoupper(str_pad(dechex($crc & 0xFFFF), 4, '0', STR_PAD_LEFT));
}

// --- 2. VALIDASI DATA POST & LOGIKA UTAMA ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Ambil dan validasi data POST
    $status_post = isset($_POST['status']) ? htmlspecialchars($_POST['status']) : null;
    $id_user = isset($_POST['id_user']) ? htmlspecialchars($_POST['id_user']) : null;
    $token_topup_post = isset($_POST['token_topup']) ? htmlspecialchars($_POST['token_topup']) : null;
    $jumlah_topup = isset($_POST['jumlah_topup']) ? (int)$_POST['jumlah_topup'] : 0;
    $kode_unik = isset($_POST['kode_unik']) ? (int)$_POST['kode_unik'] : 0;
    $total_topup_post = isset($_POST['total_topup']) ? (int)$_POST['total_topup'] : 0;
    $secret_callback = isset($_POST['secret_callback']) ? htmlspecialchars($_POST['secret_callback']) : null;

    if ($secret_callback !== YOUR_INTERNAL_SECRET) {
        die("Akses Ditolak: Kunci pengaman tidak valid.");
    }
    if ($status_post !== 'ok' || empty($token_topup_post) || $total_topup_post <= 0) {
        die("Data yang dikirim tidak lengkap atau tidak valid.");
    }

    // --- Validasi Deposit Pending ---
    $pesan_info = "";
    $sql_check = "SELECT * FROM transaksi_qris WHERE id_user = ? AND status = 'pending' LIMIT 1";
    if ($stmt_check = mysqli_prepare($link, $sql_check)) {
        mysqli_stmt_bind_param($stmt_check, "s", $id_user);
        mysqli_stmt_execute($stmt_check);
        $result_check = mysqli_stmt_get_result($stmt_check);
        
        if ($existing_transaksi = mysqli_fetch_assoc($result_check)) {
            // JIKA ADA TRANSAKSI PENDING, GUNAKAN DATA LAMA
            $pesan_info = "Anda masih memiliki transaksi tertunda. Selesaikan pembayaran di bawah ini.";
            $transaksi = $existing_transaksi;
        } else {
            // JIKA TIDAK ADA, BUAT TRANSAKSI BARU
            $total_topup = $total_topup_post;
            $nomor_invoice = $token_topup_post;
            
            $qrisStaticTemplate = "00020101021126670016COM.NOBUBANK.WWW0118B9360050300000907180214200300181683310303UMI51440014ID.CO.QRIS.WWW0215ID20254218126240303UMI5204481253033605802ID5913HERISHOP CELL6008SIDOARJO61056121162070703A01630454C1";
            $qrisDataWithoutCrc = substr($qrisStaticTemplate, 0, -4);
            $dynamicQris = str_replace("010211", "010212", $qrisDataWithoutCrc);
            $parts = explode("5802ID", $dynamicQris);
            $amountTag = "54" . str_pad(strlen($total_topup), 2, '0', STR_PAD_LEFT) . $total_topup;
            $finalString = $parts[0] . $amountTag . "5802ID" . $parts[1];
            $qrisResultString = $finalString . generateCRC16($finalString);
            $waktu_kedaluwarsa_db = date('Y-m-d H:i:s', strtotime('+15 minutes'));

            $sql_insert = "INSERT INTO transaksi_qris (id_user, nomor_invoice, jumlah_topup, kode_unik, total_topup, qris_string, waktu_kedaluwarsa) VALUES (?, ?, ?, ?, ?, ?, ?)";
            if ($stmt_insert = mysqli_prepare($link, $sql_insert)) {
                mysqli_stmt_bind_param($stmt_insert, "ssiiiss", $id_user, $nomor_invoice, $jumlah_topup, $kode_unik, $total_topup, $qrisResultString, $waktu_kedaluwarsa_db);
                if (!mysqli_stmt_execute($stmt_insert)) {
                    die("Error: Gagal menyimpan transaksi. Kemungkinan Order ID sudah ada.");
                }
                // Ambil data yang baru saja diinsert untuk ditampilkan
                $transaksi = [
                    'nomor_invoice' => $nomor_invoice, 'total_topup' => $total_topup,
                    'jumlah_topup' => $jumlah_topup, 'kode_unik' => $kode_unik,
                    'qris_string' => $qrisResultString, 'waktu_kedaluwarsa' => $waktu_kedaluwarsa_db,
                    'status' => 'pending'
                ];
            }
        }
        mysqli_stmt_close($stmt_check);
    }

} else {
    die("Akses tidak valid. Halaman ini harus diakses melalui POST.");
}

// --- 3. PERSIAPAN FINAL SEBELUM TAMPIL ---
$status_db = $transaksi['status'];
$waktu_kedaluwarsa_db = $transaksi['waktu_kedaluwarsa'];
$nomor_invoice = $transaksi['nomor_invoice'];

// Cek waktu jika status masih 'pending'
if ($status_db === 'pending' && new DateTime() > new DateTime($waktu_kedaluwarsa_db)) {
    $sql_update = "UPDATE transaksi_qris SET status = 'expired' WHERE nomor_invoice = ? AND status = 'pending'";
    if ($stmt_update = mysqli_prepare($link, $sql_update)) {
        mysqli_stmt_bind_param($stmt_update, "s", $nomor_invoice);
        mysqli_stmt_execute($stmt_update);
        $status_db = 'expired'; // Update status lokal untuk tampilan
    }
}
mysqli_close($link);
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Status Pembayaran</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <?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; 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.1em; font-weight: bold; padding: 15px; border-radius: 8px; margin: 20px 0; }
        .status-paid { color: #155724; background-color: #d4edda; }
        .status-canceled { color: #721c24; background-color: #f8d7da; }
        .info-message { color: #856404; background-color: #fff3cd; padding: 10px; border-radius: 8px; margin-bottom: 15px; }
        .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 (!empty($pesan_info)): ?>
            <div class="info-message"><?= $pesan_info; ?></div>
        <?php endif; ?>
        
        <?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($transaksi['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="invoice-id">Order ID: <?= htmlspecialchars($nomor_invoice); ?></div>
            <a href="/" class="btn-kembali">Kembali</a>
        <?php elseif ($status_db === 'canceled' || $status_db === 'expired'): ?>
            <h2>Transaksi Gagal</h2>
            <div class="status-box status-canceled">
                <?= ($status_db === 'expired') ? 'Waktu pembayaran telah habis.' : 'Transaksi ini telah dibatalkan.'; ?>
            </div>
            <div class="invoice-id">Order ID: <?= htmlspecialchars($nomor_invoice); ?></div>
            <a href="/" class="btn-kembali">Buat Transaksi Baru</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) {
                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);
        const qrCode = new QRCodeStyling({
            width: 260, height: 260, data: "<?= $transaksi['qris_string']; ?>",
            dotsOptions: { color: "#000", type: "rounded" }
        });
        qrCode.append(document.getElementById("qrcodeContainer"));
    </script>
    <?php endif; ?>
</body>
</html>
