<?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();
    }
}

// Retrieve the user ID from the session
$userid = $_SESSION['userid'];

// Retrieve form data
$account_no = $_POST['account_no'];
$bill_org = $_POST['bill_org'];
$bill_date = $_POST['bill_date'];
$holder_name = $_POST['holder_name'];
$holder_mobile = $_POST['holder_mobile'];
$amount = $_POST['amount'];
$area = $_POST['area'];
$pin = $_POST['pin'];
$date = date('Y-m-d'); // Current date and time
$status = 'Pending';

// Check the balance for the user
$sqlCheckBalance = "SELECT amount FROM balance WHERE userid = ?";
$stmtCheckBalance = $con->prepare($sqlCheckBalance);
$stmtCheckBalance->bind_param("i", $userid);
$stmtCheckBalance->execute();
$stmtCheckBalance->bind_result($balance);
$stmtCheckBalance->fetch();
$stmtCheckBalance->close();

// Check the PIN from the student table
$sqlCheckPin = "SELECT pin FROM student WHERE userid = ?";
$stmtCheckPin = $con->prepare($sqlCheckPin);
$stmtCheckPin->bind_param("i", $userid);
$stmtCheckPin->execute();
$stmtCheckPin->bind_result($storedPin);
$stmtCheckPin->fetch();
$stmtCheckPin->close();

// Validate the conditions
if ($balance >= $amount) {
    if ($storedPin === $pin) {
        // Prepare the SQL statement to insert into the bill_pay table
        $sqlInsertBillPay = "INSERT INTO bill_pay (userid, account_no, bill_org, bill_date, holder_name, holder_mobile, amount, area, pin, date, status)
                             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmtInsertBillPay = $con->prepare($sqlInsertBillPay);

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

        // Bind parameters
        $stmtInsertBillPay->bind_param("issssssssss", $userid, $account_no, $bill_org, $bill_date, $holder_name, $holder_mobile, $amount, $area, $pin, $date, $status);

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

        $stmtInsertBillPay->close();
    } else {
        // Incorrect PIN message
        $_SESSION['message'] = "আপনার পিন নম্বর সঠিক নয়"; // Your PIN number is incorrect
    }
} else {
    // Insufficient balance message
    $_SESSION['message'] = "আপনার অ্যাকাউন্টে পর্যাপ্ত টাকা নেই"; // You do not have sufficient balance in your account
}

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

// Redirect back to the appropriate page
header("Location: index.php"); // Change to your desired page
exit();
?>
