<?php
    session_start();
    if($_SERVER['REQUEST_METHOD']=="POST"){
        include("db.php");
        $time=$_POST['Time'];
        $date=$_POST['Date'];
        $type=$_POST['Type'];

        $sql="INSERT INTO `Orders`(`User_id`,`Type`, `DateMade`, `Deliverytime`) VALUES (?,?,?,?)";
        $stmt=mysqli_stmt_init($conn);
        mysqli_stmt_prepare($stmt,$sql);
        mysqli_stmt_bind_param($stmt,"isss",$_SESSION['id'],$type,$date,$time,);
        if(!mysqli_stmt_execute($stmt)){
            die("ERROR failed to insert new order" .mysqli_stmt_error($stmt));
        }
        else{
            $order_id=mysqli_stmt_insert_id($stmt);
            mysqli_stmt_close($stmt);

            $sql="INSERT INTO `Order_items`(`Order_id`,`ProductName`,`Amount`, `Price`) SELECT ?,`ProductName`,`ProductAmount`,`ProductPrice` FROM `basket` WHERE User_id=?";
            $stmt=mysqli_stmt_init($conn);
            mysqli_stmt_prepare($stmt,$sql);
            mysqli_stmt_bind_param($stmt,"ii",$_SESSION['id'],$order_id);
            if(!mysqli_stmt_execute($stmt)){
                die("ERROR, fialed to copy basket" .mysqli_stmt_error($stmt));
            }
            else{
                mysqli_stmt_close($stmt);
                $sql="DELETE * FROM basket WHERE User_id=?";
                $stmt=mysqli_stmt_init($conn);
                mysqli_stmt_prepare($stmt,$sql);
                mysqli_stmt_bind_param($stmt,"i",$_SESSION['id']);
                if(!mysqli_stmt_execute($stmt)){
                    die("ERROR, failed delete basket" .mysqli_stmt_error($stmt));
                }
                else{
                    echo"<script>alert('Order successfull');</script>";
                    echo"<script>window.location.href='Customer=Products.php';</script>";
                }
                
            }

        }
    }
?>