<?php
header('Content-Type: application/json');
date_default_timezone_set("Asia/Jakarta");

include 'config/koneksi.php';
include 'config/class_softgaming.php';

/* ===============================
   KONFIG TELEGRAM GROUP
=================================*/
function sendTelegram($message) {

    $token   = "8613767634:AAH0L9ZS3XvupoWH34ym61dJjSFteqCOqRI";
    $chat_id = "-1003937011850"; // Chat ID Group
    $topic_id = "3"; // Message Thread ID Topic Deposit

    $url = "https://api.telegram.org/bot{$token}/sendMessage";

    $data = [
        'chat_id' => $chat_id,
        'message_thread_id' => $topic_id,
        'text' => $message,
        'parse_mode' => 'Markdown'
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    $result = curl_exec($ch);

    if (curl_errno($ch)) {
        error_log('Telegram Error: ' . curl_error($ch));
    }

    curl_close($ch);

    return $result;
}

/* ===============================
   LOGGING
=================================*/
$logFile = __DIR__ . '/logs/qris_callback_' . date('Y-m-d') . '.log';
$logDir = dirname($logFile);

if (!is_dir($logDir)) {
    mkdir($logDir, 0755, true);
}

function writeLog($message) {
    global $logFile;
    $timestamp = date('Y-m-d H:i:s');
    file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND);
}

writeLog('=== CALLBACK QRIS OTOMATIS RECEIVED ===');

/* ===============================
   AMBIL DATA CALLBACK
=================================*/
$jsonInput = file_get_contents('php://input');
writeLog('Raw Input: ' . $jsonInput);

$data = json_decode($jsonInput, true);

if (!$data) {
    writeLog('ERROR: Invalid JSON input');
    die(json_encode(['status' => 'error', 'message' => 'Invalid JSON data']));
}

if (!isset($data['trx_id']) || !isset($data['amount']) || !isset($data['status'])) {
    writeLog('ERROR: Missing required fields');
    die(json_encode(['status' => 'error', 'message' => 'Missing required fields']));
}

$trx_id = mysqli_real_escape_string($conn, $data['trx_id']);
$amount = (int)$data['amount'];
$status = mysqli_real_escape_string($conn, $data['status']);

writeLog("Processing trx_id=$trx_id | amount=$amount | status=$status");

/* ===============================
   CEK TRANSAKSI
=================================*/
$sqlTrx = mysqli_query($conn, "SELECT userID, status, kd_transaksi, gameid 
FROM tb_transaksi 
WHERE note LIKE '%$trx_id%' 
AND jenis = 1 
LIMIT 1");

$trxData = mysqli_fetch_assoc($sqlTrx);

if (!$trxData) {
    writeLog("ERROR: Transaction not found");
    die(json_encode(['status' => 'error', 'message' => 'Transaction not found']));
}

if ($trxData['status'] == 1) {
    writeLog("Already processed");
    die(json_encode(['status' => 'success', 'message' => 'Already processed']));
}

if ($status !== 'success') {
    writeLog("Payment not success");
    die(json_encode(['status' => 'error', 'message' => 'Payment not success']));
}

$userID       = $trxData['userID'];
$kd_transaksi = $trxData['kd_transaksi'];
$gameid       = $trxData['gameid'];

/* ===============================
   AMBIL USERNAME
=================================*/
$sqlUser = mysqli_query($conn, "SELECT username FROM tb_user WHERE cuid = '$userID' LIMIT 1");
$u = mysqli_fetch_assoc($sqlUser);

if (!$u) {
    writeLog("User not found");
    die(json_encode(['status' => 'error', 'message' => 'User not found']));
}

$username_web = $u['username'];

/* ===============================
   DEPOSIT KE NEXUS
=================================*/
$WL = new fiver();
$agent_sign = 'DEPO_' . $kd_transaksi . '_' . time();
$res = $WL->deposit($username_web, $amount, $agent_sign);

writeLog("Nexus Response: " . print_r($res, true));

/* ===============================
   JIKA BERHASIL
=================================*/
if (isset($res['status']) && $res['status'] == 1) {

    mysqli_query($conn, "UPDATE tb_transaksi 
    SET status = 1 
    WHERE kd_transaksi = '$kd_transaksi' 
    AND userID = '$userID' 
    AND jenis = 1");

    mysqli_query($conn, "UPDATE tb_balance 
    SET active = active + $amount 
    WHERE userID = '$userID'");

    /* BONUS */
    if ($gameid > 0) {

        $getTO = mysqli_query($conn, "SELECT * FROM tb_turnover WHERE trxID = '$kd_transaksi'");
        if (mysqli_num_rows($getTO) > 0) {

            $go = mysqli_fetch_array($getTO);
            $bonus = $go['bonus'];

            mysqli_query($conn, "UPDATE tb_balance 
            SET active = active + '$bonus' 
            WHERE userID = '$userID'");

            $agent_sign_bonus = 'BONUS_' . $kd_transaksi . '_' . time();
            $WL->deposit($username_web, $bonus, $agent_sign_bonus);

            mysqli_query($conn, "UPDATE tb_turnover 
            SET status = 1 
            WHERE trxID = '$kd_transaksi'");
        }
    }

    /* TELEGRAM SUCCESS */
    $telegramMessage =
    "━━━━━━━━━━━━━━━\n".
    "💰 *DEPOSIT SUCCESS*\n".
    "━━━━━━━━━━━━━━━\n".
    "👤 User   : `$username_web`\n".
    "💵 Amount : *Rp " . number_format($amount,0,',','.') . "*\n".
    "🧾 TrxID  : `$kd_transaksi`\n".
    "🕒 " . date('d-m-Y H:i:s');

    $tgResponse = sendTelegram($telegramMessage);
    writeLog("Telegram Response: " . $tgResponse);

    writeLog("=== SUCCESS ===");

    echo json_encode([
        'status' => 'success',
        'message' => 'Payment processed'
    ]);

}
/* ===============================
   JIKA GAGAL
=================================*/
else {

    $errorMsg = isset($res['msg']) ? $res['msg'] : 'Unknown error';

    $telegramMessage =
    "━━━━━━━━━━━━━━━\n".
    "❌ *DEPOSIT FAILED*\n".
    "━━━━━━━━━━━━━━━\n".
    "👤 User   : `$username_web`\n".
    "💵 Amount : Rp " . number_format($amount,0,',','.') . "\n".
    "🧾 TrxID  : `$kd_transaksi`\n".
    "⚠ Error  : $errorMsg\n".
    "🕒 " . date('d-m-Y H:i:s');

    $tgResponse = sendTelegram($telegramMessage);
    writeLog("Telegram Response: " . $tgResponse);

    writeLog("Deposit failed: $errorMsg");

    echo json_encode([
        'status' => 'error',
        'message' => $errorMsg
    ]);
}
?>