<?php

session_set_cookie_params([
    'lifetime' => 0,                           // browser close तक
    'path'     => '/',                          // पूरे डोमेन में वैध
    'domain'   => 'allbirth.shop', // आपका 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;
// =============== TELEGRAM FUNCTION FIXED ===============
function sendTelegramMsg($message) {
    

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $data,
        CURLOPT_RETURNTRANSFER => true
    ]);
    curl_exec($ch);
    curl_close($ch);
}

/**
 * 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://allbirth.shop/crs/wallet.php'
            );
        }

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

        $map = [
            100 => 100, 
            200 => 250, 
            300 => 400, 
            400 => 600, 
            500 => 700,
        ];
        $txn_amounts = $map[$total_txn_amt] ?? $total_txn_amt;

        $userid = $sender_note;

      // =============== TELEGRAM MESSAGE SEND ===============
        $msg  = "✅ *UPI Payment Received Successfully*\n\n";
        $msg .= "💰 Amount: ₹".$txnAmount."\n";
        $msg .= "🧾 Add Wallet: ₹".$txn_amounts."\n";
        $msg .= "👤 UserID: ".$userid."\n";
        $msg .= "🔢 UTR: ".$pdata['utr']."\n";
        $msg .= "⏰ Time: ".date("H:i:s d-m-Y")."\n";
        $msg .= "🌐 Domain: allbirth.shop\n";


        sendTelegramMsg($msg);
        // ---- 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://allbirth.shop/crs/addwallet.php?txn_status=SUCCESS'
            );

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

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

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