<?php

require_once __DIR__ . '/../app/auth.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/../app/orders.php';
require_once __DIR__ . '/../app/pricing.php';
require_once __DIR__ . '/../app/settings.php';
require_once __DIR__ . '/../app/public-orders.php';
require_once __DIR__ . '/../app/contact-messages.php';

$user = sparrow_require_backyard_login();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $bulk_action = $_POST['bulk_action'] ?? '';
    $order_ids = $_POST['order_ids'] ?? [];

    if (!is_array($order_ids)) {
        $order_ids = [];
    }

    $order_ids = array_values(array_unique(array_filter(array_map('intval', $order_ids))));

    if ($bulk_action === 'print_work_log') {
        if (!$order_ids) {
            sparrow_redirect('/backyard/dashboard.php?bulk_error=no_orders');
        }

        sparrow_redirect('/backyard/work-log.php?ids=' . implode(',', $order_ids));
    }
}

$pdo = sparrow_db();

$orders = sparrow_get_orders();

/*
 * Find customer-submitted approval change requests.
 */
$approval_change_requests = array_values(array_filter(
    $orders,
    static function (array $order): bool {
        $approval_status = trim(
            (string) ($order['approval_status'] ?? '')
        );

        $customer_notes = trim(
            (string) (
                $order['customer_approval_notes']
                ?? ''
            )
        );

        return $approval_status === 'changes_requested'
            && $customer_notes !== '';
    }
));

/*
 * Find public order requests that have not been reviewed
 * or converted yet.
 */
$public_order_requests = sparrow_get_public_order_requests();

$new_order_requests = array_values(array_filter(
    $public_order_requests,
    static function (array $request): bool {
        $request_status = strtolower(trim(
            (string) ($request['status'] ?? '')
        ));

        return $request_status === 'new'
            && empty($request['converted_order_id']);
    }
));

/*
 * Find customer messages that have not been opened yet.
 */
$new_contact_messages = sparrow_get_contact_messages('New');

$dashboard_notice_count =
    count($approval_change_requests)
    + count($new_order_requests)
    + count($new_contact_messages);

$dashboard_setting_keys = [
    'show_daily_verse',
    'show_prayer_prompt',
    'hide_merged_archived',
    'hide_delivered',
    'default_dashboard_view',
];

foreach (array_keys(sparrow_setting_defaults()) as $setting_key) {
    if (str_starts_with($setting_key, 'kpi_')) {
        $dashboard_setting_keys[] = $setting_key;
    }
}

$dashboard_settings = sparrow_get_settings(
    $pdo,
    $dashboard_setting_keys
);

$show_dashboard_kpi = static function (
    string $key
) use ($dashboard_settings): bool {
    return ($dashboard_settings[$key] ?? 'yes') === 'yes';
};

$dashboard_totals = sparrow_get_dashboard_totals();

/*
 * Gift orders stay in the order and product counts, but they are not sales,
 * payments, discounts, or outstanding receivables. Adjust the existing
 * dashboard totals here so older totals helpers also report gifts correctly.
 */
$dashboard_gift_count = 0;
$dashboard_order_received_count = 0;
$dashboard_order_approved_count = 0;

foreach ($orders as $dashboard_gift_order) {
    $dashboard_order_status = trim(
        (string) ($dashboard_gift_order['status'] ?? '')
    );

    if ($dashboard_order_status === 'Order Received') {
        $dashboard_order_received_count++;
    }

    if ($dashboard_order_status === 'Order Approved') {
        $dashboard_order_approved_count++;
    }

    if (empty($dashboard_gift_order['is_gift'])) {
        continue;
    }

    $dashboard_gift_count++;

    $gift_order_id = (int) ($dashboard_gift_order['id'] ?? 0);
    $gift_pricing = sparrow_calculate_order_pricing_from_lookup($gift_order_id);

    $gift_total = (float) ($dashboard_gift_order['total_amount'] ?? 0);

    if ($gift_total <= 0) {
        $gift_total = (float) ($gift_pricing['retail_total'] ?? 0);
    }

    $gift_discount = (float) ($dashboard_gift_order['order_discount_amount'] ?? 0);
    $gift_customer_total = max(0, $gift_total - $gift_discount);
    $gift_paid = (float) ($dashboard_gift_order['paid_amount'] ?? 0);
    $gift_old_balance = max(0, $gift_customer_total - $gift_paid);

    /*
     * Remove the amounts the standard totals helper would have treated as a
     * sale. Costs remain included, so estimated profit becomes the gift loss.
     */
    $dashboard_totals['total_revenue'] = max(
        0,
        (float) ($dashboard_totals['total_revenue'] ?? 0) - $gift_customer_total
    );
    $dashboard_totals['total_collected'] = max(
        0,
        (float) ($dashboard_totals['total_collected'] ?? 0) - $gift_paid
    );
    $dashboard_totals['outstanding_balance'] = max(
        0,
        (float) ($dashboard_totals['outstanding_balance'] ?? 0) - $gift_old_balance
    );
    $dashboard_totals['total_discounts'] = max(
        0,
        (float) ($dashboard_totals['total_discounts'] ?? 0) - $gift_discount
    );
    $dashboard_totals['estimated_profit'] =
        (float) ($dashboard_totals['estimated_profit'] ?? 0) - $gift_customer_total;

    if ($gift_paid <= 0 && $gift_customer_total > 0) {
        $dashboard_totals['unpaid_count'] = max(
            0,
            (int) ($dashboard_totals['unpaid_count'] ?? 0) - 1
        );
    } elseif ($gift_paid > 0 && $gift_paid < $gift_customer_total) {
        $dashboard_totals['partial_count'] = max(
            0,
            (int) ($dashboard_totals['partial_count'] ?? 0) - 1
        );
    } else {
        $dashboard_totals['paid_count'] = max(
            0,
            (int) ($dashboard_totals['paid_count'] ?? 0) - 1
        );
    }

}

$dashboard_view_options = [
    'active' => 'Active Orders',
    'production' => 'In Production',
    'ready' => 'Ready for Pickup',
    'delivered' => 'Delivered',
    'hidden' => 'Hidden / Archived',
    'all' => 'All Orders',
];

$default_dashboard_view = (string) (
    $dashboard_settings['default_dashboard_view'] ?? 'active'
);

if (!isset($dashboard_view_options[$default_dashboard_view])) {
    $default_dashboard_view = 'active';
}

$dashboard_view = trim((string) ($_GET['view'] ?? ''));

if (!isset($dashboard_view_options[$dashboard_view])) {
    $dashboard_view = $default_dashboard_view;
}

$hide_merged_archived =
    ($dashboard_settings['hide_merged_archived'] ?? 'yes') === 'yes';
$hide_delivered =
    ($dashboard_settings['hide_delivered'] ?? 'no') === 'yes';

$orders = array_values(array_filter(
    $orders,
    static function (array $order) use (
        $dashboard_view,
        $hide_merged_archived,
        $hide_delivered
    ): bool {
        $status = trim((string) ($order['status'] ?? ''));

        switch ($dashboard_view) {
            case 'production':
                return in_array(
                    $status,
                    ['Products Ordered', 'Pressing', 'Packaging'],
                    true
                );

            case 'ready':
                return $status === 'Ready for Pickup';

            case 'delivered':
                return in_array($status, ['Delivered', 'Completed'], true);

            case 'hidden':
                return in_array($status, ['Merged', 'Archived'], true);

            case 'all':
                return true;

            case 'active':
            default:
                if (
                    $hide_merged_archived
                    && in_array($status, ['Merged', 'Archived'], true)
                ) {
                    return false;
                }

                if (
                    $hide_delivered
                    && in_array($status, ['Delivered', 'Completed'], true)
                ) {
                    return false;
                }

                return true;
        }
    }
));

sparrow_backyard_header('Backyard Dashboard');

?>

<?php if ($dashboard_notice_count > 0): ?>
    <section class="card dashboard-approval-alert">
        <h2>Notice!</h2>

        <p>
    You have <?php echo $dashboard_notice_count; ?>
    <?php echo $dashboard_notice_count === 1
        ? 'item'
        : 'items'; ?>
    waiting for your attention.
</p>

        <div class="dashboard-approval-alert-list">
            <?php foreach (
                $approval_change_requests
                as $change_request
            ): ?>
                <?php
                $change_order_id = (int) (
                    $change_request['id'] ?? 0
                );

                $change_notes = trim(
                    (string) (
                        $change_request[
                            'customer_approval_notes'
                        ] ?? ''
                    )
                );

                $change_response_date = '';

                if (
                    !empty(
                        $change_request[
                            'approval_responded_at'
                        ]
                    )
                ) {
                    $change_timestamp = strtotime(
                        $change_request[
                            'approval_responded_at'
                        ]
                    );

                    if ($change_timestamp !== false) {
                        $change_response_date = date(
                            'F j, Y \a\t g:i A',
                            $change_timestamp
                        );
                    }
                }
                ?>

                <div class="dashboard-approval-alert-item">
                    <div class="dashboard-approval-alert-heading">
                        <strong>
                            <?php echo sparrow_escape(
                                $change_request[
                                    'order_number'
                                ] ?? 'Order'
                            ); ?>
                            ·
                            <?php echo sparrow_escape(
                                $change_request[
                                    'customer_name'
                                ] ?? 'Customer'
                            ); ?>
                        </strong>

                        <a
                            class="button button-small"
                            href="<?php echo sparrow_escape(
                                sparrow_url(
                                    '/backyard/order-view.php?id='
                                    . $change_order_id
                                )
                            ); ?>"
                        >
                            View Request
                        </a>
                    </div>

                    <div class="dashboard-approval-alert-note">
                        <?php echo nl2br(
                            sparrow_escape($change_notes)
                        ); ?>
                    </div>

                    <?php if ($change_response_date !== ''): ?>
                        <div class="dashboard-approval-alert-date">
                            Submitted
                            <?php echo sparrow_escape(
                                $change_response_date
                            ); ?>
                        </div>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
			<?php foreach ($new_order_requests as $order_request): ?>
    <?php
    $request_id = (int) ($order_request['id'] ?? 0);

    $request_customer = trim(
        (string) ($order_request['customer_name'] ?? '')
    );

    $request_type = trim(
        (string) ($order_request['order_type'] ?? '')
    );

    $request_quantity = trim(
        (string) ($order_request['quantity'] ?? '')
    );

    $request_details = trim(
        (string) ($order_request['message'] ?? '')
    );

    $request_date = '';

    if (!empty($order_request['created_at'])) {
        $request_timestamp = strtotime(
            $order_request['created_at']
        );

        if ($request_timestamp !== false) {
            $request_date = date(
                'F j, Y \a\t g:i A',
                $request_timestamp
            );
        }
    }
    ?>

    <div class="dashboard-approval-alert-item">
        <div class="dashboard-approval-alert-heading">
            <strong>
                New Order Request ·
                <?php echo sparrow_escape(
                    $request_customer !== ''
                        ? $request_customer
                        : 'Customer'
                ); ?>
            </strong>

            <a
                class="button button-small"
                href="<?php echo sparrow_escape(
                    sparrow_url(
                        '/backyard/order-requests.php'
                        . '#request-' . $request_id
                    )
                ); ?>"
            >
                View Request
            </a>
        </div>

        <div class="dashboard-approval-alert-note">
            <?php if ($request_type !== ''): ?>
                <strong>
                    <?php echo sparrow_escape($request_type); ?>
                </strong>
            <?php endif; ?>

            <?php if ($request_quantity !== ''): ?>
                <span>
                    · Quantity:
                    <?php echo sparrow_escape(
                        $request_quantity
                    ); ?>
                </span>
            <?php endif; ?>
        </div>

        <?php if ($request_date !== ''): ?>
            <div class="dashboard-approval-alert-date">
                Submitted
                <?php echo sparrow_escape($request_date); ?>
            </div>
        <?php endif; ?>
    </div>
<?php endforeach; ?>

<?php foreach ($new_contact_messages as $contact_message): ?>
    <?php
    $message_id = (int) (
        $contact_message['id'] ?? 0
    );

    $message_sender = trim(
        (string) ($contact_message['name'] ?? '')
    );

    $message_subject = trim(
        (string) ($contact_message['subject'] ?? '')
    );

    $message_preview = trim(
        preg_replace(
            '/\s+/',
            ' ',
            (string) ($contact_message['message'] ?? '')
        )
    );

    if (strlen($message_preview) > 160) {
        $message_preview = substr(
            $message_preview,
            0,
            157
        ) . '...';
    }

    $message_received_date = '';

    if (!empty($contact_message['created_at'])) {
        $message_timestamp = strtotime(
            $contact_message['created_at']
        );

        if ($message_timestamp !== false) {
            $message_received_date = date(
                'F j, Y \a\t g:i A',
                $message_timestamp
            );
        }
    }
    ?>

    <div class="dashboard-approval-alert-item">
        <div class="dashboard-approval-alert-heading">
            <strong>
                New Customer Message ·
                <?php echo sparrow_escape(
                    $message_sender !== ''
                        ? $message_sender
                        : 'Customer'
                ); ?>
            </strong>

            <a
                class="button button-small"
                href="<?php echo sparrow_escape(
                    sparrow_url(
                        '/backyard/message-view.php?id='
                        . $message_id
                    )
                ); ?>"
            >
                View Message
            </a>
        </div>

        <div class="dashboard-approval-alert-note">
            <?php if ($message_subject !== ''): ?>
                <strong>
                    <?php echo sparrow_escape(
                        $message_subject
                    ); ?>
                </strong>
            <?php endif; ?>

            <?php if ($message_preview !== ''): ?>
                <p>
                    <?php echo sparrow_escape(
                        $message_preview
                    ); ?>
                </p>
            <?php endif; ?>
        </div>

        <?php if ($message_received_date !== ''): ?>
            <div class="dashboard-approval-alert-date">
                Received
                <?php echo sparrow_escape(
                    $message_received_date
                ); ?>
            </div>
        <?php endif; ?>
    </div>
<?php endforeach; ?>
        </div>
    </section>
<?php endif; ?>

<section class="card">
    <h1>Backyard Dashboard</h1>
	<p>
    <h3>
        Welcome, <?php echo sparrow_escape($user['name']); ?>.
    </h3>
</section>

<?php
$verse = sparrow_get_daily_verse($pdo);
$prayer = sparrow_get_daily_prayer($pdo);
$show_daily_verse =
    ($dashboard_settings['show_daily_verse'] ?? 'yes') === 'yes';
$show_prayer_prompt =
    ($dashboard_settings['show_prayer_prompt'] ?? 'yes') === 'yes';
?>

<?php if (
    ($show_daily_verse && !empty($verse['text']))
    || ($show_prayer_prompt && $prayer !== '')
): ?>
<section class="card daily-verse-card">
    <?php if ($show_daily_verse && !empty($verse['text'])): ?>
        <h2>Daily Verse</h2>

        <p id="daily-verse">
            <?php if (!empty($verse['reference'])): ?>
                <strong><?= htmlspecialchars($verse['reference']) ?>:</strong>
            <?php endif; ?>

            <?= htmlspecialchars($verse['text']) ?>
        </p>
    <?php endif; ?>

    <?php if ($show_prayer_prompt && $prayer !== ''): ?>
        <h3>Daily Prayer</h3>

        <p id="daily-prayer">
            <?= nl2br(htmlspecialchars($prayer)) ?>
        </p>
    <?php endif; ?>
</section>
<?php endif; ?>

<section class="dashboard-kpi-groups">

    <details class="dashboard-kpi-group-card">
        <summary>Order Counts</summary>

        <div class="dashboard-kpi-grid dashboard-kpi-grid-small">

            <?php if ($show_dashboard_kpi('kpi_total_orders')): ?>
                <div class="dashboard-kpi-card">
                    <span>Total Orders</span>
                    <strong><?= number_format((int) $dashboard_totals['order_count']) ?></strong>
                </div>
            <?php endif; ?>

            <?php if ($show_dashboard_kpi('kpi_open_orders')): ?>
                <div class="dashboard-kpi-card dashboard-kpi-blue">
                    <span>Open Orders</span>
                    <strong><?= number_format((int) $dashboard_totals['open_count']) ?></strong>
                </div>
            <?php endif; ?>

            <?php if ($show_dashboard_kpi('kpi_delivered_orders')): ?>
                <div class="dashboard-kpi-card dashboard-kpi-green">
                    <span>Delivered</span>
                    <strong><?= number_format((int) $dashboard_totals['delivered_count']) ?></strong>
                </div>
            <?php endif; ?>

            <?php if ($show_dashboard_kpi('kpi_ready_orders')): ?>
                <div class="dashboard-kpi-card dashboard-kpi-gold">
                    <span>Ready</span>
                    <strong><?= number_format((int) $dashboard_totals['ready_count']) ?></strong>
                </div>
            <?php endif; ?>

        </div>
    </details>

    <details class="dashboard-kpi-group-card">
        <summary>Workflow Status</summary>

        <div class="dashboard-kpi-grid dashboard-kpi-grid-small">

            <?php if ($show_dashboard_kpi('kpi_order_received')): ?>
                <div class="dashboard-kpi-card">
                    <span>Order Received</span>
                    <strong><?= number_format($dashboard_order_received_count) ?></strong>
                </div>
            <?php endif; ?>

            <?php if ($show_dashboard_kpi('kpi_order_approved')): ?>
                <div class="dashboard-kpi-card dashboard-kpi-blue">
                    <span>Order Approved</span>
                    <strong><?= number_format($dashboard_order_approved_count) ?></strong>
                </div>
            <?php endif; ?>

            <?php if ($show_dashboard_kpi('kpi_in_production')): ?>
                <div class="dashboard-kpi-card dashboard-kpi-purple">
                    <span>In Production</span>
                    <strong><?= number_format((int) $dashboard_totals['production_count']) ?></strong>
                </div>
            <?php endif; ?>

            <?php if ($show_dashboard_kpi('kpi_ready_orders')): ?>
                <div class="dashboard-kpi-card dashboard-kpi-gold">
                    <span>Ready</span>
                    <strong><?= number_format((int) $dashboard_totals['ready_count']) ?></strong>
                </div>
            <?php endif; ?>

        </div>
    </details>

    <details class="dashboard-kpi-group-card">
        <summary>Payments</summary>

        <div class="dashboard-kpi-grid dashboard-kpi-grid-small">

            <?php if ($show_dashboard_kpi('kpi_total_revenue')): ?>
                <div class="dashboard-kpi-card dashboard-kpi-money-green">
    <span>Total Revenue</span>
                    <strong>$<?= number_format((float) $dashboard_totals['total_revenue'], 2) ?></strong>
                </div>
            <?php endif; ?>

            <?php if ($show_dashboard_kpi('kpi_collected')): ?>
                <div class="dashboard-kpi-card dashboard-kpi-money-blue">
    <span>Collected</span>
                    <strong>$<?= number_format((float) $dashboard_totals['total_collected'], 2) ?></strong>
                </div>
            <?php endif; ?>

            <?php if ($show_dashboard_kpi('kpi_outstanding')): ?>
                <div class="dashboard-kpi-card dashboard-kpi-money-red">
    <span>Outstanding</span>
                    <strong>$<?= number_format((float) $dashboard_totals['outstanding_balance'], 2) ?></strong>
                </div>
            <?php endif; ?>

            <?php if ($show_dashboard_kpi('kpi_unpaid')): ?>
                <div class="dashboard-kpi-card dashboard-kpi-soft-red">
                    <span>Unpaid</span>
                    <strong><?= number_format((int) $dashboard_totals['unpaid_count']) ?></strong>
                </div>
            <?php endif; ?>

            <?php if ($show_dashboard_kpi('kpi_partial')): ?>
                <div class="dashboard-kpi-card dashboard-kpi-gold">
                    <span>Partial</span>
                    <strong><?= number_format((int) $dashboard_totals['partial_count']) ?></strong>
                </div>
            <?php endif; ?>

            <?php if ($show_dashboard_kpi('kpi_paid')): ?>
                <div class="dashboard-kpi-card dashboard-kpi-green">
                    <span>Paid</span>
                    <strong><?= number_format((int) $dashboard_totals['paid_count']) ?></strong>
                </div>
            <?php endif; ?>

            <?php if ($show_dashboard_kpi('kpi_blessings')): ?>
                <div class="dashboard-kpi-card dashboard-kpi-money-purple">
    <span>Blessings</span>
                    <strong>$<?= number_format((float) $dashboard_totals['total_blessings'], 2) ?></strong>
                </div>
            <?php endif; ?>

            <?php if ($show_dashboard_kpi('kpi_discounts')): ?>
                <div class="dashboard-kpi-card dashboard-kpi-money-pink">
    <span>Discounts</span>
                    <strong>$<?= number_format((float) $dashboard_totals['total_discounts'], 2) ?></strong>
                </div>
            <?php endif; ?>

            <?php if ($show_dashboard_kpi('kpi_gifts')): ?>
                <div class="dashboard-kpi-card dashboard-kpi-money-purple">
                    <span>Gift Orders</span>
                    <strong><?= number_format($dashboard_gift_count) ?></strong>
                </div>
            <?php endif; ?>

        </div>
    </details>

    <details class="dashboard-kpi-group-card">
        <summary>Products / Costs</summary>

        <div class="dashboard-kpi-grid dashboard-kpi-grid-small">

            <?php if ($show_dashboard_kpi('kpi_total_items')): ?>
                <div class="dashboard-kpi-card dashboard-kpi-money-blue">
    <span>Total Items</span>
                    <strong><?= number_format((int) $dashboard_totals['total_quantity']) ?></strong>
                </div>
            <?php endif; ?>

            <?php if ($show_dashboard_kpi('kpi_blank_costs')): ?>
                <div class="dashboard-kpi-card dashboard-kpi-purple">
    <span>Blank Costs</span>
                    <strong>$<?= number_format((float) $dashboard_totals['total_blank_costs'], 2) ?></strong>
                </div>
            <?php endif; ?>

            <?php if ($show_dashboard_kpi('kpi_est_profit')): ?>
                <div class="dashboard-kpi-card dashboard-kpi-money-green">
    <span>Est. Profit</span>
                    <strong>$<?= number_format((float) $dashboard_totals['estimated_profit'], 2) ?></strong>
                </div>
            <?php endif; ?>

        </div>
    </details>

</section>

<section class="card">
    <h2>Current Orders</h2>

    <form
        method="get"
        action="<?= sparrow_escape(sparrow_url('/backyard/dashboard.php')) ?>"
        class="orders-toolbar"
    >
        <div class="bulk-actions">
            <label for="dashboard_view">Show</label>
            <select
                name="view"
                id="dashboard_view"
                class="bulk-action-select"
            >
                <?php foreach ($dashboard_view_options as $value => $label): ?>
                    <option
                        value="<?= sparrow_escape($value) ?>"
                        <?= $dashboard_view === $value ? 'selected' : '' ?>
                    >
                        <?= sparrow_escape($label) ?>
                    </option>
                <?php endforeach; ?>
            </select>

            <button type="submit" class="button">View</button>
        </div>
    </form>

    <?php if (!$orders): ?>
        <p class="muted">
            No orders found in this view.
        </p>
    <?php else: ?>

        <form method="post" action="<?= sparrow_escape(sparrow_url('/backyard/orders-trash.php')) ?>">

            <div class="orders-toolbar">
    <div class="bulk-actions">
<select name="bulk_action" class="bulk-action-select">
    <option value="">Bulk action...</option>
    <option value="print_invoice">Print Invoices</option>
    <option value="print_packing_slip">Print Packing Slips</option>
    <option value="print_work_log">Print Work Logs</option>
    <option value="print_customer_history">
        Print Customer Histories
    </option>
    <option value="trash">Move to Trash</option>
</select>

    <button type="submit" class="button">Apply</button>
            </div>
			</div>

            <div class="table-wrap">
                <table>
                    <thead>
                        <tr>
                            <th>
                                <input type="checkbox" id="select_all_orders">
                            </th>
                            <th>Actions</th>
                            <th>Order</th>
                            <th>Customer</th>
                            <th>Qty</th>
                            <th>Details</th>
                            <th>Payment</th>
                            <th>Order Date</th>
                            <th>Status</th>
                        </tr>
                    </thead>

                    <tbody>
                        <?php foreach ($orders as $order): ?>
                            <tr>
                                <td>
                                    <input type="checkbox" name="order_ids[]" value="<?= (int) $order['id'] ?>">
                                </td>

                                <td>
                                    <a class="button button-small" href="<?= sparrow_escape(sparrow_url('/backyard/order-view.php?id=' . (int) $order['id'])) ?>">
                                        View
                                    </a>
                                </td>

                                <td>
                                    <strong><?php echo sparrow_escape($order['order_number']); ?></strong>
                                </td>

                                <td>
                                    <?php echo sparrow_escape($order['customer_name']); ?>
                                </td>

                                <td>
                                    <?php echo (int) $order['total_quantity']; ?>
                                </td>

                                <td class="dashboard-items-cell" data-label="Items">
    <?php echo sparrow_get_backyard_item_summary_label((int) $order['id']); ?>
</td>

                                <td class="sparrow-payment-cell" data-label="Payment">
    <?php
    $lookup_pricing = sparrow_calculate_order_pricing_from_lookup((int) $order['id']);

$dashboard_total = (float) ($order['total_amount'] ?? 0);

if ($dashboard_total <= 0) {
    $dashboard_total = (float) ($lookup_pricing['retail_total'] ?? 0);
}

$dashboard_paid = (float) ($order['paid_amount'] ?? 0);
$dashboard_blessing = (float) ($order['blessing_amount'] ?? 0);
$dashboard_discount = (float) ($order['order_discount_amount'] ?? 0);
$dashboard_payment_method = trim((string) ($order['payment_method'] ?? ''));
$dashboard_is_gift = !empty($order['is_gift']);
$dashboard_customer_total = max(0, $dashboard_total - $dashboard_discount);
$dashboard_balance = $dashboard_is_gift
    ? 0.00
    : max(0, $dashboard_customer_total - $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>
                                    <?php echo sparrow_escape($order['order_date']); ?>
                                </td>

                                <td class="dashboard-status-cell" data-label="Status">
								<?php
if ($dashboard_is_gift) {
    $dashboard_payment_status_label = 'Gift';
    $dashboard_payment_status_class = 'gift-order-pill';
} elseif ($dashboard_paid <= 0) {
    $dashboard_payment_status_label = 'Not Paid';
    $dashboard_payment_status_class = 'unpaid-pill';
} elseif ($dashboard_paid < $dashboard_customer_total) {
    $dashboard_payment_status_label = 'Partial';
    $dashboard_payment_status_class = 'partial-pill';
} else {
    $dashboard_payment_status_label = 'Paid';
    $dashboard_payment_status_class = 'paid-pill';
}
?>

<span class="dashboard-mini-pill <?= sparrow_escape($dashboard_payment_status_class) ?>">
    <?= sparrow_escape($dashboard_payment_status_label) ?>
</span>

<?php if (!$dashboard_is_gift && !empty($order['payment_method'])): ?>
    <span class="dashboard-mini-pill dashboard-payment-method-pill">
        <?php echo htmlspecialchars($order['payment_method']); ?>
    </span>
<?php endif; ?>
    <?php
    $approval_status = $order['approval_status'] ?? 'waiting';

    $approval_label = 'Approval: Waiting';

    if ($approval_status === 'approved') {
        $approval_label = 'Approval: Approved';
    } elseif ($approval_status === 'changes_requested') {
        $approval_label = 'Approval: Changes Requested';
    }
    ?>

    <span class="dashboard-mini-pill dashboard-order-status-pill">
        <?php echo sparrow_escape($order['status'] ?? 'Order Received'); ?>
    </span>

    <span class="dashboard-mini-pill dashboard-approval-pill dashboard-approval-<?php echo htmlspecialchars($approval_status); ?>">
        <?php echo htmlspecialchars($approval_label); ?>
    </span>
</td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </form>

    <?php endif; ?>
</section>

<script>
const selectAllOrders = document.getElementById('select_all_orders');

if (selectAllOrders) {
    selectAllOrders.addEventListener('change', function () {
        document.querySelectorAll('input[name="order_ids[]"]').forEach(function (checkbox) {
            checkbox.checked = selectAllOrders.checked;
        });
    });
}
</script>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const bulkForm = document.querySelector(
        'form[action*="orders-trash.php"]'
    );

    if (!bulkForm) {
        return;
    }

    bulkForm.addEventListener('submit', function (event) {
        const bulkAction = bulkForm.querySelector(
            'select[name="bulk_action"]'
        );

        const checkedOrders = bulkForm.querySelectorAll(
            'input[name="order_ids[]"]:checked'
        );

        if (!bulkAction) {
            return;
        }

        const printActions = [
            'print_invoice',
            'print_packing_slip',
            'print_work_log',
			'print_customer_history'
        ];

        if (!printActions.includes(bulkAction.value)) {
            return;
        }

        event.preventDefault();

        const ids = Array.from(checkedOrders)
            .map(function (checkbox) {
                return checkbox.value;
            })
            .filter(Boolean);

        if (ids.length === 0) {
            alert(
                'Please select at least one order to print.'
            );
            return;
        }

        const idsQuery = encodeURIComponent(
            ids.join(',')
        );

        if (bulkAction.value === 'print_invoice') {
            window.location.href =
                '<?= sparrow_url('/backyard/invoice.php') ?>'
                + '?ids='
                + idsQuery;

            return;
        }

        if (bulkAction.value === 'print_work_log') {
            window.location.href =
                '<?= sparrow_url('/backyard/work-log.php') ?>'
                + '?ids='
                + idsQuery;

            return;
        }

        if (
    bulkAction.value ===
    'print_packing_slip'
) {
    window.location.href =
        '<?= sparrow_url('/backyard/packing-slip.php') ?>'
        + '?ids='
        + idsQuery;

    return;
}

if (
    bulkAction.value ===
    'print_customer_history'
) {
    window.location.href =
        '<?= sparrow_url('/backyard/customer-print.php') ?>'
        + '?order_ids='
        + idsQuery;

    return;
}

    });
});
</script>

<?php

sparrow_backyard_footer();
