<?php
// Wajib ditaruh paling atas biar session kebaca
session_start();
header('Content-Type: application/json');

// Pastikan koneksi ke database bener
if (file_exists('../connect.php')) {
    require_once '../connect.php'; 
} else {
    require_once 'connect.php'; 
}

require_once 'class.sitranfer.php'; 

// AMBIL KEY DARI DATABASE (BIAR SINKRON SAMA ADMIN PANEL)
$web_sett = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT sitransfer_key FROM tb_web LIMIT 1"));
$apiKey = $web_sett['sitransfer_key'];

// PANGGIL CLASS Sambil BAWA KEY DARI DATABASE
$sitransfer = new SiTransfer($apiKey);

// AMBIL DARI AJAX (nominal & channel)
$channel = $_POST['channel'] ?? null;
$nominal = $_POST['nominal'] ?? null; 
$bonus   = $_POST['bonus'] ?? 'tanpabonus';

// SINKRONISASI SESSION PLAYER DARI FILE LOGIN LU
$player  = $_SESSION['extplayer'] ?? $_SESSION['id'] ?? $_SESSION['username'] ?? null;

// Validasi awal biar gak lempar Invalid Action gajelas
if (!$player) {
    echo json_encode(['status' => false, 'message' => 'Error: Sesi login habis, silahkan login ulang!']);
    exit;
}
if (!$nominal || (int)$nominal <= 0) {
    echo json_encode(['status' => false, 'message' => 'Error: Nominal deposit tidak valid!']);
    exit;
}
if (!$channel) {
    echo json_encode(['status' => false, 'message' => 'Error: Metode pembayaran belum dipilih!']);
    exit;
}

try {
    $res = null;
    if (strtolower($channel) == 'qris') {
        $res = $sitransfer->generateQRIS($player, $nominal);
    } else if (strtolower($channel) == 'dana') {
        $res = $sitransfer->generateDana($player, $nominal);
    } else {
        echo json_encode(['status' => false, 'message' => 'Error: Channel pembayaran tidak didukung!']);
        exit;
    }
    
    // CEK RESPON API
    if ($res && isset($res['success']) && $res['success'] == true) {
        
        // AMBIL DATA DARI RESPON SITRANSFER
        $trx_id  = mysqli_real_escape_string($koneksi, $res['data']['transaction_id'] ?? '');
        $amount  = (int)$res['data']['amount'];
        $player_clean = mysqli_real_escape_string($koneksi, $player);
        $metode_bayar = strtoupper($channel);
        
        if (!empty($trx_id)) {
            // INSERT TRANSAKSI OTOMATIS
            mysqli_query($koneksi, "INSERT INTO tb_transaksi (tanggal, transaksi, total, metode, bonus, keterangan, status, id_user, reff_id) 
                                    VALUES (NOW(), 'Top Up', '$amount', '$metode_bayar', '$bonus', 'Pending Automated Payment', 'Pending', '$player_clean', '$trx_id')");
        }

        // Susun ulang responnya biar dibaca lancar sama JavaScript lu
        $output = [
            'status'  => true,
            'action'  => (strtolower($channel) == 'qris') ? 'qris' : 'redirect',
            'total'   => $amount,
            'message' => $res['message'],
            'reff_id' => $trx_id
        ];

        if (strtolower($channel) == 'qris') {
            $output['qris_image'] = $res['data']['qris_image'];
        } else {
            $output['redirect_url'] = $res['data']['payment_url'];
        }

        echo json_encode($output);

    } else {
        $msg = $res['message'] ?? 'Gagal konek ke API SiTransfer, cek log/saldo gateway!';
        echo json_encode(['status' => false, 'message' => $msg]);
    }
} catch (Exception $e) {
    echo json_encode(['status' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>
