<?php
/* include db connection file */
include("connection.php");
if(isset($_POST['submit'])){
    session_start();
    /* capture values from HTML form */
    $Place = $_POST['place'];
    $renterId = $_POST['ID'];
    $category= $_POST['categoryType'];
    $license = $_POST['Licences'];
    $date = $_POST['dates'];
    $approve = False;
    $check = False;
    $pay = False;
    
    //Admin ID
    $adminSql = "SELECT Admin_ID FROM admin ORDER BY Admin_ID ASC LIMIT 1";
    $adminResult = mysqli_query($conn, $adminSql);
    $adminRow = mysqli_fetch_assoc($adminResult);
    $adminId = $adminRow['Admin_ID'];

    //Order ID
    function generateOrderID() {
        return "Ord" . str_pad(mt_rand(0, 99999), 5, '0', STR_PAD_LEFT);
    }

    // Function to check if the generated order ID already exists in the database
    function isOrderIDExists($conn, $new0rderID) {
        $stmt = $conn->prepare("SELECT COUNT(*) FROM orders WHERE OrderID = ?");
        $stmt->bind_param("s", $newOrderID);
        $stmt->execute();
        $stmt->bind_result($count);
        $stmt->fetch();
        $stmt->close();
        return $count > 0;
    }

    do {
        $newOrderID = generateOrderID();
    } while (isOrderIDExists($conn, $newOrderID));

    // Check if the combination of Place_Num and Dates already exists
    $checkSql = "SELECT * FROM orders WHERE Place_Num = '$Place' AND Dates = '$date'";
    $checkResult = mysqli_query($conn, $checkSql);

    if(mysqli_num_rows($checkResult) > 0) {
        // Combination already exists, show error message
        echo "<script>alert('Selected of Place at that Date is already booked. Please choose another Place or Date.')</script>";
        echo "<script>window.location = 'rentPlace.php'</script>";
        exit();
    }
    else{
        // Insert into user table
        $sql = "INSERT INTO orders (OrderID, Place_Num, Renter_ID, Admin_ID, License, Dates, Category_Type, Approve_Status, Checks_Status, Pay_Status) VALUES ('".$newOrderID."','".$Place."', '".$renterId."', '".$adminId."', '".$license."', '".$date."', '".$category."','".$approve."','".$check."','".$pay."')";

        $column = mysqli_query($conn, $sql); 

        if($column != 0) {
            echo "<script>alert('Your order is successfull, please wait until management approve your order rent')</script>";
            echo "<script>window.location = 'rentermenu.php'</script>";
            exit();
        }
        else {
            echo "<script>alert('ID Or Connection is Error, Please contact our Admin !!!')</script>";
            echo "<script>window.location = 'login.html'</script>";
            exit();
        }
    }
    

    mysqli_close($conn); //data security purposes
    }
?>


