<?php
include '../../function/connect.php';
session_start();

 $id_login  = $_SESSION['id'];
 $extplayer = $_SESSION['extplayer'];
 $tanggal   = date('Y-m-d H:i:s');

if (!isset($_POST['submit'])) {
    header("Location: ../index.php?page=deposit");
    exit;
}

 $nominal     = (int) $_POST['nominal'];
 $metode_id   = $_POST['metode'];
 $bonus_id    = $_POST['bonus'] ?? 'tanpabonus';
 $dari_bank   = $_POST['dari_bank'] ?? '';
 $keterangan  = $_POST['keterangan'] ?? '';
 $gambar      = 'no-image.png';

// Cek deposit pending sebelumnya
 $cek = mysqli_query($koneksi, "SELECT id FROM tb_transaksi WHERE id_user='$extplayer' AND transaksi='Top Up' AND status='Pending'");
if (mysqli_num_rows($cek) > 0) {
    header("Location: ../index.php?page=deposit&pesan=13");
    exit;
}

// Cek minimal deposit
 $web = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT min_depo FROM tb_web"));
if ($nominal < (int)$web['min_depo']) {
    header("Location: ../index.php?page=deposit&pesan=16");
    exit;
}

// Tentukan metode pembayaran
if ($metode_id === 'QRIS') {
    $metode = 'QRIS';
} elseif ($metode_id === 'QRIS_MANUAL') {
    $metode = 'QRIS Manual';
} else {
    $bank = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT nama_bank FROM tb_bank WHERE id='$metode_id'"));
    $metode = $bank['nama_bank'];
}

// ================= UPLOAD BUKTI TRANSFER =================
if ($metode !== 'QRIS' && !empty($_FILES['bukti_transfer']['name'])) {

    $allow = ['jpg', 'jpeg', 'png'];
    $file  = $_FILES['bukti_transfer'];
    $ext   = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));

    // Validasi ekstensi & ukuran
    if (!in_array($ext, $allow) || $file['size'] > 1044070) {
        header("Location: ../index.php?page=deposit&pesan=11");
        exit;
    }

    // Path folder upload
    $upload_dir = __DIR__ . '/../../uploads/bukti_transfer/';

    // Auto-create folder kalau belum ada
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0755, true);
    }

    // Nama file unik pakai timestamp
    $gambar = time() . '_' . preg_replace('/[^a-zA-Z0-9.\-_]/', '', $file['name']);

    // Upload file
    $upload_ok = move_uploaded_file($file['tmp_name'], $upload_dir . $gambar);

    // GAGAL UPLOAD? Batalkan, jangan masukin ke database
    if (!$upload_ok) {
        // Log error buat debugging (hapus kalau udah yakin aman)
        error_log("UPLOAD GAGAL | User: $extplayer | Tmp: {$file['tmp_name']} | Dest: " . $upload_dir . $gambar);
        header("Location: ../index.php?page=deposit&pesan=upload_gagal");
        exit;
    }
}

// ================= BONUS =================
 $bonus_data = null;
if ($bonus_id !== 'tanpabonus') {
    $bonus_data = mysqli_fetch_assoc(mysqli_query($koneksi, "SELECT id, persen, minimal_deposit, type_bonus FROM tb_promosi WHERE id='$bonus_id' AND status='active'"));
    if (!$bonus_data) {
        header("Location: ../index.php?page=deposit&pesan=bonus_invalid");
        exit;
    }

    if ($bonus_data['type_bonus'] === 'new_member') {
        $cek_nm = mysqli_query($koneksi, "SELECT id FROM tb_transaksi WHERE id_user='$extplayer' AND transaksi='Top Up' AND status='Sukses' LIMIT 1");
        if (mysqli_num_rows($cek_nm) > 0) {
            header("Location: ../index.php?page=deposit&pesan=bonus_only_new_member");
            exit;
        }
    }

    if ($nominal < (int)$bonus_data['minimal_deposit']) {
        header("Location: ../index.php?page=deposit&pesan=15");
        exit;
    }
}

// ================= SIMPAN TRANSAKSI =================
 $insert_transaksi = mysqli_query($koneksi, "
    INSERT INTO tb_transaksi (gambar, tanggal, transaksi, total, dari_bank, metode, bonus, keterangan, status, id_user)
    VALUES ('$gambar', '$tanggal', 'Top Up', '$nominal', '$dari_bank', '$metode', '$bonus_id', '$keterangan', 'Pending', '$extplayer')
");

if (!$insert_transaksi) {
    // Kalau insert gagal, hapus file yang udah keupload biar nggak numpuk
    if ($gambar !== 'no-image.png' && file_exists($upload_dir . $gambar)) {
        unlink($upload_dir . $gambar);
    }
    header("Location: ../index.php?page=deposit&pesan=10");
    exit;
}

// ================= SIMPAN BONUS =================
if ($bonus_data) {
    $nominal_bonus = ($nominal * (int)$bonus_data['persen']) / 100;
    if ($nominal_bonus <= 0) {
        header("Location: ../index.php?page=deposit&pesan=bonus_invalid");
        exit;
    }
    mysqli_query($koneksi, "INSERT INTO tb_bonus (id_user, id_bonus, nominal, status, tanggal) VALUES ('$extplayer', '{$bonus_data['id']}', '$nominal_bonus', 'Pending', '$tanggal')");
}

header("Location: ../index.php?page=deposit&pesan=9");
exit;