<?php
session_start();
if (!isset($_SESSION['admin_loggedin']) || $_SESSION['admin_loggedin'] !== true) {
    header("Location: admin_login.php");
    exit;
}

include "db.php";

$office = mysqli_real_escape_string($conn, $_GET['office']);
$period = $_GET['period'];

// Decide date range based on period
if ($period == "weekly") {
    $query = "SELECT * FROM sales WHERE office_name='$office' AND WEEK(date) = WEEK(CURDATE()) AND YEAR(date) = YEAR(CURDATE())";
} elseif ($period == "monthly") {
    $query = "SELECT * FROM sales WHERE office_name='$office' AND MONTH(date) = MONTH(CURDATE()) AND YEAR(date) = YEAR(CURDATE())";
} else {
    die("Invalid period");
}

$result = mysqli_query($conn, $query);
?>

<!DOCTYPE html>
<html>
<head>
    <title><?= ucfirst($period) ?> Report - <?= htmlspecialchars($office) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="p-4">
<div class="container">
    <h2><?= ucfirst($period) ?> Report for <?= htmlspecialchars($office) ?></h2>
    <a href="admin_dashboard.php" class="btn btn-secondary mb-3">Back to Dashboard</a>
    
    <table class="table table-bordered table-striped">
        <thead>
            <tr>
                <th>Date</th>
                <th>Staff ID</th>
                <th>Item</th>
                <th>Description</th>
                <th>Amount Payable</th>
                <th>Amount Paid</th>
                <th>Balance</th>
                <th>Customer</th>
            </tr>
        </thead>
        <tbody>
        <?php while ($row = mysqli_fetch_assoc($result)) { ?>
            <tr>
                <td><?= htmlspecialchars($row['date']) ?></td>
                <td><?= htmlspecialchars($row['staff_id']) ?></td>
                <td><?= htmlspecialchars($row['item_name']) ?></td>
                <td><?= htmlspecialchars($row['description']) ?></td>
                <td><?= htmlspecialchars($row['amount_payable']) ?></td>
                <td><?= htmlspecialchars($row['amount_paid']) ?></td>
                <td><?= htmlspecialchars($row['balance']) ?></td>
                <td><?= htmlspecialchars($row['customer_name']) ?></td>
            </tr>
        <?php } ?>
        </tbody>
    </table>
</div>
</body>
</html>
