<?php

session_set_cookie_params([
    'lifetime' => 0,                           // browser close तक
    'path'     => '/',                          // पूरे डोमेन में वैध
    'domain'   => 'in-co.xyz', // आपका exact domain
    'secure'   => true,                          // HTTPS पर true
    'httponly' => true,
    'samesite' => 'Lax'
]);
session_start();

   
require_once('lib/Config_RechPay.php');
require_once('lib/RechPayChecksum.php');

$secret = $secret;

/**
 * SweetAlert popup + redirect
 */
function sweetAlertPage($title, $text, $icon, $redirectUrl){
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Payment Status</title>
        <script src="https://unpkg.com/sweetalert2@11/dist/sweetalert2.all.min.js"></script>
    </head>
    <body>
        <script>
        Swal.fire({
            title: '<?= addslashes($title) ?>',
            text: '<?= addslashes($text) ?>',
            icon: '<?= $icon ?>',
            confirmButtonText: 'OK'
        }).then(function(){
            window.location.replace('<?= $redirectUrl ?>');
        });
        </script>
    </body>
    </html>
    <?php
    exit;
}

// ==================================================================
//   MAIN LOGIC
// ==================================================================
if (!empty($_POST['status']) && $_POST['status'] === 'SUCCESS') {

    $hash    = $_POST['hash'] ?? '';
    $decoded = hash_decrypt($hash, $secret);
    $pdata   = json_decode($decoded, true);

    if ($pdata && $pdata['txnStatus'] === "TXN_SUCCESS" && !empty($pdata['payee_vpa'])) {

        $txnId       = mysqli_real_escape_string($conn, $pdata['txnId']);
        $txnAmount   = floatval($pdata['txnAmount']);
        $sender_note = mysqli_real_escape_string($conn, $pdata['sender_note']);

        // ---- Prevent duplicate credit ----
        $check = mysqli_query($conn,
            "SELECT id FROM transactions WHERE txn_id='$txnId' LIMIT 1");
        if (mysqli_num_rows($check) > 0) {
            sweetAlertPage(
                'Already Processed',
                'This transaction has already been credited.',
                'info',
                'https://in-co.xyz/crs/wallet.php'
            );
        }

        // ---- Wallet credit calculation ----
        $percentDecimal = (10 - 0) / 10;              // 1.0
        $total_txn_amt  = $percentDecimal * $txnAmount;

        $map = [
            100 => 200, 
            200 => 500, 
            300 => 900, 
            400 => 1200, 
            500 => 1500,
        ];
        $txn_amounts = $map[$total_txn_amt] ?? $total_txn_amt;

        $userid = $sender_note;

        // ---- Atomic transaction ----
        mysqli_begin_transaction($conn);
        try {
            mysqli_query($conn,
                "INSERT INTO transactions (txn_id, amount, userid)
                 VALUES ('$txnId', '$txn_amounts', '$sender_note')");

            mysqli_query($conn,
                "UPDATE usertable
                 SET walletamount = walletamount + '$txn_amounts'
                 WHERE userid = '$sender_note'");

            mysqli_commit($conn);

            // ✅ SUCCESS POPUP + absolute redirect
            sweetAlertPage(
                'Payment Successful!',
                "₹{$txn_amounts} credited to your wallet.",
                'success',
                'https://in-co.xyz/crs/addwallet.php?txn_status=SUCCESS'
            );

        } catch (Exception $e) {
            mysqli_rollback($conn);
            sweetAlertPage(
                'Error',
                'Transaction could not be recorded.',
                'error',
                'https://in-co.xyz/crs/addwallet.php?txn_status=TXN_FAILED'
            );
        }

    } else {
        sweetAlertPage(
            'Transaction Failed',
            'Invalid transaction.',
            'error',
            'https://in-co.xyz/crs/addwallet.php?txn_status=TXN_FAILED'
        );
    }

} else {
    sweetAlertPage(
        'Payment Failed',
        'Your payment was not successful.',
        'error',
        'https://in-co.xyz/crs/addwallet.php?txn_status=FAILED'
    );
}
?>      