<?php
    session_start();

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

    require './connect.php';

    $orders_res = mysqli_query($conn, "SELECT * FROM orders WHERE status = 'd'; ");
?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="./CSS/AdminOrders.css">
        <title>Delivered Orders</title>
    </head>
    <body>
        <table class="container">
            <tr class="header">
                <th>Order Number</th>
                <th>User ID</th>
                <th>Order Date</th>
                <th>Shipped Date</th>
                <th>Delivered Date</th>
                <th>Price</th>
                <th>City</th>
                <th>Postal Code</th>
                <th>Address</th>
                <th></th>
            </tr>
            <?php

                foreach($orders_res as $order) {
                    $order_price = 0;
                    $order_items = mysqli_query($conn, "SELECT * FROM order_item WHERE order_id={$order['id']};");

                    foreach($order_items as $item) {
                        $product_name = mysqli_query($conn, "SELECT name FROM products INNER JOIN order_item ON products.product_id = order_item.product_id WHERE order_item.id={$item['id']};")->fetch_assoc()['name'];
                        $order_price = $order_price + ($item['quantity']*$item['price']);
                    }
                    ?>
                        <tr>
                            <td><?php echo $order['id'] ?></td>
                            <td><?php echo $order['user_id'] ?></td>
                            <td><?php echo $order['order_date'] ?></td>
                            <td><?php echo $order['shipped_date'] ?></td>
                            <td><?php echo $order['arrived_date'] ?></td>
                            <td>$<?php echo $order_price ?></td>
                            <td><?php echo $order['city'] ?></td>
                            <td><?php echo $order['postal_code'] ?></td>
                            <td><?php echo $order['address'] ?></td>
                            <td>
                                <a href='./ViewOrder.php?order_id=<?php echo $order['id'] ?>'>View</a>
                            </td>
                        </tr>
                    <?php
                }

            ?>
        </table>
    </body>
</html>