<?php
/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

if (!defined('NICKELBOX')) {
    die("Direct access denied.");
}

if ($loggedin !== true || is_null($account)) {
    header('Location: ./?page=login');
    die("Please log in.");
}
?>

<div class="container mt-4">
    <h1 class="display-4">Account</h1>

    <div class="row">
        <div class="col-md-8">
            <h3>Recent Orders</h3>
            <div class="list-group">
                <?php
                $orders = $database->select('transactions', ['txid', 'txdate', 'type'], ['customerid' => $account['id'], 'ORDER' => ['txdate' => 'DESC'], 'LIMIT' => 50]);
                foreach ($orders as $o) {
                    $lines = $database->select('lines', ['lineid', 'amount', 'qty', 'name'], ['txid' => $o['txid']]);
                    $itemcount = 0;
                    $total = 0.0;
                    foreach ($lines as $l) {
                        $itemcount += $l['qty'];
                        $total += $l['amount'] * $l['qty'];
                    }
                    ?>
                    <div class="list-group-item">
                        Date: <?php echo date(DATETIME_FORMAT, strtotime($o['txdate'])); ?><br />
                        Type: <?php
                        switch ($o['type']) {
                            case 1:
                                echo "In-store";
                                break;
                            case 2:
                                echo "Return";
                                break;
                            case 3:
                                echo "Online";
                                break;
                            default:
                                echo "Other";
                                break;
                        }
                        ?><br />
                        Total: $<?php echo number_format($total, 2); ?><br />
                        <div class="list-group list-group-flush">
                            <?php
                            foreach ($lines as $l) {
                                ?>
                                <div class="list-group-item d-flex justify-content-between">
                                    <div><?php echo $l['name']; ?></div>
                                    <div><?php echo $l['qty'] * 1.0; ?>@<?php echo number_format($l['amount'], 2); ?></div>
                                    <div>$<?php echo number_format($l['amount'] * $l['qty'], 2); ?></div>
                                </div>
                                <?php
                            }
                            ?>
                        </div>
                    </div>
                    <?php
                }
                ?>
            </div>
        </div>
    </div>
</div>