<?php
// 1. Bersihkan output biar nggak ada spasi/error teks yang ganggu JSON
ob_start();
error_reporting(0); // Matikan display error biar nggak ngerusak format JSON

header('Content-Type: application/json');
session_start();
include '../../function/connect.php'; 

// Token Bearer lu
$token = "229|MlsrvDeaCcDtJG4wgnDZjRiROtJLBRQfD7WAkCyd8ba08dff";

$nominal  = isset($_POST['nominal']) ? intval($_POST['nominal']) : 0;
$username = $_SESSION['username'] ?? 'Guest';

if ($nominal < 25000) {
    ob_clean();
    echo json_encode(["status" => false, "message" => "Minimal deposit 25.000"]);
    exit;
}

// 2. Kirim Request ke API
$order_id = "INV-" . time();
$data = ["merchant_order_id" => $order_id, "amount" => $nominal];

$ch = curl_init("https://payments.yah.or.id/api/payments/qris/create");
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_TIMEOUT => 30, // Biar nggak nunggu selamanya kalau API lemot
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer $token", 
        "Content-Type: application/json", 
        "Accept: application/json"
    ],
    CURLOPT_POSTFIELDS => json_encode($data)
]);

$response = curl_exec($ch);
$result = json_decode($response, true);
curl_close($ch);

// 3. Logika Nangkep Payload (Disesuaikan buat token baru lu)
$payload = $result['data']['qris_payload'] ?? ($result['qris_payload'] ?? null);
$total_final = $result['data']['total_amount'] ?? ($result['total_amount'] ?? $nominal);
$success = $result['success'] ?? false;

if ($success && $payload) {
    // 4. Query Database (Tanpa ID biar nggak Duplicate Entry '0')
    $query = "INSERT INTO tb_transaksi (id_user, total, transaksi, dari_bank, metode, status, tanggal, gambar) 
              VALUES ('$username', '$total_final', 'Top Up', 'QRIS', 'QRIS', 'Pending', NOW(), 'no-image.png')";
    
    if (mysqli_query($koneksi, $query)) {
        ob_clean();
        echo json_encode([
            "status" => true,
            "qris_payload" => $payload,
            "total" => $total_final
        ]);
    } else {
        ob_clean();
        echo json_encode(["status" => false, "message" => "Database Error: Simpan transaksi gagal"]);
    }
} else {
    ob_clean();
    // Kalau payload kosong, kasih tau apa kata providernya
    $msg = $result['message'] ?? "Payload Kosong (Cek Dashboard Yah.or.id)";
    echo json_encode(["status" => false, "message" => "Provider: " . $msg]);
}
exit;
