<?php
include_once('./db.php');

$data = file_get_contents("php://input");
$ret  = json_decode($data, true);

$logFile = __DIR__ . '/callback_logs.txt';

function saveLog($msg) {
    global $logFile;
    file_put_contents(
        $logFile,
        date('Y-m-d H:i:s') . " - " . $msg . PHP_EOL,
        FILE_APPEND | LOCK_EX
    );
}

saveLog("RAW CALLBACK: " . $data);

if (!isset($ret['status'], $ret['merOrderNo'])) {
    echo "INVALID";
    exit;
}

if ((int)$ret['status'] !== 5) {
    echo "IGNORED";
    exit;
}

$order_id = $ret['merOrderNo'];


$stmt = $conn->prepare("
    SELECT user_id, final_amount, status 
    FROM deposits 
    WHERE order_id = ?
    LIMIT 1
");
$stmt->bind_param("s", $order_id);
$stmt->execute();
$deposit = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$deposit) {
    echo "DEPOSIT_NOT_FOUND";
    exit;
}

if ($deposit['status'] === 'approved') {
    echo "SUCCESS";
    exit;
}

$conn->begin_transaction();

try {

    $user_id = (int)$deposit['user_id'];
    $amount  = (float)$deposit['final_amount'];

    $stmt = $conn->prepare("
        UPDATE deposits 
        SET status = 'approved',
            updated_at = NOW() 
        WHERE order_id = ?
    ");
    $stmt->bind_param("s", $order_id);
    $stmt->execute();
    $stmt->close();

    $stmt = $conn->prepare("
        UPDATE users 
        SET balance = balance + ? 
        WHERE id = ?
    ");
    $stmt->bind_param("di", $amount, $user_id);
    $stmt->execute();
    $stmt->close();

    $conn->commit();

    saveLog("DEPOSIT APPROVED | ORDER_ID=$order_id | USER_ID=$user_id | AMOUNT=$amount");
    echo "SUCCESS";

} catch (Exception $e) {

    $conn->rollback();
    echo "FAILED";
}
