<?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 = [];

$where[] = "o.status = 'PAID'";

/*
    Search
*/
if (!empty($search)) {
    $where[] = "i.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 * oi.price), 0) AS taxable_sales,
        COALESCE(SUM(oi.gst), 0) AS total_gst
    FROM order_items oi
    INNER JOIN items i ON oi.item_id = i.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 oi.item_id
        FROM order_items oi
        INNER JOIN items i ON oi.item_id = i.id
        INNER JOIN orders o ON oi.order_id = o.id
        $whereSql
        GROUP BY oi.item_id
    ) x
";

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

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

/*
    DATA
*/
$dataSql = "
    SELECT
        i.name,
        SUM(oi.quantity) AS qty_sold,
        AVG(oi.price) AS avg_price,
        SUM(oi.quantity * oi.price) AS taxable_amount,
        SUM(oi.gst) AS gst_amount
    FROM order_items oi
    INNER JOIN items i ON oi.item_id = i.id
    INNER JOIN orders o ON oi.order_id = o.id
    $whereSql
    GROUP BY oi.item_id
    ORDER BY gst_amount DESC
    LIMIT $limit OFFSET $offset
";

$stmt = $db->prepare($dataSql);
$stmt->execute($params);

$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

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

    <div class="col-md-6">
        <div class="card shadow-sm border-primary">
            <div class="card-body">
                <h6>Taxable Sales</h6>
                <h4>
                    ₹ <?= number_format((float)$summary['taxable_sales'], 2) ?>
                </h4>
            </div>
        </div>
    </div>

    <div class="col-md-6">
        <div class="card shadow-sm border-warning">
            <div class="card-body">
                <h6>Total GST Collected</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>Item</th>
                    <th>Qty Sold</th>
                    <th>Avg Price</th>
                    <th>Taxable Amount</th>
                    <th>GST Amount</th>
                </tr>
            </thead>

            <tbody>

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

            <?php foreach ($rows as $row): ?>
                <tr>
                    <td><?= htmlspecialchars($row['name']) ?></td>

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

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

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

                    <td>
                        ₹ <?= number_format((float)$row['gst_amount'], 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="loadGSTReport(<?= $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="loadGSTReport(<?= $i ?>)"
                            >
                                <?= $i ?>
                            </button>
                        </li>
                    <?php endfor; ?>

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

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

    </div>
</div>