<?php
/**
 * SILENTAPI SEAMLESS CALLBACK - SAME FOLDER AS LAUNCH
 */

error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

$log_dir = __DIR__ . '/callback_logs';
if (!file_exists($log_dir)) { mkdir($log_dir, 0777, true); }

function writeLog($type, $msg) {
    global $log_dir;
    $logFile = $log_dir . "/callback_error_" . date('Y-m-d') . ".log";
    file_put_contents($logFile, "[" . date('H:i:s') . "] [$type] $msg" . PHP_EOL, FILE_APPEND);
}

writeLog("DEBUG", "--- SCRIPT START (LAUNCH FOLDER MODE) ---");

// 💡 SAME PATH AS LAUNCH FILE
$conn_path = "../../conn.php"; 
if (file_exists($conn_path)) {
    include_once $conn_path;
    writeLog("DEBUG", "Include success: conn.php");
} else {
    writeLog("CRITICAL", "❌ File NOT FOUND: $conn_path");
    exit(json_encode(['code' => 1, 'msg' => 'Conn file missing']));
}

$raw_input = file_get_contents('php://input');
$headers = getallheaders();
$signature = $headers['X-Signature'] ?? $headers['x-signature'] ?? '';

writeLog("INCOMING", "Body: $raw_input | Sig: $signature");

// Secret Key Check - Ise apne SilentAPI panel ke Secret Key se match karein
define('SECRET_KEY', '97f0b26ed54b7bb805ce7c5817ab50b7e4385bd4136359d2ebd733527f7505b8');
$calculated_sig = hash_hmac('sha256', $raw_input, SECRET_KEY);

if ($signature !== $calculated_sig) {
    writeLog("ERROR", "❌ Signature Mismatch. Sent: $signature | Calc: $calculated_sig");
    exit(json_encode(['code' => 1, 'msg' => 'Invalid Signature']));
}

writeLog("DEBUG", "Signature Verified ✅");

$data = json_decode($raw_input, true);
$uid = $data['member_account'] ?? 'UNKNOWN';

try {
    writeLog("DEBUG", "Starting Transaction for User: $uid");
    
    if (!isset($conn)) {
        throw new Exception("Database Connection object (\$conn) is missing!");
    }

    $bet = floatval($data['bet_amount'] ?? 0);
    $win = floatval($data['win_amount'] ?? 0);

    // Fetch Player Balance
    $bal_q = $conn->prepare("SELECT motta FROM shonu_kaichila WHERE balakedara = ?");
    $bal_q->bind_param("s", $uid);
    $bal_q->execute();
    $res = $bal_q->get_result()->fetch_assoc();

    if (!$res) {
        writeLog("ERROR", "❌ User $uid not found in DB");
        exit(json_encode(['code' => 1, 'msg' => 'User not found']));
    }

    $old_bal = floatval($res['motta']);
    $new_bal = $old_bal - $bet + $win;

    // Update Balance
    $update = $conn->prepare("UPDATE shonu_kaichila SET motta = ? WHERE balakedara = ?");
    $update->bind_param("ds", $new_bal, $uid);
    $update->execute();

    writeLog("SUCCESS", "✅ Updated Balance: $new_bal");
    echo json_encode(['code' => 0, 'msg' => 'Success', 'balance' => (string)$new_bal]);

} catch (Exception $e) {
    writeLog("CRITICAL", "❌ Engine Crash: " . $e->getMessage());
    echo json_encode(['code' => 1, 'msg' => 'Exception Occurred']);
}

writeLog("DEBUG", "--- SCRIPT END ---");
