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

include 'db_connect.php';

date_default_timezone_set('Africa/Nairobi');
$page_title = "Sales Report | Admin";

// -------------------------
// 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;

// bring in global head / theme / sidebar styles
include('head.php');
?>

<body>

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

<!-- MAIN WRAPPER (same pattern as other admin pages) -->
<div class="content-wrapper" id="content-wrapper">

    <!-- TOP BAR (SHARED FORMAT) -->
    <div class="topbar">
        <div class="topbar-left">
            <span class="menu-btn" onclick="toggleAdminSidebar()">☰</span>
            <span class="topbar-title">Admin Panel</span>
        </div>
        <div class="topbar-right">
            <button class="theme-toggle" type="button" onclick="toggleAdminTheme()">
                🌓 Theme
            </button>
            <span class="topbar-user">
                Logged in as
                <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Admin'); ?></strong>
            </span>
        </div>
    </div>

    <!-- PAGE BODY -->
    <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>Receipt #</th>
                        <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'] * (float)$row['quantity']) - $discount;
                        $profit   = $total - ((float)$row['buying_price'] * (float)$row['quantity']);

                        $page_total_sales  += $total;
                        $page_total_profit += $profit;
                    ?>
                    <tr>
                        <td><?= htmlspecialchars($row['receipt_id']) ?></td>
                        <td><?= htmlspecialchars($row['sale_datetime']) ?></td>
                        <td><?= htmlspecialchars($row['cashier']) ?></td>
                        <td><?= htmlspecialchars($row['product_name']) ?></td>
                        <td class="numeric"><?= (float)$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="10">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>

    <?php include 'footer.php'; ?>

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

<style>
    /* --------- Layout with sidebar --------- */
    .content-wrapper {
        margin-left: 250px;
        padding: 24px 26px;
        background:
            radial-gradient(circle at top left, rgba(0,255,239,0.08), transparent 55%),
            var(--bg-main, #001f3f);
        min-height: 100vh;
        box-sizing: border-box;
        transition: margin-left 0.3s ease, background 0.3s ease;
        display: flex;
        flex-direction: column;
    }

    /* When sidebar is hidden, take full width */
    .content-wrapper.fullwidth {
        margin-left: 0;
    }

    /* Ensure hidden sidebar really disappears */
    #sidebar.hidden {
        display: none;
    }

    /* TOPBAR – same look as other pages */
    .topbar {
        background: var(--bg-sidebar);
        padding: 14px 18px;
        margin-bottom: 20px;
        border-radius: 12px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border: 1px solid #B8860B;
        box-shadow: 0 6px 18px rgba(0,0,0,0.5);
        color: brown;
    }

    .topbar-left {
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .topbar-right {
        display: flex;
        align-items: center;
        gap: 10px;
        font-size: 13px;
    }

    .topbar-title {
        font-weight: 600;
        font-size: 15px;
        letter-spacing: 0.03em;
    }

    .menu-btn {
        font-size: 22px;
        cursor: pointer;
        color: var(--accent-gold, #f4b400);
        transition: 0.3s;
        line-height: 1;
    }

    .menu-btn:hover {
        color: #e6c34b;
    }

    .theme-toggle {
        border-radius: 999px;
        border: 1px solid rgba(184,134,11,0.7);
        padding: 6px 12px;
        background: rgba(0,0,0,0.4);
        color: #f9f9f9;
        font-size: 12px;
        cursor: pointer;
    }

    .theme-toggle:hover {
        background: rgba(0,0,0,0.65);
    }

    .topbar-user strong {
        font-weight: 600;
    }

    @media (max-width: 900px) {
        .content-wrapper {
            margin-left: 0;
            padding: 18px 14px;
        }
        .topbar {
            flex-direction: column;
            align-items: flex-start;
            gap: 8px;
        }
    }

    /* --------- Page header, filters, table, totals --------- */
    .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;
    }

    .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;
    }

    .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 {
        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 {
        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-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 centered at bottom of content area */
    footer {
        background: transparent;
        text-align: center;
        margin-top: 24px;
    }
</style>

<script>
// Sidebar toggle – hide sidebar completely and expand content
function toggleAdminSidebar() {
    const sidebar = document.getElementById('sidebar');
    const wrapper = document.getElementById('content-wrapper');
    if (!sidebar || !wrapper) return;

    const isHidden = sidebar.classList.toggle('hidden');
    if (isHidden) {
        wrapper.classList.add('fullwidth');
    } else {
        wrapper.classList.remove('fullwidth');
    }
}
</script>

</body>
</html>
