<?php
// Debug: Enable error reporting untuk debugging
error_reporting(E_ALL);
ini_set('display_errors', 1); // Tampilkan error di browser untuk debugging
ini_set('log_errors', 1);

error_log("=== DEPOSIT.PHP START ===");
error_log("POST Data: " . print_r($_POST, true));
error_log("REQUEST Method: " . $_SERVER['REQUEST_METHOD']);
error_log("REQUEST URI: " . $_SERVER['REQUEST_URI']);
error_log("HTTP Referer: " . (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'N/A'));

try {
    require_once('session.php');
    error_log("Session.php loaded successfully");
} catch (Exception $e) {
    error_log("Error loading session.php: " . $e->getMessage());
    die("Error loading session: " . $e->getMessage());
} catch (Error $e) {
    error_log("Fatal error loading session.php: " . $e->getMessage());
    die("Fatal error loading session: " . $e->getMessage());
}

// Gunakan helper untuk mendapatkan URL yang benar
if (!function_exists('get_active_base_url')) {
    include(__DIR__ . '/../config/url_helper.php');
}
$urlweb = get_active_base_url();
error_log("URL Web from helper: " . $urlweb);

$result = mysqli_query($conn, "SELECT mindepo FROM tb_seo LIMIT 1");
if (!$result) {
    error_log("Failed to get mindepo: " . mysqli_error($conn));
    // Fallback jika query gagal
    $minDeposit = 10000;
} else {
    $seo = mysqli_fetch_assoc($result);
    $mindepo_value = isset($seo['mindepo']) ? $seo['mindepo'] : '10000';
    $minDeposit = (int)str_replace(',', '', $mindepo_value);
}

// Cek dulu apakah ada submit button - JANGAN validasi jika belum submit
error_log("Checking for submit button...");
error_log("POST keys: " . implode(', ', array_keys($_POST)));
error_log("Submit button exists: " . (isset($_POST['submit']) ? 'YES' : 'NO'));

if(!isset($_POST['submit'])){
    error_log("Submit button NOT detected in POST");
    error_log("All POST data: " . print_r($_POST, true));
    // Jika tidak ada submit, redirect kembali ke halaman deposit
    if (isset($urlweb) && !empty($urlweb)) {
        header('Location: ' . rtrim($urlweb, '/') . '/m/account/deposit/?notif=6&msg=Form tidak valid - Submit button tidak terdeteksi');
    } else {
        header('Location: ../m/account/deposit/?notif=6&msg=Form tidak valid - Submit button tidak terdeteksi');
    }
    exit();
}

// Ambil data dari POST dengan default value untuk menghindari undefined array key
$metode = isset($_POST['metode']) ? $_POST['metode'] : '';
$nominal_input = isset($_POST['nominal']) ? $_POST['nominal'] : (isset($_POST['amount']) ? $_POST['amount'] : '0');
// Pastikan nominal_input tidak null sebelum preg_replace
$nominal_input = $nominal_input ? $nominal_input : '0';
$nominal = preg_replace('/[^A-Za-z0-9\-]/','', (string)$nominal_input);
$pay_from = isset($_POST['pay_from']) ? $_POST['pay_from'] : '';
$catatan = isset($_POST['catatan']) ? $_POST['catatan'] : '';
$gameid = isset($_POST['gameid']) ? $_POST['gameid'] : '0';
$postID = isset($_POST['postID']) ? $_POST['postID'] : (isset($_POST['username']) ? $_POST['username'] : '');

// Validasi required fields - hanya jika submit sudah ada
if (empty($nominal) || $nominal == '0') {
    header('Location:../m/account/deposit/?notif=6&msg=Nominal deposit tidak boleh kosong');
    exit();
}

if (empty($pay_from)) {
    header('Location:../m/account/deposit/?notif=6&msg=Rekening pengirim tidak boleh kosong');
    exit();
}

if (empty($postID)) {
    header('Location:../m/account/deposit/?notif=6&msg=User ID tidak ditemukan');
    exit();
}

// Jika postID adalah username, ambil userID dari database
if (!is_numeric($postID)) {
    $username_escaped = mysqli_real_escape_string($conn, $postID);
    $user_query = mysqli_query($conn, "SELECT cuid FROM tb_user WHERE username = '$username_escaped'");
    if (!$user_query) {
        error_log("User query failed: " . mysqli_error($conn));
        header('Location:../m/account/deposit/?notif=6&msg=Error mencari user');
        exit();
    }
    if (mysqli_num_rows($user_query) > 0) {
        $user_data = mysqli_fetch_array($user_query);
        $postID = (int)$user_data['cuid'];
    } else {
        header('Location:../m/account/deposit/?notif=6&msg=User tidak ditemukan');
        exit();
    }
} else {
    $postID = (int)$postID;
}

$unik = date('Hs');
$kode_unik = substr(str_shuffle(1234567890), 0, 2);
$kd_transaksi = date('Ymds') . $kode_unik;
$created_date = date('Y-m-d H:i:s');

// Ambil persentase fee admin dari tb_seo
$fee_result = mysqli_query($conn, "SELECT feepulsa FROM tb_seo LIMIT 1");
if ($fee_result) {
    $fee_data = mysqli_fetch_assoc($fee_result);
    $feepulsa = isset($fee_data['feepulsa']) && is_numeric($fee_data['feepulsa']) ? (float)$fee_data['feepulsa'] : 0;
} else {
    $feepulsa = 0;
}
// Hindari pembagian dengan 0
$fee_persen = ($feepulsa > 0) ? ($feepulsa / 100) : 0;

// Kurangi totalBayar dengan fee admin
$nominal = (float)$nominal;
$totalBayar = $nominal;

// Submit sudah dicek di atas, langsung proses
error_log("Submit button detected");
error_log("Nominal: $nominal, MinDeposit: $minDeposit");

if($nominal < $minDeposit) {
    error_log("Nominal kurang dari minimum deposit");
    header('Location:../m/account/deposit/?notif=6&msg=Nominal deposit yang anda masukan kurang dari nominal batas minimum deposit');
    exit();
} else {
try {
        error_log("Starting transaction insert...");
        // Escape untuk keamanan SQL
        $kd_transaksi_escaped = mysqli_real_escape_string($conn, $kd_transaksi);
        $catatan_escaped = mysqli_real_escape_string($conn, $catatan);
        $metode_escaped = mysqli_real_escape_string($conn, $metode);
        $pay_from_escaped = mysqli_real_escape_string($conn, $pay_from);
        $gameid_escaped = mysqli_real_escape_string($conn, $gameid);
        
        error_log("Inserting transaction: kd_transaksi=$kd_transaksi_escaped, userID=$postID, total=$totalBayar");
        $insert_transaksi = 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_escaped','$created_date','Top Up','$totalBayar',0, '$catatan_escaped', '$gameid_escaped', '0','1','$metode_escaped','$pay_from_escaped','$postID',0)");
        
        if (!$insert_transaksi) {
            error_log("INSERT FAILED: " . mysqli_error($conn));
            // Jika insert gagal, redirect dengan error menggunakan URL lengkap dari helper
            $error_url = rtrim($urlweb, '/') . '/m/account/deposit/?notif=6&msg=' . urlencode('Gagal menyimpan transaksi: ' . mysqli_error($conn));
            header('Location: ' . $error_url);
            exit();
        }
        
        error_log("Transaction inserted successfully!");

    // Proses bonus jika ada (non-blocking, tidak menghentikan redirect jika error)
    if($gameid != '' && $gameid != '0'){
        try {
            $gameid_escaped = mysqli_real_escape_string($conn, $gameid);
            $sql_transaksi = mysqli_query($conn, "SELECT * FROM `tb_post` WHERE cuid = '$gameid_escaped'");
            if($sql_transaksi && mysqli_num_rows($sql_transaksi) > 0) {
                $st = mysqli_fetch_array($sql_transaksi);
                $jml_to = isset($st['min_to']) && is_numeric($st['min_to']) ? (float)$st['min_to'] : 0;
                $persen_value = isset($st['persen']) && is_numeric($st['persen']) ? (float)$st['persen'] : 0;
                if($persen_value > 0 && $jml_to > 0) {
                    $persen = $persen_value / 100;
                    $bonusnya = $nominal * $persen;
                    $bonuse = round($bonusnya);
                    if($bonuse > 200000){
                        $bonusDepo = 200000;
                    } else {
                        $bonusDepo = $bonuse;
                    }
                    $totalTO = ($nominal + $bonusDepo) * $jml_to;
                    $insertTO = mysqli_query($conn, "INSERT INTO `tb_turnover` (`userID`, `trxID`, `depo`, `bonus`, `jmlh_to`, `total_to`, `sisa_to`, `status`) VALUES ('$postID','$kd_transaksi_escaped','$nominal','$bonusDepo','$jml_to','$totalTO','$totalTO',0)");
                    // Jika insert turnover gagal, tetap lanjutkan (tidak critical)
                }
            }
        } catch (Exception $e) {
            // Jika ada error di bonus, tetap lanjutkan ke redirect (tidak critical)
        }
    }
    
    // Debug: Log informasi sebelum redirect
    error_log("=== DEPOSIT SUCCESS DEBUG ===");
    error_log("URL Web: " . (isset($urlweb) ? $urlweb : 'NOT SET'));
    error_log("Headers Sent: " . (headers_sent() ? 'YES' : 'NO'));
    error_log("OB Level: " . ob_get_level());
    error_log("Insert Success: " . ($insert_transaksi ? 'YES' : 'NO'));
    
        // Redirect ke halaman sukses menggunakan URL lengkap dari helper
        $redirect_url = rtrim($urlweb, '/') . '/m/?notif=8';
        error_log("Redirect URL: " . $redirect_url);
        
        // Jangan membersihkan buffer dari session.php, langsung redirect
        // Output buffer dari session.php akan di-handle oleh browser
        
        // Redirect dengan header - sederhana seperti function2/deposit.php
        header('Location: ' . $redirect_url);
        exit();
        
    } catch (Exception $e) {
        error_log("EXCEPTION in deposit: " . $e->getMessage());
        error_log("Stack trace: " . $e->getTraceAsString());
        // Jika ada error, tetap redirect ke halaman error
        $error_url = rtrim($urlweb, '/') . '/m/account/deposit/?notif=6&msg=' . urlencode('Terjadi kesalahan: ' . $e->getMessage());
        header('Location: ' . $error_url);
        exit();
    } catch (Error $e) {
        error_log("FATAL ERROR in deposit: " . $e->getMessage());
        error_log("Stack trace: " . $e->getTraceAsString());
        // Jika ada fatal error, tetap redirect ke halaman error
        $error_url = rtrim($urlweb, '/') . '/m/account/deposit/?notif=6&msg=' . urlencode('Terjadi kesalahan fatal');
        header('Location: ' . $error_url);
        exit();
    }
}
error_log("=== DEPOSIT.PHP END ===");

// Fallback: Jika script sampai di sini tanpa redirect, tampilkan error
if (!headers_sent()) {
    header('Location: ../m/account/deposit/?notif=6&msg=Terjadi kesalahan tidak diketahui');
    exit();
} else {
    // Jika header sudah terkirim, output HTML error
    ?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Error</title>
</head>
<body>
    <h2>Terjadi Kesalahan</h2>
    <p>Silakan kembali ke halaman deposit.</p>
    <a href="../m/account/deposit/">Kembali ke Deposit</a>
</body>
</html>
    <?php
}
?>