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

require_once('lib/Config_RechPay.php');
require_once('lib/RechPayChecksum.php');
include('config.php');
include('functions.php');

/* ===================== BASIC VALIDATION ===================== */

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

$amount  = safe_str($_POST['amount']);
$user_id = safe_str($_POST['id']);

if (!is_numeric($amount) || $amount < 1 || $amount > 10000) {
    die("Invalid amount. Minimum 50 Rupees.");
}

/* ===================== FETCH USER ===================== */

$stmt = $connection->prepare("SELECT id, phone, email, balance FROM users WHERE id = ?");
if (!$stmt) {
    die("Prepare failed (users): " . $connection->error);
}

$stmt->bind_param("s", $user_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    die("User not found.");
}

$user = $result->fetch_assoc();
$stmt->close();

/* ===================== ORDER DETAILS ===================== */

$orderid     = 'DMPRINT' . time() . rand(11111, 99999);
$phone       = $user['phone'];
$email       = $user['email'];
$balance     = (float)$user['balance'];
$new_balance = $balance;
$now         = date('Y-m-d H:i:s');

/* ===================== INSERT WALLET HISTORY ===================== */

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

$stmt = $connection->prepare($insert_sql);
if (!$stmt) {
    die("Prepare failed (insert): " . mysqli_error($connection));
}

$purpose = "WALLET";
$type    = "Credit";
$status  = "0";

$stmt->bind_param(
    "ssssdddds",
    $phone,        // userid
    $orderid,
    $purpose,
    $type,
    $amount,
    $balance,
    $new_balance,
    $orderid,      // txn_id
    
    $status
);

if (!$stmt->execute()) {
    die("Insert failed: " . $stmt->error);
}

$stmt->close();

/* ===================== PAYMENT GATEWAY ===================== */

$token        = "d61d49-db8c01-d54fab-ad282b-0df7fb";
$secret       = "z00O2QH3aC";
$upiuid       = "paytmqr80kha99smf@paytm";
$callback_url = "https://www.hargharrojgar.in/new/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</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>

<center>
    <h2>Please do not refresh this page...</h2>
</center>

<form method="post" action="<?= htmlspecialchars($gateway_url) ?>" name="paymentForm">
    <?php foreach ($params as $key => $value): ?>
        <input type="hidden" name="<?= htmlspecialchars($key) ?>" value="<?= htmlspecialchars($value) ?>">
    <?php endforeach; ?>
    <input type="hidden" name="checksum" value="<?= htmlspecialchars($checksum) ?>">
</form>

<script>
    document.paymentForm.submit();
</script>

</body>
</html>
