<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
session_start();
header('Content-Type: application/json');

include '../db/koneksi.php';

$response = ['success' => false, 'message' => 'Terjadi kesalahan tak terduga.'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $extplayer = $_SESSION['extplayer'] ?? '';
    $username  = $_SESSION['username'] ?? '';

    if (empty($extplayer) || empty($username)) {
        echo json_encode(['success' => false, 'message' => 'Sesi pengguna tidak valid.']);
        exit;
    }

    $qpending = mysqli_query($koneksi, "SELECT * FROM tb_deposit WHERE extplayer='" . $_SESSION['extplayer'] . "' AND status= 'Pending'");
    if (mysqli_num_rows($qpending) > 0) {
        echo json_encode(['success' => false, 'message' => 'Anda memiliki deposit pending. Silakan selesaikan atau batalkan deposit tersebut sebelum membuat yang baru.']);
        exit;
    }

    $bank_asal = mysqli_real_escape_string($koneksi, $_POST['user_bank_info'] ?? '');
    $bank_tujuan_id   = (int) ($_POST['master_bank_accounts_id'] ?? 0);
    $promo_id = (int) ($_POST['promo_id'] ?? 0);
    $amount = $_POST['amount'] ?? '0';

    $cleanAmount = preg_replace('/[^0-9]/', '', $amount);
    $jumlah = (int)$cleanAmount;
    $admin_fee = $_POST['admin_fee'] ?? 0;
    $admin_type = $_POST['admin_fee_type'] ?? 'percentage';
    $bukti_base64 = $_POST['receipt_base64'] ?? '';
    $status = 'Pending';
    $bonus = 0;

    if ($jumlah <= 0 || $bank_tujuan_id === 0) {
        echo json_encode(['success' => false, 'message' => 'Pastikan semua data telah diisi dengan benar.']);
        exit;
    }

    // if (!empty($promo_id)) {
    //     $qPromo = mysqli_query($koneksi, "SELECT * FROM promos WHERE id='$promo_id'");
    //     if ($qPromo && mysqli_num_rows($qPromo) > 0) {
    //         $promoData   = mysqli_fetch_assoc($qPromo);
    //         $bonusPersen = $promoData['bonus_percentage'];
    //         $maxBonus    = $promoData['max_bonus'];
    //         $bonus       = min(($jumlah * $bonusPersen / 100), $maxBonus);
    //     }
    // }

    $qBank = mysqli_query($koneksi, "SELECT * FROM bank WHERE id_bank='$bank_tujuan_id'");
    if (!$qBank || mysqli_num_rows($qBank) === 0) {
        echo json_encode(['success' => false, 'message' => 'Rekening tujuan tidak ditemukan.']);
        exit;
    }
    $bankData    = mysqli_fetch_assoc($qBank);
    $bank_tujuan = $bankData['jenis_bank'] . ' - ' . $bankData['nomor_rekening_bank'] . ' (' . $bankData['atas_nama_bank'] . ')';

    $ref = 'DEP' . strtoupper(substr(md5(uniqid()), 0, 8));

    $bukti_transfer_path = '';
    if (!empty($bukti_base64)) {
        $folderPath = $_SERVER['DOCUMENT_ROOT'] . '/asset/transaksi/';
        if (!file_exists($folderPath)) {
            mkdir($folderPath, 0777, true);
        }

        if (preg_match('/^data:image\/(\w+);base64,/', $bukti_base64, $type)) {
            $bukti_base64 = substr($bukti_base64, strpos($bukti_base64, ',') + 1);
            $type = strtolower($type[1]);
            if (!in_array($type, ['jpg', 'jpeg', 'png', 'gif'])) {
                echo json_encode(['success' => false, 'message' => 'Format gambar tidak didukung.']);
                exit;
            }

            $bukti_base64 = base64_decode($bukti_base64);
            if ($bukti_base64 === false) {
                echo json_encode(['success' => false, 'message' => 'Gagal decode gambar base64.']);
                exit;
            }

            $fileName = 'bukti_' . $ref . '.' . $type;
            $filePath = $folderPath . $fileName;

            file_put_contents($filePath, $bukti_base64);

            $bukti_transfer_path = '/asset/transaksi/' . $fileName;
        } else {
            echo json_encode(['success' => false, 'message' => 'Format data base64 tidak valid.']);
            exit;
        }
    }

    $stmt = $koneksi->prepare("
        INSERT INTO tb_deposit 
        (extplayer, username, ref, jumlah, bonus, bukti, bank_asal, bank_tujuan, status, created_at, updated_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
    ");
    $stmt->bind_param('sssisssss', $extplayer, $username, $ref, $jumlah, $bonus, $bukti_transfer_path, $bank_asal, $bank_tujuan, $status);

    if ($stmt->execute()) {
        $response = ['success' => true, 'message' => 'Deposit berhasil dikirim, menunggu konfirmasi admin.'];
    } else {
        $response = ['success' => false, 'message' => 'Gagal menyimpan deposit: ' . $stmt->error];
    }

    $stmt->close();
}

echo json_encode($response);
exit;
