<?php
session_start();
include "../connection.php"; 


if (!isset($_SESSION['userid'])) {
    // Check if the cookie exists
    if (isset($_COOKIE['userid'])) {
        $_SESSION['userid'] = $_COOKIE['userid'];
    } else {
        header("Location: ../login.php");
        exit();
    }
}

$userid = $_SESSION['userid'];
$gateway = $_POST['gateway'];
$trans_type = $_POST['trans_type'];
$mobile = $_POST['mobile'];
$amount = $_POST['amount'];
$date = date('Y-m-d'); // Current date and time
$status = 'Pending';

// Fetch user's current balance
$sqlCheckBalance = "SELECT amount FROM balance WHERE userid = ?";
$stmtCheckBalance = $con->prepare($sqlCheckBalance);

if ($stmtCheckBalance === false) {
    die('Prepare failed: ' . htmlspecialchars($con->error));
}

$stmtCheckBalance->bind_param("i", $userid);
$stmtCheckBalance->execute();
$stmtCheckBalance->bind_result($currentBalance);
$stmtCheckBalance->fetch();
$stmtCheckBalance->close();

if ($currentBalance >= $amount) {
    // Prepare the SQL statement to insert into the mobile_banking table
    $sqlInsertTopup = "INSERT INTO mobile_banking (userid, gateway, trans_type, mobile, amount, date, status)
                       VALUES (?, ?, ?, ?, ?, ?, ?)";
    $stmtInsertTopup = $con->prepare($sqlInsertTopup);

    if ($stmtInsertTopup === false) {
        die('Prepare failed: ' . htmlspecialchars($con->error));
    }

    // Corrected binding types
    $stmtInsertTopup->bind_param("issssss", $userid, $gateway, $trans_type, $mobile, $amount, $date, $status);

    if ($stmtInsertTopup->execute()) {
        // Success message
        $_SESSION['message'] = "রিকোয়েস্ট সফল হয়েছে";
    } else {
        // Error message
        $_SESSION['message'] = "দু:খিত! পুনরায় চেষ্টা করুন";
    }

    $stmtInsertTopup->close();
} else {
    // Insufficient balance message
    $_SESSION['message'] = " আপনার অ্যাকাউন্টে পর্যাপ্ত টাকা নেই ";
}

// Close connection
$con->close();

// Redirect to index.php
header("Location: index.php");
exit();
?>
