<?php

    session_start();

    require './connect.php';

    if(!isset($_SESSION['user_ID']) ) {
        header("Location: ./Log In.php");
        die();
    }

    if(!isset($_POST['user_id'])) {
        header("Location: ./Cart.php");
        die();
    }

    try {
        $personal_data = mysqli_query($conn, "SELECT * FROM users_information WHERE user_id = {$_SESSION['user_ID']};");

        if(mysqli_num_rows($personal_data) <= 0) {
            header("Location: ./EditProfile.php");
            die();
        }
        else {
            $personal_data = $personal_data->fetch_assoc();
        }

        $order_items = mysqli_query($conn, "SELECT * FROM cart WHERE user_id = {$_SESSION['user_ID']};");
        $order_price = 2;

        foreach($order_items as $item) {
            $item_information = mysqli_query($conn, "SELECT * FROM products WHERE product_id = {$item['product_id']};")->fetch_assoc();
            $order_price = $order_price + (($item_information['price'] - ($item_information['price']*$item_information['discount']/100.0))*$item['quantity']);
        }

        mysqli_query($conn, "insert into orders(user_id, order_date, total_sum, status, city, postal_code, address, phone_number, name, surname)". 
            "values({$_SESSION['user_ID']}, CURDATE(), {$order_price}, 'p', '{$personal_data['city']}', {$personal_data['postal_code']}, '{$personal_data['address']}', ".
            "'{$personal_data['phone_number']}', '{$personal_data['name']}', '{$personal_data['surname']}');");

        $order_id = $conn->insert_id;

        foreach($order_items as $item) {
            $item_information = mysqli_query($conn, "SELECT * FROM products WHERE product_id = {$item['product_id']};")->fetch_assoc();
            $item_price = $item_information['price'] - ($item_information['price']*$item_information['discount']/100.0);
            mysqli_query($conn, "INSERT INTO order_item(order_id, product_id, quantity, price) VALUES ($order_id, {$item_information['product_id']}, {$item['quantity']}, {$item_price});");
        }

        mysqli_query($conn, "DELETE FROM cart WHERE user_id = {$_SESSION['user_ID']};");

        header("Location: ./Profile.php");
    } catch(Exception $e) {

    }



?>