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

// Check user's 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($balance);
$stmtCheckBalance->fetch();
$stmtCheckBalance->close();

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

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

    // Binding parameters for the insert
    $stmtInsertTopup->bind_param("issssss", $userid, $sim_name, $sim_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'] = "আপনার অ্যাকাউন্টে পর্যাপ্ত টাকা নেই";
}

header("Location: index.php");

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