<?php
/**
 * fampay_order_resolver.php
 * The single place that actually marks a FamPay order SUCCESS: atomic
 * claim (race-safe), webhook send, report insert, usage counter,
 * notification. Used by BOTH:
 *   - payment9/payment_status.php (fired while the customer's browser is
 *     actively polling - fastest path, usually a couple of seconds)
 *   - crons/fampay_order_watcher.php (an independent background check
 *     that keeps working even if the customer closes their browser tab
 *     right after paying, before the browser poll ever sees success)
 *
 * Having ONE function for this (instead of duplicating the same
 * atomic-claim + webhook logic in two files) means both paths stay
 * correct and in sync automatically.
 */

function resolve_fampay_order_success($conn, $order_id, $UTR, $db_amount, $user_token, $cxrremark1, $megabyteuserid, $callback_url, $gmail) {
    // Atomically "claim" this order before doing anything else - if the
    // browser poll and the background watcher both detect the match at
    // nearly the same moment, only ONE of them should actually send the
    // webhook/notification. The other sees 0 affected rows and does
    // nothing further - this is what prevents duplicate webhook sends.
    $sql = "UPDATE orders SET status='SUCCESS' WHERE order_id=? AND status != 'SUCCESS'";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $order_id);
    $stmt->execute();
    $wonTheRace = $stmt->affected_rows > 0;
    $stmt->close();

    if (!$wonTheRace) {
        return false; // someone else already resolved this order - nothing to do
    }

    include_once __DIR__ . '/webhook_lib.php';
    send_webhook($conn, $megabyteuserid, $callback_url, 'payment.success', [
        'order_id'   => htmlspecialchars_decode($order_id),
        'txn_id'     => $UTR,
        'status'     => 'Success',
        'amount'     => $db_amount,
        'pay_amount' => $db_amount,
        'utr'        => $UTR,
        'remark1'    => $cxrremark1,
    ], $order_id);

    $sql = "UPDATE orders SET utr=? WHERE order_id=?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $UTR, $order_id);
    $stmt->execute();
    $stmt->close();

    $sqlInsertReport = "INSERT INTO reports (transactionId, status, order_id, vpa, user_name, paymentApp, amount, user_token, transactionNote, merchantTransactionId, user_id) VALUES (?, 'TXN_SUCCESS', ?, ?, 'NULL', 'FamPay', ?, ?, ?, ?, ?)";
    $stmtInsertReport = $conn->prepare($sqlInsertReport);
    $stmtInsertReport->bind_param("sssssssi", $UTR, $order_id, $gmail, $db_amount, $user_token, $cxrremark1, $order_id, $megabyteuserid);
    $stmtInsertReport->execute();
    $stmtInsertReport->close();

    include_once __DIR__ . '/subscription_lib.php';
    incrementTransactionUsage($conn, $megabyteuserid);

    include_once __DIR__ . '/notify_lib.php';
    send_payment_success_notification($conn, $megabyteuserid, $order_id, $db_amount, $UTR, 'FamPay');

    // Commission only applies to a merchant collecting from their own
    // customer. Orders created for the platform's own subscription
    // purchases ('test1' remark, see auth/lib/pay.php) or wallet top-ups
    // ('WALLET_TOPUP' remark, see auth/lib/wallet_pay.php) are the
    // merchant PAYING the platform, not receiving a payment - charging
    // commission on those would be charging commission on the commission.
    if ($cxrremark1 !== 'test1' && strpos((string)$cxrremark1, 'WALLET_TOPUP') !== 0) {
        include_once __DIR__ . '/wallet_lib.php';
        deduct_commission_on_success($conn, $megabyteuserid, $order_id, $db_amount);
    }

    return true;
}
