<?php
session_start();

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

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

$search = trim($_GET['search'] ?? '');
$reportDate = trim($_GET['report_date'] ?? '');
$status = trim($_GET['status'] ?? '');
$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 = [];

/*
    Order ID search
*/
if (!empty($search) && is_numeric($search)) {
    $where[] = "id = ?";
    $params[] = (int)$search;
}

/*
    Date filter
*/
if (!empty($reportDate)) {
    $where[] = "DATE(order_date) = ?";
    $params[] = $reportDate;
}

/*
    Status filter
*/
if (!empty($status)) {
    $where[] = "status = ?";
    $params[] = $status;
}

$whereSql = '';

if (!empty($where)) {
    $whereSql = ' WHERE ' . implode(' AND ', $where);
}

/*
    SUMMARY
*/
$summarySql = "
    SELECT
        COUNT(*) AS total_orders,
        COALESCE(SUM(total), 0) AS total_sales,
        COALESCE(SUM(gst), 0) AS total_gst
    FROM orders
    $whereSql
";

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

/*
    COUNT
*/
$countSql = "
    SELECT COUNT(*)
    FROM orders
    $whereSql
";

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

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

/*
    DATA
*/
$dataSql = "
    SELECT *
    FROM orders
    $whereSql
    ORDER BY order_date DESC
    LIMIT $limit OFFSET $offset
";

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

$orders = $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 Orders</h6>
                <h4><?= $summary['total_orders'] ?></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>Order ID</th>
                    <th>Order Date</th>
                    <th>Total</th>
                    <th>GST</th>
                    <th>Status</th>
                    <th width="260">Actions</th>
                </tr>
            </thead>

            <tbody>

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

            <?php foreach ($orders as $order): ?>

                <?php
                $badgeClass = match ($order['status']) {
                    'PAID' => 'bg-success',
                    'CANCELLED' => 'bg-danger',
                    default => 'bg-secondary'
                };
                ?>

                <tr>
                    <td>#<?= $order['id'] ?></td>

                    <td>
                        <?= date(
                            'd-m-Y h:i A',
                            strtotime($order['order_date'])
                        ) ?>
                    </td>

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

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

                    <td>
                        <span class="badge <?= $badgeClass ?>">
                            <?= htmlspecialchars($order['status']) ?>
                        </span>
                    </td>

                    <td>
                        <a
                            href="../invoices/view_invoice.php?id=<?= $order['id'] ?>"
                            class="btn btn-sm btn-info"
                        >
                            View
                        </a>

                        <a
                            href="../invoices/print_invoice.php?id=<?= $order['id'] ?>"
                            target="_blank"
                            class="btn btn-sm btn-primary"
                        >
                            Print
                        </a>

                        <a
                            href="../invoices/export_pdf.php?id=<?= $order['id'] ?>"
                            target="_blank"
                            class="btn btn-sm btn-danger"
                        >
                            PDF
                        </a>
                    </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="loadDailySales(<?= $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="loadDailySales(<?= $i ?>)"
                            >
                                <?= $i ?>
                            </button>
                        </li>
                    <?php endfor; ?>

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

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

    </div>
</div>