<?php
// MATIKAN JIKA SUDAH PRODUCTION
ini_set('display_errors', 1);
error_reporting(E_ALL);

// =================================================================
// KONFIGURASI
// =================================================================
$db_host = 'localhost';
$db_user = 'resende1_api2';
$db_pass = 'resende1_api2';
$db_name = 'resende1_api2';
$atlantic_api_key = '2IlkUzIHCJNNVu4g5oRoCcNxeUTaxP3tJngs7uOf8x6pOqAGwoI72aQ3Vn3nhEuXfonu0kzmIm14RRge5xqPuDCQIq8icJvEaYFU';

// =================================================================
// PROSES DATA DARI FORM
// =================================================================
$token_topup = $_POST['token_topup'] ?? null;
$nominal = (float) ($_POST['total_topup'] ?? 0);
$email_user = $_POST['email_user'] ?? 'emailtidakada@example.com';
$pilihan_pembayaran = explode('|', $_POST['metode_pembayaran'] ?? '');
$metode = $pilihan_pembayaran[0] ?? null;
$type = $pilihan_pembayaran[1] ?? null;
if (!$token_topup || !$metode || !$type || $nominal <= 0) die("Data tidak lengkap.");
$reff_id = 'INV-' . time() . '-' . strtoupper(substr(md5($email_user), 0, 5));

// =================================================================
// PANGGIL API /deposit/create
// =================================================================
$post_fields = http_build_query(['api_key' => $atlantic_api_key, 'reff_id' => $reff_id, 'nominal' => $nominal, 'type' => $type, 'method' => $metode]);
$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => 'https://atlantich2h.com/deposit/create',
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_CUSTOMREQUEST => 'POST',
  CURLOPT_POSTFIELDS => $post_fields,
  CURLOPT_HTTPHEADER => array('Content-Type: application/x-www-form-urlencoded'),
));
$response = curl_exec($curl);
curl_close($curl);
$invoice_data_api = json_decode($response, true);
if (($invoice_data_api['status'] ?? false) !== true) die("Gagal membuat invoice dari API: " . ($invoice_data_api['data']['msg'] ?? 'Error tidak diketahui'));

// =================================================================
// EKSTRAK SEMUA KEMUNGKINAN DATA & SIMPAN KE DATABASE
// =================================================================
$details = $invoice_data_api['data'];
$amount_to_pay = $details['nominal'] ?? $nominal; // Nominal dari API adalah yang paling akurat
// Data Spesifik per Tipe
$qr_string = $details['qr_string'] ?? null;
$qr_image = $details['qr_image'] ?? null;
$nomor_va = $details['nomor_va'] ?? null;
$payment_url = $details['url'] ?? null;
$bank_name = $details['bank'] ?? null;
$account_number = $details['tujuan'] ?? null;
$account_holder = $details['atas_nama'] ?? null;
// Data Umum
$expired_timestamp = strtotime($details['expired_at'] ?? '+1 hour');
$expired_at_db = date("Y-m-d H:i:s", $expired_timestamp);

$conn = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($conn->connect_error) die("Koneksi database gagal: " . $conn->connect_error);
$sql = "INSERT INTO transaksi (token_topup, reff_id, total_topup, email_user, metode_pembayaran, payment_code, qr_string, payment_url, bank_name, account_number, account_holder, expired_at, status_pembayaran) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'PENDING')
        ON DUPLICATE KEY UPDATE 
        reff_id = VALUES(reff_id), metode_pembayaran = VALUES(metode_pembayaran), payment_code = VALUES(payment_code), qr_string = VALUES(qr_string), payment_url = VALUES(payment_url), bank_name = VALUES(bank_name), account_number = VALUES(account_number), account_holder = VALUES(account_holder), expired_at = VALUES(expired_at), status_pembayaran = 'PENDING'";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssisssssssss", $token_topup, $reff_id, $amount_to_pay, $email_user, $metode, $nomor_va, $qr_string, $payment_url, $bank_name, $account_number, $account_holder, $expired_at_db);
$stmt->execute();
$stmt->close();
$conn->close();
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Invoice Pembayaran</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
</head>
<body class="bg-light">
    <div class="container py-5">
        <div class="row justify-content-center">
            <div class="col-lg-6">
                <div class="card shadow-lg border-0 rounded-4">
                    <div class="card-header bg-primary text-white text-center rounded-top-4">
                        <h4 class="mb-0 py-2">Selesaikan Pembayaran</h4>
                    </div>
                    <div class="card-body p-4">
                        <div class="text-center mb-4">
                            <p class="text-muted mb-1">Total yang harus dibayar</p>
                            <h2 class="fw-bolder text-primary">Rp <?php echo number_format($amount_to_pay, 0, ',', '.'); ?></h2>
                        </div>
                        <ul class="list-group list-group-flush mb-4">
                            <li class="list-group-item d-flex justify-content-between"><span>ID Referensi</span><strong><?php echo htmlspecialchars($reff_id); ?></strong></li>
                            <li class="list-group-item d-flex justify-content-between text-danger"><span>Bayar Sebelum</span><strong><?php echo date("d M Y, H:i", $expired_timestamp); ?> WIB</strong></li>
                        </ul>

                        <?php if (!empty($qr_image)): ?>
                        <div class="text-center">
                            <h5 class="fw-bold"><?php echo htmlspecialchars($metode); ?></h5>
                            <p>Scan QR Code di bawah dengan aplikasi perbankan atau e-wallet Anda.</p>
                            <img src="<?php echo htmlspecialchars($qr_image); ?>" alt="QR Code Pembayaran" class="img-fluid border rounded p-2">
                        </div>
                        
                        <?php elseif (!empty($nomor_va)): ?>
                        <div class="text-center">
                            <h5 class="fw-bold">Virtual Account <?php echo htmlspecialchars($bank_name); ?></h5>
                            <p>Salin nomor Virtual Account di bawah dan bayar melalui <?php echo htmlspecialchars($bank_name); ?>.</p>
                            <div class="input-group my-3">
                                <input type="text" class="form-control form-control-lg text-center fs-4 fw-bold" id="paymentCode" value="<?php echo htmlspecialchars($nomor_va); ?>" readonly>
                                <button class="btn btn-outline-primary" type="button" onclick="copyToClipboard()">
                                    <i class="bi bi-clipboard"></i> Salin
                                </button>
                            </div>
                        </div>

                        <?php elseif (!empty($payment_url)): ?>
                        <div class="text-center">
                            <h5 class="fw-bold">Lanjutkan Pembayaran <?php echo htmlspecialchars($metode); ?></h5>
                            <p>Klik tombol di bawah untuk diarahkan ke halaman pembayaran.</p>
                            <a href="<?php echo htmlspecialchars($payment_url); ?>" class="btn btn-success btn-lg w-100 py-3 fw-bold">
                                Lanjutkan ke Pembayaran
                            </a>
                        </div>
                        
                        <?php elseif (!empty($account_number)): ?>
                        <div>
                            <h5 class="fw-bold text-center">Transfer Bank <?php echo htmlspecialchars($bank_name); ?></h5>
                            <div class="alert alert-warning text-center">
                                <strong>PENTING!</strong> Mohon transfer dengan nominal yang **sama persis** hingga 3 digit terakhir.
                            </div>
                            <ul class="list-group">
                                <li class="list-group-item d-flex justify-content-between"><span>Bank Tujuan</span><strong><?php echo htmlspecialchars($bank_name); ?></strong></li>
                                <li class="list-group-item d-flex justify-content-between"><span>Nomor Rekening</span><strong><?php echo htmlspecialchars($account_number); ?></strong></li>
                                <li class="list-group-item d-flex justify-content-between"><span>Atas Nama</span><strong><?php echo htmlspecialchars($account_holder); ?></strong></li>
                            </ul>
                        </div>
                        <?php endif; ?>

                    </div>
                </div>
            </div>
        </div>
    </div>
    <script>
        // Fungsi untuk menyalin teks ke clipboard
        function copyToClipboard() {
            const paymentCodeEl = document.getElementById('paymentCode');
            paymentCodeEl.select();
            document.execCommand('copy');
            alert('Kode pembayaran berhasil disalin: ' + paymentCodeEl.value);
        }
    </script>
</body>
</html>
