<?php
header('Content-Type: application/json');

$base = realpath(__DIR__ . '/../../../');
if (file_exists($base . '/app/session.php')) include $base . '/app/session.php';
if (file_exists($base . '/config/db.php')) include $base . '/config/db.php';
if (file_exists($base . '/config/deposit_lib.php')) include $base . '/config/deposit_lib.php';

if (!isset($link)) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'db']);
    exit;
}

$user_id = isset($_SESSION['user_id']) ? intval($_SESSION['user_id']) : 0;
if ($user_id <= 0) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'not_authenticated']);
    exit;
}

$tx_hash = isset($_GET['tx_hash']) ? trim($_GET['tx_hash']) : '';
if ($tx_hash === '' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $body = json_decode(file_get_contents('php://input'), true);
    $tx_hash = isset($body['tx_hash']) ? trim($body['tx_hash']) : '';
}
if ($tx_hash === '') {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'tx_hash required']);
    exit;
}

deposit_ensure_table($link);
$tx_esc = mysqli_real_escape_string($link, $tx_hash);
$res = mysqli_query($link, "SELECT * FROM deposits WHERE tx_hash='$tx_esc' AND user_id='$user_id' LIMIT 1");
if (!$res || mysqli_num_rows($res) === 0) {
    echo json_encode(['ok' => false, 'status' => 'not_found']);
    exit;
}

$deposit = mysqli_fetch_assoc($res);
if ($deposit['status'] === 'confirmed') {
    echo json_encode(['ok' => true, 'status' => 'confirmed']);
    exit;
}
if ($deposit['status'] === 'failed') {
    echo json_encode(['ok' => false, 'status' => 'failed']);
    exit;
}

$rpc = [];
if (file_exists($base . '/config/rpc.php')) $rpc = include $base . '/config/rpc.php';

$result = deposit_verify_and_credit($link, $deposit, $rpc);
echo json_encode($result);
