<?php
// Wallet top-up callback - mirrors auth/lib/callback.php (subscription
// purchase confirmation) exactly, but credits the wallet instead of
// activating a plan.

session_start();
require_once __DIR__ . '/../config.php'; // $conn
require_once 'config.php';               // $token
include_once __DIR__ . '/../../includes/wallet_lib.php';

$orderid = $_COOKIE['wallet_topup_order_id_cookie'] ?? '';

$walletPageUrl = "https://" . $_SERVER["SERVER_NAME"] . "/auth/wallet";

if ($orderid === '') {
    header("Location: $walletPageUrl?topup_failed=1&reason=missing_order");
    exit;
}

// Check the real payment status via NeoPay's own status API - same as the
// subscription flow. This is the ONLY thing that decides whether the
// wallet actually gets credited; nothing here trusts the redirect alone.
$url = "https://" . $_SERVER["SERVER_NAME"] . "/api/check-order-status";
$postData = array(
    "user_token" => $token,
    "order_id" => $orderid,
);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$response = curl_exec($ch);

if (curl_errno($ch)) {
    curl_close($ch);
    header("Location: $walletPageUrl?topup_failed=1&reason=network");
    exit;
}
curl_close($ch);

$responseData = json_decode($response, true);

if (!$responseData || ($responseData["status"] ?? '') !== "COMPLETED") {
    header("Location: $walletPageUrl?topup_failed=1&reason=lookup");
    exit;
}

$txnStatus = $responseData["result"]["txnStatus"] ?? '';
$paidAmount = (float)($responseData["result"]["amount"] ?? 0);

if ($txnStatus === 'COMPLETED') {

    // remark2 holds the merchant's own user id (set when the order was
    // created in auth/lib/wallet_pay.php).
    $stmt = $conn->prepare("SELECT amount, remark1, remark2 FROM orders WHERE order_id = ? LIMIT 1");
    $stmt->bind_param("s", $orderid);
    $stmt->execute();
    $orderRow = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    $merchantId = (int)($orderRow['remark2'] ?? 0);
    $amount = $paidAmount > 0 ? $paidAmount : (float)($orderRow['amount'] ?? 0);

    if (!$merchantId) {
        header("Location: $walletPageUrl?topup_failed=1&reason=unresolved_owner");
        exit;
    }

    // Idempotency: don't double-credit if this exact order_id already has
    // a TopUp entry (e.g. user refreshed the callback page).
    $chk = $conn->prepare("SELECT id FROM wallet_transactions WHERE order_id = ? AND type = 'TopUp' LIMIT 1");
    $chk->bind_param("s", $orderid);
    $chk->execute();
    $already = $chk->get_result()->fetch_assoc();
    $chk->close();

    if (!$already) {
        credit_wallet($conn, $merchantId, $orderid, $amount, 'Wallet top-up via UPI');
    }

    setcookie('wallet_topup_order_id_cookie', '', time() - 3600, '/');
    header("Location: $walletPageUrl?topup_success=1");
    exit;

} elseif ($txnStatus === 'FAILURE') {
    header("Location: $walletPageUrl?topup_failed=1&reason=payment_failed");
    exit;
} else {
    header("Location: $walletPageUrl?topup_pending=1");
    exit;
}
