<?php

$pageTitle = 'Báo cáo & Thống kê - PET SPA';
$pageStyles = ['owner.css'];
$activeOwnerPage = 'reports';
$reportRoute = 'owner/reports';
$reportFilters = [];
$reportQuery = [
    'range' => $range['key'],
    'from' => $range['from'],
    'to' => $range['to']
];

require BASE_PATH . '/app/views/layouts/header.php';
require BASE_PATH . '/app/views/layouts/navbar.php';

?>

<main class="owner-area">

    <div class="container-fluid">

        <div class="row g-4">

            <div class="col-xl-2 col-lg-3">
                <?php require BASE_PATH . '/app/views/layouts/owner-sidebar.php'; ?>
            </div>

            <div class="col-xl-10 col-lg-9">

                <div class="owner-page-header">
                    <div>
                        <h1>Báo cáo & Thống kê</h1>
                        <p>Dữ liệu kỳ báo cáo: <?= htmlspecialchars($range['label']) ?></p>
                    </div>
                </div>

                <?php require BASE_PATH . '/app/views/owner/reports/_date-filter.php'; ?>

                <?php if ($range['error']): ?>
                    <div class="alert alert-danger"><?= htmlspecialchars($range['error']) ?></div>
                <?php endif; ?>

                <div class="row g-3 mb-4">
                    <div class="col-6 col-xl-3"><div class="owner-stat-card"><i class="bi bi-cash-stack"></i><strong><?= number_format((float) $completedSales['final_revenue'], 0, ',', '.') ?></strong><span>Doanh thu hoàn thành (<?= htmlspecialchars($currency) ?>)</span></div></div>
                    <div class="col-6 col-xl-3"><div class="owner-stat-card"><i class="bi bi-receipt"></i><strong><?= number_format((int) $lifecycle['total_orders']) ?></strong><span>Đơn đặt trong kỳ</span></div></div>
                    <div class="col-6 col-xl-3"><div class="owner-stat-card"><i class="bi bi-check2-circle"></i><strong><?= number_format((int) $completedSales['completed_order_count']) ?></strong><span>Đơn hoàn thành trong kỳ</span></div></div>
                    <div class="col-6 col-xl-3"><div class="owner-stat-card"><i class="bi bi-x-circle"></i><strong><?= number_format((int) $lifecycle['cancelled_order_count']) ?></strong><span>Đơn hủy trong kỳ</span></div></div>
                    <div class="col-6 col-xl-3"><div class="owner-stat-card"><i class="bi bi-calculator"></i><strong><?= number_format((float) $completedSales['average_order_value'], 0, ',', '.') ?></strong><span>Giá trị đơn hoàn thành TB</span></div></div>
                    <div class="col-6 col-xl-3"><div class="owner-stat-card"><i class="bi bi-box-seam"></i><strong><?= number_format($quantitySold) ?></strong><span>Sản phẩm đã bán</span></div></div>
                    <div class="col-6 col-xl-3"><div class="owner-stat-card"><i class="bi bi-people"></i><strong><?= number_format((int) $completedSales['customer_count']) ?></strong><span>Khách có đơn hoàn thành</span></div></div>
                    <div class="col-6 col-xl-3"><div class="owner-stat-card"><i class="bi bi-percent"></i><strong><?= number_format($cancellationRate, 1) ?>%</strong><span>Tỷ lệ hủy theo đơn đặt</span></div></div>
                </div>

                <section class="owner-card mb-4">
                    <div class="owner-card-header"><h2>Giá trị đơn hoàn thành</h2></div>
                    <div class="table-responsive">
                        <table class="table align-middle owner-table mb-0">
                            <thead><tr><th>Trước giảm giá</th><th>Khuyến mãi đã giảm</th><th>Phí vận chuyển</th><th>Doanh thu cuối</th><th>Giá trị đơn hủy</th></tr></thead>
                            <tbody><tr><td><?= number_format((float) $completedSales['subtotal_amount'], 0, ',', '.') ?> <?= htmlspecialchars($currency) ?></td><td><?= number_format((float) $completedSales['discount_amount'], 0, ',', '.') ?> <?= htmlspecialchars($currency) ?></td><td><?= number_format((float) $completedSales['shipping_amount'], 0, ',', '.') ?> <?= htmlspecialchars($currency) ?></td><td><strong><?= number_format((float) $completedSales['final_revenue'], 0, ',', '.') ?> <?= htmlspecialchars($currency) ?></strong></td><td><?= number_format((float) $lifecycle['cancelled_order_value'], 0, ',', '.') ?> <?= htmlspecialchars($currency) ?></td></tr></tbody>
                        </table>
                    </div>
                    <small class="text-muted d-block mt-3">Bốn cột đầu chỉ tính đơn hoàn thành theo thời điểm hoàn thành; giá trị đơn hủy không được tính là doanh thu.</small>
                </section>

                <div class="row g-4 mb-4">
                    <div class="col-xl-6">
                        <section class="owner-card h-100">
                            <div class="owner-card-header"><h2>Doanh thu theo ngày</h2><a href="<?= BASE_URL ?>/?<?= htmlspecialchars(http_build_query(array_merge(['url' => 'owner/reports/export/revenue'], $reportQuery))) ?>">Xuất CSV</a></div>
                            <div class="table-responsive"><table class="table align-middle owner-table"><thead><tr><th>Ngày hoàn thành</th><th>Đơn</th><th>Doanh thu</th></tr></thead><tbody>
                                <?php foreach ($dailyRevenue as $row): ?><tr><td><?= htmlspecialchars($row['report_date']) ?></td><td><?= (int) $row['order_count'] ?></td><td><?= number_format((float) $row['revenue'], 0, ',', '.') ?> <?= htmlspecialchars($currency) ?></td></tr><?php endforeach; ?>
                                <?php if ($dailyRevenue === []): ?><tr><td colspan="3" class="text-center text-muted py-4">Không có đơn hoàn thành.</td></tr><?php endif; ?>
                            </tbody></table></div>
                        </section>
                    </div>
                    <div class="col-xl-6">
                        <section class="owner-card h-100">
                            <div class="owner-card-header"><h2>Doanh thu theo tháng</h2></div>
                            <div class="table-responsive"><table class="table align-middle owner-table"><thead><tr><th>Tháng</th><th>Đơn hoàn thành</th><th>Doanh thu</th></tr></thead><tbody>
                                <?php foreach ($monthlyRevenue as $row): ?><tr><td><?= htmlspecialchars($row['report_month']) ?></td><td><?= (int) $row['completed_order_count'] ?></td><td><?= number_format((float) $row['revenue'], 0, ',', '.') ?> <?= htmlspecialchars($currency) ?></td></tr><?php endforeach; ?>
                                <?php if ($monthlyRevenue === []): ?><tr><td colspan="3" class="text-center text-muted py-4">Không có đơn hoàn thành.</td></tr><?php endif; ?>
                            </tbody></table></div>
                        </section>
                    </div>
                </div>

                <div class="row g-4 mb-4">
                    <div class="col-xl-5">
                        <section class="owner-card h-100">
                            <div class="owner-card-header"><h2>Trạng thái đơn đặt trong kỳ</h2></div>
                            <div class="table-responsive"><table class="table align-middle owner-table"><thead><tr><th>Trạng thái</th><th>Số đơn</th><th>Tỷ lệ</th></tr></thead><tbody>
                                <?php foreach ($statusStats as $stat): ?><tr><td><?= htmlspecialchars($stat['label']) ?></td><td><?= (int) $stat['order_count'] ?></td><td><?= number_format((float) $stat['percentage'], 1) ?>%</td></tr><?php endforeach; ?>
                            </tbody></table></div>
                        </section>
                    </div>
                    <div class="col-xl-7">
                        <section class="owner-card h-100">
                            <div class="owner-card-header"><h2>Sản phẩm bán chạy</h2><a href="<?= BASE_URL ?>/?<?= htmlspecialchars(http_build_query(array_merge(['url' => 'owner/reports/products'], $reportQuery))) ?>">Xem đầy đủ</a></div>
                            <div class="table-responsive"><table class="table align-middle owner-table"><thead><tr><th>Sản phẩm</th><th>Đã bán</th><th>Đơn</th><th>Doanh thu</th></tr></thead><tbody>
                                <?php foreach ($bestSellingProducts as $product): ?><tr><td><strong><?= htmlspecialchars($product['product_name']) ?></strong><small class="d-block text-muted"><?= htmlspecialchars($product['sku'] ?? '') ?></small></td><td><?= (int) $product['quantity_sold'] ?></td><td><?= (int) $product['order_count'] ?></td><td><?= number_format((float) $product['revenue'], 0, ',', '.') ?> <?= htmlspecialchars($currency) ?></td></tr><?php endforeach; ?>
                                <?php if ($bestSellingProducts === []): ?><tr><td colspan="4" class="text-center text-muted py-4">Không có dữ liệu bán hàng.</td></tr><?php endif; ?>
                            </tbody></table></div>
                        </section>
                    </div>
                </div>

                <section class="owner-card mb-4">
                    <div class="owner-card-header"><h2>Hiệu quả danh mục</h2></div>
                    <div class="table-responsive"><table class="table align-middle owner-table"><thead><tr><th>Danh mục hiện tại</th><th>Số lượng bán</th><th>Đơn hoàn thành</th><th>Doanh thu</th></tr></thead><tbody>
                        <?php foreach ($categoryPerformance as $category): ?><tr><td><?= htmlspecialchars($category['category_name']) ?></td><td><?= (int) $category['quantity_sold'] ?></td><td><?= (int) $category['completed_order_count'] ?></td><td><?= number_format((float) $category['revenue'], 0, ',', '.') ?> <?= htmlspecialchars($currency) ?></td></tr><?php endforeach; ?>
                        <?php if ($categoryPerformance === []): ?><tr><td colspan="4" class="text-center text-muted py-4">Không có dữ liệu danh mục.</td></tr><?php endif; ?>
                    </tbody></table></div>
                    <small class="text-muted d-block mt-3">Danh mục được lấy từ sản phẩm hiện tại vì order item chưa lưu snapshot danh mục.</small>
                </section>

            </div>

        </div>

    </div>

</main>

<?php require BASE_PATH . '/app/views/layouts/footer.php'; ?>
