<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

ob_start();
if (session_status() === PHP_SESSION_NONE) { 
    session_start(); 
}

// Setup full tracking configuration hooks
require_once('../../titancore/titanconfig.php');
require_once('lib/Config_RechPay.php');
require_once('lib/RechPayChecksum.php');
include('../functions.php');

if (!isset($_POST['akupi'], $_POST['amount'], $_POST['id'])) {
    die("Invalid request parameters detected.");
}

$amount  = $conn->real_escape_string(trim($_POST['amount']));
$user_id = $conn->real_escape_string(trim($_POST['id']));

if (!is_numeric($amount) || $amount < 1 || $amount > 10000) {
    die("Invalid processing parameters provided. Permitted values range: ₹50 to ₹10,000.");
}

/* ===================== EXTRACT DATA FROM FRAMEWORK CONTEXT ===================== */
$user_query = $conn->query("SELECT id, phone, email, wallet FROM users WHERE id = '$user_id' LIMIT 1");
if (!$user_query || $user_query->num_rows === 0) {
    die("Account context verification failed.");
}

$user = $user_query->fetch_assoc();

$orderid     = 'DMPRINT' . time() . rand(11111, 99999);
$phone       = $user['phone'];
$email       = !empty($user['email']) ? $user['email'] : 'info@titanapi.com';
$balance     = (float)$user['wallet'];
$new_balance = $balance;

/* ===================== LOG TRANSACTION IN HISTORY ===================== */
$purpose = "WALLET";
$type    = "Credit";
$status  = "0";

$insert_sql = "INSERT INTO `wallethistory` 
               (`userid`, `orderid`, `purpose`, `type`, `amount`, `balance`, `new_balance`, `txn_id`, `status`) 
               VALUES 
               ('$phone', '$orderid', '$purpose', '$type', '$amount', '$balance', '$new_balance', '$orderid', '$status')";

if (!$conn->query($insert_sql)) {
    die("Transaction ledger entry initialization error: " . $conn->error);
}

/* ===================== GENERATE CHECKSUM & FORWARD TO API ===================== */
$token        = "ae91cf-4da9be-8d9126-52175c-53bc98";
$secret       = "Xft2ConEj6";
$upiuid       = "paytm.s20bntq@pty";

// Build a dynamic internal callback URL path structure
$protocol     = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
$callback_url = $protocol . $_SERVER['SERVER_NAME'] . "/dashboard/akpaytm/txnResult.php";
$gateway_url  = "https://upi.anshulcyberpoint.in/order/paytm";

$params = [
    "cust_Mobile"  => $phone,
    "cust_Email"   => $email,
    "upiuid"       => $upiuid,
    "token"        => $token,
    "orderId"      => $orderid,
    "txnAmount"    => $amount,
    "txnNote"      => $user_id,
    "callback_url" => $callback_url
];

$checksum = RechPayChecksum::generateSignature($params, $secret);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Redirecting to Payment Gateway</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #f8f9fa; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; }
        .loader-card { background: white; padding: 40px; border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); text-align: center; max-width: 40px; width: 100%; }
        h3 { color: #2b3a4a; margin-bottom: 8px; }
        p { color: #6c757d; font-size: 14px; margin-top: 0; }
    </style>
</head>
<body>

<div class="loader-card">
    <h3>Connecting Securely...</h3>
    <p>Please do not close windows or refresh browser contents.</p>
</div>

<form method="post" action="<?= htmlspecialchars($gateway_url, ENT_QUOTES, 'UTF-8') ?>" name="paymentForm" style="display:none;">
    <?php foreach ($params as $key => $value): ?>
        <input type="hidden" name="<?= htmlspecialchars($key, ENT_QUOTES, 'UTF-8') ?>" value="<?= htmlspecialchars($value, ENT_QUOTES, 'UTF-8') ?>">
    <?php endforeach; ?>
    <input type="hidden" name="checksum" value="<?= htmlspecialchars($checksum, ENT_QUOTES, 'UTF-8') ?>">
</form>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        document.paymentForm.submit();
    });
</script>

</body>
</html>
<?php 
ob_end_flush(); 
?>