<?php
require_once('session.php');

$metode = isset($_POST['metode']) ? $_POST['metode'] : '';
$nominal = preg_replace('/[^0-9]/','', $_POST['nominal']);
$pay_from = isset($_POST['pay_from']) ? $_POST['pay_from'] : '';
$catatan = isset($_POST['catatan']) ? $_POST['catatan'] : '';
$postID = intval($_POST['postID']);

$kode_unik = substr(str_shuffle("1234567890"),0,3);
$kd_transaksi = date('YmdHis').$kode_unik;

$totalBayar = (int)$nominal;
$created_date = date('Y-m-d H:i:s');

$bukti_transfer = null;

/* ========================================================
   CEK APAKAH ADA DEPOSIT YANG MASIH PENDING (BARU)
======================================================== */
$cekPending = mysqli_query($conn, "SELECT kd_transaksi FROM tb_transaksi WHERE userID='$postID' AND transaksi='Top Up' AND status='0' LIMIT 1");

if(mysqli_num_rows($cekPending) > 0){
    if($metode === 'qris_otomatis') {
        header('Content-Type: application/json');
        echo json_encode(['status' => 'error', 'message' => 'Anda masih memiliki permintaan deposit yang berstatus PENDING. Silahkan selesaikan atau batalkan terlebih dahulu.']);
        exit();
    } else {
        echo "<script>alert('Anda masih memiliki permintaan deposit yang berstatus PENDING. Silahkan selesaikan terlebih dahulu.');history.back();</script>";
        exit();
    }
}

/* ==========================
   CEK / BUAT SALDO USER
========================== */
$cekSaldo = mysqli_query($conn,"SELECT cuid FROM tb_balance WHERE userID='$postID'");

if(mysqli_num_rows($cekSaldo) == 0){
    mysqli_query($conn,"
        INSERT INTO tb_balance
        (userID,active,pending,transfer,payout,created_date)
        VALUES
        ('$postID','0','0','0','0',NOW())
    ");
}

/* ==========================
   UPLOAD BUKTI TRANSFER (Hanya untuk Deposit Manual)
========================== */
if(isset($_FILES['bukti_transfer']) && $_FILES['bukti_transfer']['error'] == 0){

    $target_dir = "../upload/bukti/";

    if(!is_dir($target_dir)){
        mkdir($target_dir,0777,true);
    }

    $ext_allowed = ['jpg','jpeg','png','gif','webp'];

    $file_name = $_FILES['bukti_transfer']['name'];
    $file_tmp = $_FILES['bukti_transfer']['tmp_name'];
    $file_size = $_FILES['bukti_transfer']['size'];

    $file_ext = strtolower(pathinfo($file_name,PATHINFO_EXTENSION));

    if(!in_array($file_ext,$ext_allowed)){
        if($metode === 'qris_otomatis') {
            header('Content-Type: application/json');
            echo json_encode(['status' => 'error', 'message' => 'Format file tidak didukung']);
            exit();
        } else {
            echo "<script>alert('Format file tidak didukung');history.back();</script>";
            exit();
        }
    }

    if($file_size > 5*1024*1024){
        if($metode === 'qris_otomatis') {
            header('Content-Type: application/json');
            echo json_encode(['status' => 'error', 'message' => 'File terlalu besar (Max 5MB)']);
            exit();
        } else {
            echo "<script>alert('File terlalu besar (Max 5MB)');history.back();</script>";
            exit();
        }
    }

    $new_name = time()."_".uniqid().".".$file_ext;
    $target_file = $target_dir.$new_name;

    if(move_uploaded_file($file_tmp,$target_file)){
        $bukti_transfer = $new_name;
    }
}

/* ==========================
   VALIDASI NOMINAL
========================== */
if($totalBayar < 10000){
    if($metode === 'qris_otomatis') {
        header('Content-Type: application/json');
        echo json_encode(['status' => 'error', 'message' => 'Minimal deposit adalah 10.000']);
        exit();
    } else {
        header('Location:../m/deposit.php?notif=1');
        exit();
    }
}

/* ==========================
   SIMPAN TRANSAKSI
========================== */
$insert_trx = mysqli_query($conn,"
    INSERT INTO tb_transaksi
    (kd_transaksi,date,transaksi,total,saldo,note,gameid,providerID,jenis,metode,pay_from,userID,status)
    VALUES
    ('$kd_transaksi','$created_date','Top Up','$totalBayar','0','$bukti_transfer','','0','1','$metode','$pay_from','$postID','0')
");

/* ==========================
   PENGKONDISIAN RESPON (PENTING!)
========================== */
if($metode === 'qris_otomatis') {
    // Jika via QRIS Otomatis, kirim respon JSON murni ke JavaScript agar gambar QR muncul
    header('Content-Type: application/json');
    if($insert_trx) {
        echo json_encode(['status' => 'success', 'message' => 'QRIS sukses di-generate', 'trxID' => $kd_transaksi]);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Gagal menyimpan ke database: ' . mysqli_error($conn)]);
    }
    exit();
} else {
    // Jika deposit manual bank biasa, alihkan halaman ke history seperti semula
    header("Location: ../m/history.php?trxID=$kd_transaksi");
    exit();
}
?>