<?php
session_start();
if (!isset($_SESSION['username']) || ($_SESSION['role'] ?? '') !== 'admin') {
    header("Location: login.html?error=unauthorized");
    exit();
}

include 'db_connect.php';

// -------------------------
// Date filter
// -------------------------
$today = date('Y-m-d');

$from_date = isset($_GET['from_date']) && $_GET['from_date'] !== ''
    ? $_GET['from_date']
    : $today;
$to_date = isset($_GET['to_date']) && $_GET['to_date'] !== ''
    ? $_GET['to_date']
    : $today;

// basic safety – very simple Y-m-d check
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $from_date)) {
    $from_date = $today;
}
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $to_date)) {
    $to_date = $today;
}

// WHERE clause for all sales queries (filtered by date range)
$where_sql = "WHERE DATE(s.sale_datetime) BETWEEN '$from_date' AND '$to_date'";

// -------------------------
// Pagination
// -------------------------
$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
if ($limit <= 0) $limit = 10;

$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$page = max(1, $page);
$offset = ($page - 1) * $limit;

// Count total rows in range
$count_sql = "
    SELECT COUNT(*) AS total
    FROM sales s
    $where_sql
";
$countResult = $conn->query($count_sql);

$totalRows = 0;
if ($countResult) {
    $countRow  = $countResult->fetch_assoc();
    $totalRows = (int)($countRow['total'] ?? 0);
}

$totalPages = $limit > 0 ? max(1, ceil($totalRows / $limit)) : 1;
if ($page > $totalPages) {
    $page   = $totalPages;
    $offset = ($page - 1) * $limit;
}

// -------------------------
// Fetch paginated sales
// -------------------------
$sql = "
    SELECT s.*, p.name AS product_name
    FROM sales s
    JOIN products p ON s.product_id = p.id
    $where_sql
    ORDER BY s.sale_datetime DESC
    LIMIT $limit OFFSET $offset
";
$result = $conn->query($sql);

// -------------------------
// Grand totals (for the same date range)
// -------------------------
$grand_sql = "
    SELECT 
        SUM(selling_price * quantity - discount) AS grand_total_sales,
        SUM((selling_price * quantity - discount) - (buying_price * quantity)) AS grand_total_profit
    FROM sales s
    $where_sql
";
$grandQuery = $conn->query($grand_sql);

$grand_total_sales  = 0;
$grand_total_profit = 0;
if ($grandQuery) {
    $grand = $grandQuery->fetch_assoc();
    if ($grand) {
        $grand_total_sales  = (float)($grand['grand_total_sales']  ?? 0);
        $grand_total_profit = (float)($grand['grand_total_profit'] ?? 0);
    }
}

$page_total_sales  = 0;
$page_total_profit = 0;

$page_title = "Sales Report | Admin";
?>
<!DOCTYPE html>
<html>
<head>
    <title><?= htmlspecialchars($page_title) ?></title>
    <?php include('head.php'); ?>

    <style>
        body {
            font-family: 'Poppins', Arial, sans-serif;
            background: var(--bg-main);
            margin: 0;
            color: var(--text-main);
        }

        .content-area {
            margin-left: 260px;
            padding: 25px 30px;
        }

        @media (max-width: 768px) {
            .content-area {
                margin-left: 80px;
                padding: 20px;
            }
        }

        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-end;
            flex-wrap: wrap;
            gap: 10px;
            margin-bottom: 18px;
        }

        .page-title {
            font-size: 22px;
            font-weight: 600;
            color: var(--text-heading);
        }

        .page-subtitle {
            font-size: 13px;
            color: #f4b400;
            margin-top: 4px;
        }

        /* Filter + show X form */
        .filters {
            font-size: 13px;
            color: var(--text-main);
        }

        .filters form {
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            align-items: center;
        }

        .filters label {
            display: flex;
            align-items: center;
            gap: 4px;
        }

        .filters input[type="date"],
        .filters select {
            padding: 6px 10px;
            border-radius: 6px;
            border: 1px solid #0a4a85;
            background: #01356f;
            color: #ffffff;
            font-size: 13px;
        }

        .filters input[type="date"]:focus,
        .filters select:focus {
            outline: none;
            background: #014b94;
            border-color: #f4b400;
        }

        .filters button {
            padding: 7px 12px;
            border-radius: 6px;
            border: none;
            cursor: pointer;
            font-size: 13px;
            font-weight: 600;
            background: #f4b400;
            color: #111827;
        }

        body[data-theme="light"] .filters input[type="date"],
        body[data-theme="light"] .filters select {
            background: #ffffff;
            color: #111827;
            border-color: #cbd5f5;
        }

        body[data-theme="light"] .filters input[type="date"]:focus,
        body[data-theme="light"] .filters select:focus {
            background: #f9fafb;
            border-color: #facc15;
        }

        /* Card around table */
        .page-card {
            background: var(--bg-card);
            border-radius: 14px;
            padding: 18px 22px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.35);
            border: 1px solid #0a4a85;
            color: var(--text-main);
        }

        body[data-theme="light"] .page-card {
            box-shadow: 0 12px 30px rgba(15,23,42,0.12);
            border-color: rgba(148,163,184,0.55);
        }

        .page-card-title {
            font-size: 16px;
            font-weight: 500;
            margin-bottom: 10px;
            color: var(--text-heading);
        }

        /* Table wrapper */
        .table-wrapper {
            width: 100%;
            overflow-x: auto;
            margin-top: 6px;
        }

        table {
            width: 100%;
            min-width: 1200px;
            border-collapse: collapse;
            background: var(--bg-card);
            color: var(--text-main);
            border-radius: 10px;
        }

        thead tr {
            background: var(--bg-table-head);
        }

        th,
        td {
            padding: 10px 12px;
            border: 1px solid rgba(255,255,255,0.15);
            text-align: center;
            font-size: 13px;
            white-space: nowrap;
        }

        th {
            color: #ffffff;
            font-weight: 600;
        }

        tbody tr {
            background: var(--bg-table-row);
        }

        tbody tr:nth-child(even) {
            background: var(--bg-table-row);
        }

        tbody tr:hover {
            background: var(--bg-table-hover);
            color: #ffffff;
        }

        body[data-theme="light"] th {
            color: #111827;
            border-color: rgba(148,163,184,0.5);
        }

        body[data-theme="light"] td {
            border-color: rgba(148,163,184,0.35);
        }

        body[data-theme="light"] tbody tr {
            background: var(--bg-table-row);
        }

        body[data-theme="light"] tbody tr:nth-child(even) {
            background: var(--bg-table-row);
        }

        body[data-theme="light"] tbody tr:hover {
            background: var(--bg-table-hover);
            color: #111827;
        }

        .numeric {
            text-align: right;
        }

        /* Pagination */
        .pagination {
            text-align: center;
            margin-top: 18px;
        }

        .page-btn {
            padding: 7px 12px;
            margin: 3px;
            background: #012a57;
            color: white;
            border-radius: 4px;
            text-decoration: none;
            border: 1px solid #0a4a85;
            font-size: 13px;
        }

        .page-btn.active {
            background: #5a47f5;
            border-color: #5a47f5;
            font-weight: 700;
        }

        .page-btn:hover {
            background: #014b94;
            border-color: #014b94;
        }

        body[data-theme="light"] .page-btn {
            background: #e5e7eb;
            color: #111827;
            border-color: #cbd5f5;
        }

        body[data-theme="light"] .page-btn.active {
            background: #facc15;
            border-color: #d4a017;
            color: #111827;
        }

        body[data-theme="light"] .page-btn:hover {
            background: #d1d5db;
            border-color: #9ca3af;
        }

        /* Totals */
        .totals-box {
            margin-top: 20px;
            text-align: right;
            font-weight: 600;
            font-size: 14px;
            color: var(--text-main);
        }

        .totals-box span.label {
            color: var(--text-main);
        }

        .totals-box span.value {
            color: #f4b400;
        }

        .grand-totals-box {
            margin-top: 16px;
            padding: 12px 16px;
            background: var(--bg-card);
            border-left: 6px solid #f4b400;
            border-radius: 10px;
            text-align: right;
            font-weight: 600;
            font-size: 14px;
            box-shadow: 0 4px 10px rgba(0,0,0,0.3);
            color: var(--text-main);
        }

        body[data-theme="light"] .grand-totals-box {
            box-shadow: 0 10px 24px rgba(15,23,42,0.12);
            border-color: #facc15;
        }

        .grand-totals-box span.label {
            color: var(--text-main);
        }

        .grand-totals-box span.value {
            color: #f4b400;
        }

        footer {
            background: transparent;
        }
    </style>
</head>

<body>

<?php include("sidebar.php"); ?>

<div class="content-area">

    <div class="page-header">
        <div>
            <div class="page-title">Sales Report</div>
            <div class="page-subtitle">
                Showing sales from
                <?= htmlspecialchars($from_date) ?> to <?= htmlspecialchars($to_date) ?> —
                page <?= $page ?> of <?= $totalPages ?> (<?= $limit ?> per page)
            </div>
        </div>

        <div class="filters">
            <form method="GET">
                <label>
                    From
                    <input type="date" name="from_date" value="<?= htmlspecialchars($from_date) ?>">
                </label>
                <label>
                    To
                    <input type="date" name="to_date" value="<?= htmlspecialchars($to_date) ?>">
                </label>
                <label>
                    Show
                    <select name="limit">
                        <option value="10"  <?= $limit == 10  ? 'selected' : '' ?>>10</option>
                        <option value="25"  <?= $limit == 25  ? 'selected' : '' ?>>25</option>
                        <option value="50"  <?= $limit == 50  ? 'selected' : '' ?>>50</option>
                        <option value="100" <?= $limit == 100 ? 'selected' : '' ?>>100</option>
                    </select>
                    entries
                </label>
                <button type="submit">Filter</button>
            </form>
        </div>
    </div>

    <div class="page-card">
        <div class="page-card-title">Sales Detail</div>

        <div class="table-wrapper">
            <table>
                <thead>
                    <tr>
                        <th>Date and Time</th>
                        <th>Cashier</th>
                        <th>Product</th>
                        <th>Quantity Sold</th>
                        <th>Buying Price (KES)</th>
                        <th>Selling Price (KES)</th>
                        <th>Discount (KES)</th>
                        <th>Total Sale (KES)</th>
                        <th>Profit (KES)</th>
                    </tr>
                </thead>
                <tbody>
                <?php if ($result && $result->num_rows > 0): ?>
                    <?php while ($row = $result->fetch_assoc()):
                        $discount = (float)($row['discount'] ?? 0);
                        $total    = ((float)$row['selling_price'] * (int)$row['quantity']) - $discount;
                        $profit   = $total - ((float)$row['buying_price'] * (int)$row['quantity']);

                        $page_total_sales  += $total;
                        $page_total_profit += $profit;
                    ?>
                    <tr>
                        <td><?= htmlspecialchars($row['sale_datetime']) ?></td>
                        <td><?= htmlspecialchars($row['cashier']) ?></td>
                        <td><?= htmlspecialchars($row['product_name']) ?></td>
                        <td class="numeric"><?= (int)$row['quantity'] ?></td>
                        <td class="numeric"><?= number_format((float)$row['buying_price'], 2) ?></td>
                        <td class="numeric"><?= number_format((float)$row['selling_price'], 2) ?></td>
                        <td class="numeric"><?= number_format($discount, 2) ?></td>
                        <td class="numeric"><?= number_format($total, 2) ?></td>
                        <td class="numeric"><?= number_format($profit, 2) ?></td>
                    </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="9">No sales found in this period.</td>
                    </tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <?php if ($totalPages > 1): ?>
            <div class="pagination">
                <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                    <a class="page-btn <?= ($i == $page) ? 'active' : '' ?>"
                       href="?page=<?= $i ?>&limit=<?= $limit ?>&from_date=<?= urlencode($from_date) ?>&to_date=<?= urlencode($to_date) ?>">
                        <?= $i ?>
                    </a>
                <?php endfor; ?>
            </div>
        <?php endif; ?>
    </div>

    <!-- Page totals -->
    <div class="totals-box">
        <div>
            <span class="label">Page Total Sales:</span>
            <span class="value">KES <?= number_format($page_total_sales, 2) ?></span>
        </div>
        <div>
            <span class="label">Page Total Profit:</span>
            <span class="value">KES <?= number_format($page_total_profit, 2) ?></span>
        </div>
    </div>

    <!-- Grand totals for filtered period -->
    <div class="grand-totals-box">
        <div>
            <span class="label">Total Sales (<?= htmlspecialchars($from_date) ?> – <?= htmlspecialchars($to_date) ?>):</span>
            <span class="value">KES <?= number_format($grand_total_sales, 2) ?></span>
        </div>
        <div>
            <span class="label">Total Profit (<?= htmlspecialchars($from_date) ?> – <?= htmlspecialchars($to_date) ?>):</span>
            <span class="value">KES <?= number_format($grand_total_profit, 2) ?></span>
        </div>
    </div>

</div> <!-- end content-area -->

<?php include 'footer.php'; ?>
</body>
</html>
