<?php
if(isset($_SESSION['username'])) {
    $sql = "SELECT * FROM wp_extra_orders 
            WHERE userId = " . $_SESSION['user_id'] . " 
            ORDER BY orderId ASC 
            ;";
    
    try {
        $results = $wpdb->get_results($sql);
        ?>

        <h1>List of orders</h1>

        <table class="orders-table">
            <tr>
                <th>Order</th>
                <th>Status</th>
                <th>Total</th>
                <th>ProductName</th>
                <th>Price</th>
                <th>Quantity</th>
                <th>Subtotal</th>
            </tr>
        

        <?php

        if($results && count($results)>0) {

            foreach ($results as $result) {
                $order_id = $result->orderId;

                $sql1 = "SELECT * FROM wp_extra_cart_products cp 
                        JOIN wp_users u ON cp.userId = u.ID 
                        JOIN wp_extra_orders o ON cp.orderId = o.orderId 
                        JOIN wp_extra_products p ON cp.productId = p.Id 
                        WHERE u.ID = " . $_SESSION['user_id'] . " 
                        AND o.orderId = " . $order_id . " 
                        ;";
                
                $results1 = $wpdb->get_results($sql1);
                $count = count($results1);
                if($results1 && $count>0) {
                    $i=0;
                    $total = 0;
                    foreach ($results1 as $result1) {
                        $subtotal = $result1->NewPrice * $result1->quantity;
                        $total += $subtotal;
                        ?>

                        <tr>
                            <?php 
                            if($i == 0) {
                            ?>
                                <td rowspan="<?php echo $count; ?>"><?php echo $order_id ?></td>
                                <td rowspan="<?php echo $count; ?>"><?php echo $result->status ?></td>
                                <td rowspan="<?php echo $count; ?>" id="total-<?php echo $order_id; ?>"></td>
                            <?php
                            }
                            ?>
                            <td><?php echo $result1->Name ?></td>
                            <td>$<?php echo $result1->NewPrice ?></td>
                            <td><?php echo $result1->quantity ?></td>
                            <td>$<?php echo $subtotal ?></td>
                        </tr>

                        <?php
                        $i++;
                    }
                    ?>

                    <input type="hidden" class="order-total" id="order-total-<?php echo $order_id; ?>" value="<?php echo $total; ?>">

                    <?php

                }


            }
        }
        ?>
        </table>
        <?php

    } catch (Exception $ex) {
        echo 'Exception: ' . $ex->getMessage() . '<br>';
    }
}