<?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'];
$bank_name = $_POST['bank_name'];
$holder_name = $_POST['holder_name'];
$account_no = $_POST['account_no'];
$mobile = $_POST['mobile'];
$amount = $_POST['amount'];
$branch_name = $_POST['branch_name'];
$district = $_POST['district'];
$date = date('Y-m-d'); // Current date
$status = 'Pending';

// Check for minimum amount requirement
if ($amount < 500) {
    $_SESSION['message'] = "পরিমাণ 500 টাকার বেশি হতে হবে।";
    header("Location: index.php");
    exit();
}

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

if ($stmtCheckBalance === false) {
    $_SESSION['message'] = "একটি ত্রুটি ঘটেছে।";
    header("Location: index.php");
    exit();
}

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

// Check if user has enough balance
if ($currentBalance < $amount) {
    $_SESSION['message'] = "আপনার অ্যাকাউন্টে পর্যাপ্ত টাকা নেই।";
    header("Location: index.php");
    exit();
}

// Prepare the SQL statement to insert into the mobile_banking table
$sqlInsertTopup = "INSERT INTO banking (userid, bank_name, holder_name, account_no, mobile, amount, branch_name, district, date, status)
                   VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
$stmtInsertTopup = $con->prepare($sqlInsertTopup);

if ($stmtInsertTopup === false) {
    $_SESSION['message'] = "রিকোয়েস্ট সম্পন্ন করতে সমস্যা হয়েছে।";
    header("Location: index.php");
    exit();
}

// Binding types
$stmtInsertTopup->bind_param("isssssssss", $userid, $bank_name, $holder_name, $account_no, $mobile, $amount, $branch_name, $district, $date, $status);

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

// Close connections
$stmtInsertTopup->close();
$con->close();

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