<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once('session.php');

if (!function_exists('get_active_base_url')) {
    include(__DIR__ . '/../config/url_helper.php');
}
$urlweb = get_active_base_url();

/* ===============================
   AMBIL MINIMUM DEPOSIT
=================================*/
$result = mysqli_query($conn, "SELECT mindepo FROM tb_seo LIMIT 1");
$seo = mysqli_fetch_assoc($result);
$minDeposit = (int)str_replace(',', '', $seo['mindepo']);

/* ===============================
   VALIDASI SUBMIT
=================================*/
if(!isset($_POST['submit'])){
    header('Location: '.$urlweb.'/m/account/deposit/?notif=6');
    exit();
}

/* ===============================
   AMBIL DATA POST
=================================*/
$metode     = $_POST['metode'] ?? '';
$nominalRaw = $_POST['nominal'] ?? ($_POST['amount'] ?? '0');
$pay_from   = $_POST['pay_from'] ?? '';
$catatan    = $_POST['catatan'] ?? '';
$gameid     = (int)($_POST['gameid'] ?? 0);
$postID     = (int)($_POST['postID'] ?? 0);

$nominal = preg_replace('/[^0-9]/','', $nominalRaw);
$nominal = (float)$nominal;

if ($postID !== (int) $userID) {
    header('Location: '.$urlweb.'/m/account/deposit/?notif=6&msg=Sesi tidak valid');
    exit();
}

if($nominal < $minDeposit){
    header('Location: '.$urlweb.'/m/account/deposit/?notif=6&msg=Nominal kurang dari minimum');
    exit();
}

if(empty($pay_from) || $postID < 1){
    header('Location: '.$urlweb.'/m/account/deposit/?notif=6');
    exit();
}

/* ===============================
   GENERATE DATA TRANSAKSI
=================================*/
$kd_transaksi = date('YmdHis') . rand(10,99);
$created_date = date('Y-m-d H:i:s');

$metode_escaped   = mysqli_real_escape_string($conn, $metode);
$pay_from_escaped = mysqli_real_escape_string($conn, $pay_from);
$catatan_escaped  = mysqli_real_escape_string($conn, $catatan);
$postID           = (int)$postID;

/* ===============================
   INSERT TRANSAKSI
=================================*/
$insert = 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','$nominal',0,'$catatan_escaped','$gameid','0','1','$metode_escaped','$pay_from_escaped','$postID',0)
");

if(!$insert){
    header('Location: '.$urlweb.'/m/account/deposit/?notif=6');
    exit();
}

if ($gameid > 0) {
    $sql_bonus = mysqli_query($conn, "SELECT * FROM `tb_post` WHERE cuid = '$gameid'") or die(mysqli_error($conn));
    $st = mysqli_fetch_array($sql_bonus);

    if ($st) {
        $jml_to = $st['min_to'];
        $persen = $st['persen'] / 100;
        $bonusnya = $nominal * $persen;
        $bonusDepo = min(200000, round($bonusnya));
        $totalTO = ($nominal + $bonusDepo) * $jml_to;
        $expiredAt = date('Y-m-d H:i:s', strtotime('+1 day'));

        mysqli_query($conn, "INSERT INTO `tb_turnover`
            (`userID`, `trxID`, `depo`, `bonus`, `jmlh_to`, `total_to`, `sisa_to`, `status`, `created_at`, `expired_at`)
            VALUES
            ('$postID', '$kd_transaksi', '$nominal', '$bonusDepo', '$jml_to', '$totalTO', '$totalTO', 0, NOW(), '$expiredAt')")
            or die(mysqli_error($conn));

        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','Promosi','$bonusDepo',0,'$catatan_escaped','$gameid','0','7','$metode_escaped','$pay_from_escaped','$postID',0)")
            or die(mysqli_error($conn));
    }
}

/* ===============================
   TELEGRAM NOTIF DEPOSIT MANUAL
=================================*/
$bot_token = "8613767634:AAH0L9ZS3XvupoWH34ym61dJjSFteqCOqRI";
$chat_id   = "-1003937011850";
$topic_id = "4"; // kosongkan jika tidak pakai topic

$getUser = mysqli_query($conn,"SELECT username FROM tb_user WHERE cuid='$postID'");
$user = mysqli_fetch_array($getUser);
$usernameMember = $user['username'];

$pesan  = "📝 REQUEST DEPOSIT MANUAL\n\n";
$pesan .= "👤 User : $usernameMember\n";
$pesan .= "💰 Nominal : Rp ".number_format($nominal,0,',','.')."\n";
$pesan .= "🏦 Dari : $pay_from\n";
$pesan .= "🆔 KD : $kd_transaksi\n";
$pesan .= "⏰ $created_date\n";
$pesan .= "🔔 Status : PENDING";

$url = "https://api.telegram.org/bot".$bot_token."/sendMessage";

$data = [
    'chat_id' => $chat_id,
    'text' => $pesan
];

$options = [
    'http' => [
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data),
    ]
];

$context = stream_context_create($options);
file_get_contents($url, false, $context);

/* ===============================
   REDIRECT SUCCESS
=================================*/
header('Location: '.$urlweb.'/m/?notif=8');
exit();
?>