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

// 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. Jika status Sukses, teruskan callback ke URL Client
        if ($gspay_status == 1) {
            $stmt_agent = $pdo->prepare("SELECT callback_url FROM agent_api WHERE username = ?");
            $stmt_agent->execute([$trx['agent']]);
            $agent = $stmt_agent->fetch();

            if ($agent && !empty($agent['callback_url'])) {
                // Susun payload sesuai format asli yang diharapkan client
                $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); // Tambah timeout sedikit lebih lama
                
                $client_response = curl_exec($ch);
                $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); // Ambil respon code (misal: 200, 404, 500)
                $curl_error = curl_error($ch);
                curl_close($ch);

                // 4. SIMPAN LOG KE DATABASE (Tabel callback_log)
                $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, // Simpan error curl jika response kosong
                    $http_code,
                    $log_status
                ]);

                // Tetap simpan di file txt sebagai cadangan
                file_put_contents('callback_log.txt', "[" . date('Y-m-d H:i:s') . "] Sent to: " . $trx['agent'] . " | HTTP: " . $http_code . "\n", FILE_APPEND);

                // --- TAMBAHAN NOTIFIKASI TELEGRAM (Dijalankan di akhir proses sukses) ---
                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) {
                }
            }
        }
    }
}

// Respon balik ke GSPay agar mereka berhenti mengirim callback yang sama
echo json_encode(["status" => "success"]);