<?php
    //get member id
    session_start();
    $mem_id = $_SESSION["memid"];
    include("conn.php");

    // Check connection
    if (mysqli_connect_errno()) {
        die("Connection failed: " . mysqli_connect_error());
    }
    //payment method
    $payment = $_POST["payment"];
    // about the item
    $item_id = $_POST["itemID"];
    $item_number = $_POST["itemAmount"];
    $total = $_POST["total"];
    
    $sql = "INSERT INTO online_payment (Payment_Amount, Payment_Method)
    VALUES ('$total', '$payment');";
    mysqli_query($conn, $sql);

    //-->>>>set the payment id for online_ordering table
    $sql_pid = "SELECT Payment_ID FROM online_payment ORDER BY Payment_ID DESC LIMIT 0, 1";
    $rows = mysqli_fetch_array(mysqli_query($conn,$sql_pid));
    $payment_id = $rows["Payment_ID"];
    //online_ordering table!!!!!!!!
    $sql = "INSERT INTO online_ordering (Order_Date, Mem_ID, Payment_ID, Order_Status, Man_ID)
    VALUES ('".date("Y-m-d H:i:s")."', $mem_id, $payment_id, 'Processing', 1)";
    mysqli_query($conn, $sql);

    //--->>>>set the order_id for online_ordering_details table
    $sql_oid = "SELECT Order_ID FROM online_ordering ORDER BY Order_ID DESC LIMIT 0, 1";
    $rows = mysqli_fetch_array(mysqli_query($conn,$sql_oid));
    $order_id = $rows["Order_ID"];
    //online_ordering_details table!!
    $min = min(count($item_id), count($item_number));
    for($i=0; $i < $min; $i++){
    $sql = "INSERT INTO online_ordering_details (Order_ID, Item_ID, Order_Amount)
    VALUES ($order_id, $item_id[$i], $item_number[$i]);";
    mysqli_query($conn, $sql);
    //update the items stock
    $sql = "UPDATE item SET Item_Stock = Item_Stock - $item_number[$i] WHERE Item_ID = $item_id[$i]";
    mysqli_query($conn, $sql);
    }
    


    if (mysqli_query($conn, $sql)) {
        setcookie("shopping_cart", "", date("0"));
        echo("<script>alert('You have successfully buy the items! The items will be delivered soon!');
        window.location.href='my_purchases.php';</script>");
    } else {
        echo "Error: " . $sql . "<br>" . mysqli_error($conn);
        die ("<script>window.history.go(-1);</script>")	;
    }


    mysqli_close($conn);
?>