<?php
session_start();

require_once '../../config/database.php';
require_once '../../includes/auth.php';

$db = (new Database())->connect();

$search = trim($_GET['search'] ?? '');
$fromDate = trim($_GET['from_date'] ?? '');
$toDate = trim($_GET['to_date'] ?? '');
$page = max(1, (int)($_GET['page'] ?? 1));

$allowedLimits = [10, 25, 50, 100];
$limit = (int)($_GET['limit'] ?? 10);

if (!in_array($limit, $allowedLimits)) {
    $limit = 10;
}

$offset = ($page - 1) * $limit;

$where = [];
$params = [];

/*
    Only PAID orders
*/
$where[] = "o.status = 'PAID'";

/*
    Search
*/
if (!empty($search)) {
    $where[] = "c.name LIKE ?";
    $params[] = "%$search%";
}

/*
    Date filters
*/
if (!empty($fromDate)) {
    $where[] = "DATE(o.order_date) >= ?";
    $params[] = $fromDate;
}

if (!empty($toDate)) {
    $where[] = "DATE(o.order_date) <= ?";
    $params[] = $toDate;
}

$whereSql = ' WHERE ' . implode(' AND ', $where);

/*
    SUMMARY
*/
$summarySql = "
    SELECT
        COALESCE(SUM(oi.quantity), 0) AS total_qty,
        COALESCE(SUM(oi.quantity * oi.price), 0) AS total_sales,
        COALESCE(SUM(oi.gst), 0) AS total_gst
    FROM categories c
    INNER JOIN items i ON c.id = i.category_id
    INNER JOIN order_items oi ON i.id = oi.item_id
    INNER JOIN orders o ON oi.order_id = o.id
    $whereSql
";

$stmt = $db->prepare($summarySql);
$stmt->execute($params);
$summary = $stmt->fetch(PDO::FETCH_ASSOC);

/*
    COUNT
*/
$countSql = "
    SELECT COUNT(*)
    FROM (
        SELECT c.id
        FROM categories c
        INNER JOIN items i ON c.id = i.category_id
        INNER JOIN order_items oi ON i.id = oi.item_id
        INNER JOIN orders o ON oi.order_id = o.id
        $whereSql
        GROUP BY c.id
    ) x
";

$stmt = $db->prepare($countSql);
$stmt->execute($params);
$totalRecords = $stmt->fetchColumn();

$totalPages = ceil($totalRecords / $limit);

/*
    DATA
*/
$dataSql = "
    SELECT
        c.name AS category_name,
        SUM(oi.quantity) AS qty_sold,
        SUM(oi.quantity * oi.price) AS revenue,
        SUM(oi.gst) AS total_gst,
        COUNT(DISTINCT oi.item_id) AS item_count
    FROM categories c
    INNER JOIN items i ON c.id = i.category_id
    INNER JOIN order_items oi ON i.id = oi.item_id
    INNER JOIN orders o ON oi.order_id = o.id
    $whereSql
    GROUP BY c.id
    ORDER BY revenue DESC
    LIMIT $limit OFFSET $offset
";

$stmt = $db->prepare($dataSql);
$stmt->execute($params);
$categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!-- SUMMARY -->
<div class="row mb-3">

    <div class="col-md-4">
        <div class="card shadow-sm border-primary">
            <div class="card-body">
                <h6>Total Qty Sold</h6>
                <h4><?= number_format((float)$summary['total_qty'], 2) ?></h4>
            </div>
        </div>
    </div>

    <div class="col-md-4">
        <div class="card shadow-sm border-success">
            <div class="card-body">
                <h6>Total Sales</h6>
                <h4>₹ <?= number_format((float)$summary['total_sales'], 2) ?></h4>
            </div>
        </div>
    </div>

    <div class="col-md-4">
        <div class="card shadow-sm border-warning">
            <div class="card-body">
                <h6>Total GST</h6>
                <h4>₹ <?= number_format((float)$summary['total_gst'], 2) ?></h4>
            </div>
        </div>
    </div>

</div>

<!-- TABLE -->
<div class="card shadow-sm">
    <div class="card-body table-responsive">

        <table class="table table-bordered table-hover align-middle">

            <thead class="table-dark">
                <tr>
                    <th>Category</th>
                    <th>Items Sold</th>
                    <th>Total Qty</th>
                    <th>Revenue</th>
                    <th>GST</th>
                </tr>
            </thead>

            <tbody>

            <?php if (empty($categories)): ?>
                <tr>
                    <td colspan="5" class="text-center">
                        No category sales found.
                    </td>
                </tr>
            <?php endif; ?>

            <?php foreach ($categories as $category): ?>
                <tr>
                    <td><?= htmlspecialchars($category['category_name']) ?></td>

                    <td><?= $category['item_count'] ?></td>

                    <td><?= number_format((float)$category['qty_sold'], 2) ?></td>

                    <td>
                        ₹ <?= number_format((float)$category['revenue'], 2) ?>
                    </td>

                    <td>
                        ₹ <?= number_format((float)$category['total_gst'], 2) ?>
                    </td>
                </tr>
            <?php endforeach; ?>

            </tbody>

        </table>

        <!-- PAGINATION -->
        <?php if ($totalPages > 1): ?>
            <nav>
                <ul class="pagination justify-content-center">

                    <?php if ($page > 1): ?>
                        <li class="page-item">
                            <button
                                class="page-link"
                                onclick="loadCategorySales(<?= $page - 1 ?>)"
                            >
                                Previous
                            </button>
                        </li>
                    <?php endif; ?>

                    <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                        <li class="page-item <?= $page == $i ? 'active' : '' ?>">
                            <button
                                class="page-link"
                                onclick="loadCategorySales(<?= $i ?>)"
                            >
                                <?= $i ?>
                            </button>
                        </li>
                    <?php endfor; ?>

                    <?php if ($page < $totalPages): ?>
                        <li class="page-item">
                            <button
                                class="page-link"
                                onclick="loadCategorySales(<?= $page + 1 ?>)"
                            >
                                Next
                            </button>
                        </li>
                    <?php endif; ?>

                </ul>
            </nav>
        <?php endif; ?>

    </div>
</div>