<?php
header('Content-Type: application/json');
require_once 'secret/config.php';
require_once 'secret/bot_tele.php'; // Memuat fungsi notifikasi Telegram

// Ambil data mentah dari GSPay
$rawBody = file_get_contents("php://input");
$data = json_decode($rawBody, true);

// Log awal jika JSON tidak valid
if (!$data) {
    file_put_contents('callback_log.txt', "[" . date('Y-m-d H:i:s') . "] Invalid JSON Received\n", FILE_APPEND);
    exit;
}

$raw_tx_id = $data['transaction_id'] ?? '';
$gspay_status = $data['status'] ?? 0; // 1 = Success, 2 = Failed

if ($raw_tx_id) {
    // 1. Cari data transaksi di database lokal
    $stmt = $pdo->prepare("SELECT agent, check_id, player, amount, type FROM trx_agent WHERE transaction_id = ?");
    $stmt->execute([$raw_tx_id]);
    $trx = $stmt->fetch();

    if ($trx) {
        // Konversi status GSPay ke text
        $status_text = ($gspay_status == 1) ? 'success' : (($gspay_status == 2) ? 'failed' : 'pending');

        // 2. Update status transaksi di tabel utama
        $upd = $pdo->prepare("UPDATE trx_agent SET status = ?, respon = ? WHERE transaction_id = ?");
        $upd->execute([$status_text, $rawBody, $raw_tx_id]);

        // 3. Logika Khusus Jika Status Sukses
        if ($gspay_status == 1) {
            // Ambil detail agen untuk cek Level dan Fee
            $stmt_agent = $pdo->prepare("SELECT callback_url, level, fee, balance FROM agent_api WHERE username = ?");
            $stmt_agent->execute([$trx['agent']]);
            $agent = $stmt_agent->fetch();

            if ($agent) {
                // --- LOGIKA INSTANT SETTLEMENT UNTUK LEVEL SPECIAL ---
                if ($agent['level'] === 'Special') {
                    try {
                        $pdo->beginTransaction(); // Mulai transaksi database

                        // Hitung nilai bersih (Amount - Fee Agen)
                        $current_fee = $agent['fee']; 
                        $nett_amount = $trx['amount'] * (1 - $current_fee); 

                        // Update Saldo Utama Agen secara instan
                        $upd_bal = $pdo->prepare("UPDATE agent_api SET balance = balance + ? WHERE username = ?");
                        $upd_bal->execute([$nett_amount, $trx['agent']]);

                        // Tandai transaksi sebagai SUDAH SETTLE dan SUDAH TRANSFER
                        $upd_trx = $pdo->prepare("UPDATE trx_agent SET settle = '1', transfer = '1', updated_at = NOW() WHERE transaction_id = ?");
                        $upd_trx->execute([$raw_tx_id]);

                        $pdo->commit(); // Simpan perubahan
                        
                        file_put_contents('callback_log.txt', "[" . date('Y-m-d H:i:s') . "] AUTO-SETTLE SUCCESS: Agent " . $trx['agent'] . " | Nett: " . $nett_amount . "\n", FILE_APPEND);
                    } catch (Exception $e_settle) {
                        $pdo->rollBack(); // Batalkan jika error
                        file_put_contents('callback_log.txt', "[" . date('Y-m-d H:i:s') . "] AUTO-SETTLE ERROR: " . $e_settle->getMessage() . "\n", FILE_APPEND);
                    }
                }

                // 4. Teruskan Callback ke URL Client
                if (!empty($agent['callback_url'])) {
                    $callback_data = [
                        "success" => true,
                        "data" => [
                            "type"           => $trx['type'],
                            "currency"       => "IDR",
                            "username"       => $trx['player'],
                            "transaction_id" => $trx['check_id'],
                            "amount"         => (string)number_format($trx['amount'], 0, '', ''),
                            "remark"         => $data['remark'] ?? "Payment successful",
                            "status"         => "success"
                        ]
                    ];

                    $payload_json = json_encode($callback_data);

                    // Eksekusi pengiriman ke Client URL
                    $ch = curl_init($agent['callback_url']);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload_json);
                    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
                    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
                    
                    $client_response = curl_exec($ch);
                    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                    $curl_error = curl_error($ch);
                    curl_close($ch);

                    // Simpan Log Callback ke Database
                    $stmt_log = $pdo->prepare("INSERT INTO callback_log (agent_username, transaction_id, check_id, payload_sent, client_response, http_code, status) VALUES (?, ?, ?, ?, ?, ?, ?)");
                    $log_status = ($http_code == 200) ? 'success' : 'failed';
                    $stmt_log->execute([
                        $trx['agent'], 
                        $raw_tx_id, 
                        $trx['check_id'], 
                        $payload_json, 
                        $client_response ?: $curl_error, 
                        $http_code,
                        $log_status
                    ]);
                }
            }

            // 5. Notifikasi Telegram
            try {
                $timestamp = date('d M Y | H:i:s');
                $amount_formatted = "Rp " . number_format($trx['amount'], 0, ',', '.');
                $cid = $trx['check_id'];
                $masked_check_id = (strlen($cid) > 8) ? substr($cid, 0, 8) . "****" : $cid . "****";

                $msg = "<b>💰 NOTIFIKASI DEPOSIT BERHASIL</b>\n";
                $msg .= "———————————————————\n\n";
                $msg .= "<b>STATUS INFO</b>\n";
                $msg .= "└ CHECK ID : <code>$masked_check_id</code>\n";
                $msg .= "└ Status   : <pre>CONFIRMED</pre>\n";
                $msg .= "└ Amount   : <b>$amount_formatted</b>\n";
                $msg .= "└ Method   : " . strtoupper($trx['type']) . "\n\n";
                $msg .= "———————————————————\n";
                $msg .= "📅 <b>Waktu :</b> <code>$timestamp</code>\n";
                $msg .= "🤖 <i>Deposit-System Automated</i>";

                sendTelegramNotif('deposit', $msg);
            } catch (Exception $e_tele) {
                // Ignore telegram error
            }
        }
    }
}

// Respon balik ke GSPay
echo json_encode(["status" => "success"]);