<?php
// public/backyard/orders.php

require_once __DIR__ . '/../app/auth.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/../app/orders.php';

$user = sparrow_require_backyard_login();

// Fetch all orders, newest first
$orders = sparrow_get_orders([
    'order_by' => 'order_date',
    'order_dir' => 'DESC',
    'exclude_trashed' => true,
]);

sparrow_backyard_header('Orders');

function sparrow_money($amount): string
{
    return '$' . number_format((float)($amount ?? 0), 2);
}

function sparrow_format_order_date($date): string
{
    return $date ? date('j M Y', strtotime($date)) : '';
}
?>

<section class="card">
    <div class="page-heading-row">
        <div>
            <h1>Orders</h1>
            <p class="muted">Main Backyard order list.</p>
        </div>

        <div class="heading-actions">
            <a class="button" href="<?php echo sparrow_escape(sparrow_url('/backyard/order-new.php')); ?>">
                New Order
            </a>
        </div>
    </div>
</section>

<section class="card orders-list-card">
    <?php if (!$orders): ?>
        <p class="muted">No orders found yet.</p>
    <?php else: ?>
        <div class="table-wrap orders-dashboard-wrap">
            <table class="orders-dashboard-table">
                <thead>
                    <tr>
                        <th class="select-col">Select</th>
                        <th class="actions-col">Actions</th>
                        <th class="order-col">Order</th>
                        <th class="customer-col">Customer</th>
                        <th class="items-col">Items</th>
                        <th class="payment-col">Payment</th>
                        <th class="delivery-col">Delivery</th>
                        <th class="status-col">Status</th>
                    </tr>
                </thead>

                <tbody>
                    <?php foreach ($orders as $order): ?>
                        <?php
                        $order_id = (int)($order['id'] ?? 0);
                        $items = sparrow_get_order_items($order_id);

                        $total_amount = (float)($order['total_amount'] ?? 0);
                        $paid_amount = (float)($order['paid_amount'] ?? 0);
                        $blessing_amount = (float)($order['blessing_amount'] ?? 0);
                        $discount_amount = (float)($order['order_discount_amount'] ?? 0);
                        $is_gift = !empty($order['is_gift']);
                        $balance_amount = $is_gift
                            ? 0.00
                            : max(0, $total_amount - $discount_amount - $paid_amount);

                        $delivery_method = trim((string)($order['delivery_method'] ?? 'Not Set'));
                        $status = trim((string)($order['status'] ?? 'Order Received'));

                        $status_class = strtolower($status);
                        $status_class = preg_replace('/[^a-z0-9]+/', '-', $status_class);
                        $status_class = trim($status_class, '-');

                        $is_closed = in_array($status, ['Delivered', 'Completed'], true);
                        ?>
                        <tr>
                            <td class="select-col" data-label="Select">
                                <input type="checkbox" name="selected_orders[]" value="<?= $order_id; ?>">
                            </td>

                            <td class="actions-col" data-label="Actions">
                                <a class="open-pill" href="<?= sparrow_escape(sparrow_url('/backyard/order-view.php?id=' . $order_id)); ?>">
                                    <?= $is_closed ? 'Closed' : 'Open'; ?>
                                </a>
                            </td>

                            <td class="order-col" data-label="Order">
                                <div class="order-number"><?= sparrow_escape($order['order_number']); ?></div>
                                <div class="order-date"><?= sparrow_escape(sparrow_format_order_date($order['order_date'])); ?></div>
                            </td>

                            <td class="customer-col" data-label="Customer">
                                <div class="customer-name"><?= sparrow_escape($order['customer_name']); ?></div>
                                <?php if (!empty($order['customer_phone'])): ?>
                                    <div class="customer-sub"><?= sparrow_escape($order['customer_phone']); ?></div>
                                <?php endif; ?>
                                <?php if (!empty($order['customer_email'])): ?>
                                    <div class="customer-sub"><?= sparrow_escape($order['customer_email']); ?></div>
                                <?php endif; ?>
                            </td>

                            <td class="items-col" data-label="Items">
                                <?php foreach ($items as $item): ?>
                                    <div class="item-line">
                                        <?= htmlspecialchars($item['quantity'] . ' ' . $item['shirt_color'] . ' ' . $item['item_type'] .
                                            (!empty($item['shirt_size']) ? ', ' . $item['shirt_size'] : '') .
                                            (!empty($item['print_location']) ? ', ' . $item['print_location'] : '')
                                        ); ?>
                                    </div>
                                <?php endforeach; ?>
                            </td>

        <td class="sparrow-payment-cell" data-label="Payment">
    <?php
    $dashboard_total = (float) ($order['total_amount'] ?? 0);
    $dashboard_paid = (float) ($order['paid_amount'] ?? 0);
    $dashboard_blessing = (float) ($order['blessing_amount'] ?? 0);
    $dashboard_discount = (float) ($order['order_discount_amount'] ?? 0);
    $dashboard_is_gift = !empty($order['is_gift']);
    $dashboard_balance = $dashboard_is_gift
        ? 0.00
        : max(0, $dashboard_total - $dashboard_discount - $dashboard_paid);
    ?>

    <div class="sparrow-payment-mini-card">
        <div class="sparrow-payment-mini-grid">

            <div class="sparrow-payment-mini-row sparrow-payment-total">
                <span>Total</span>
                <strong>$<?= number_format($dashboard_total, 2) ?></strong>
            </div>

            <div class="sparrow-payment-mini-row sparrow-payment-collected">
                <span>Paid</span>
                <strong>$<?= number_format($dashboard_paid, 2) ?></strong>
            </div>

            <div class="sparrow-payment-mini-row sparrow-payment-blessing">
                <span>Blessing</span>
                <strong>$<?= number_format($dashboard_blessing, 2) ?></strong>
            </div>

            <div class="sparrow-payment-mini-row sparrow-payment-discount">
                <span>Discount</span>
                <strong>$<?= number_format($dashboard_discount, 2) ?></strong>
            </div>

            <div class="sparrow-payment-mini-row sparrow-payment-balance <?= ($dashboard_balance > 0) ? 'sparrow-payment-balance-open' : 'sparrow-payment-balance-paid' ?>">
                <span>Balance</span>
                <strong>$<?= number_format($dashboard_balance, 2) ?></strong>
            </div>

        </div>
    </div>
</td>

                            <td class="delivery-col" data-label="Delivery">
                                <span class="delivery-pill"><?= sparrow_escape($delivery_method); ?></span>
                            </td>

                            <td class="status-col" data-label="Status">
                                <span class="order-status-pill status-<?= $status_class; ?>"><?= sparrow_escape($status); ?></span>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</section>

<?php
sparrow_backyard_footer();
