<?php
session_start();
include "admin_header.php";
include "db.php";

if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: admin_login.php");
    exit();
}

// Date range defaults to current week
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-d', strtotime('monday this week'));
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d', strtotime('sunday this week'));
$office_filter = isset($_GET['office_name']) ? $_GET['office_name'] : "";
$search = isset($_GET['search']) ? trim($_GET['search']) : "";

// Get offices for dropdown
$offices = mysqli_query($conn, "SELECT DISTINCT office_name FROM sales ORDER BY office_name ASC");

// Build query
$query = "SELECT * FROM sales WHERE sale_date BETWEEN '$start_date' AND '$end_date'";

if (!empty($office_filter)) {
    $query .= " AND office_name = '" . mysqli_real_escape_string($conn, $office_filter) . "'";
}

if (!empty($search)) {
    $safe_search = mysqli_real_escape_string($conn, $search);
    $query .= " AND (customer_name LIKE '%$safe_search%' OR item_name LIKE '%$safe_search%')";
}

$query .= " ORDER BY sale_date DESC";
$result = mysqli_query($conn, $query);

// Totals
$total_payable = $total_paid = $total_balance = 0;
?>
<!DOCTYPE html>
<html>
<head>
    <title>Admin - Weekly Sales Report</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="container mt-4">
<h2 class="mb-3">Admin - Weekly Sales Report</h2>
<a href="admin_dashboard.php" class="btn btn-secondary btn-sm" >Back to Dashboard</a>
<br>
<br>
<!-- Filter Form -->
<form method="GET" class="mb-3 row g-2 align-items-center">
   
   <div class="col-md-3 col-12">
	<label>Select office</label>
        <select name="office_name" class="form-select">
            <option value="">-- All Offices --</option>
            <?php while ($row = mysqli_fetch_assoc($offices)): ?>
                <option value="<?php echo $row['office_name']; ?>" <?php if ($office_filter == $row['office_name']) echo "selected"; ?>>
                    <?php echo $row['office_name']; ?>
                </option>
            <?php endwhile; ?>
        </select>
    </div>
	
   <div class="col-md-3 col-12">
            <label>Start Date:</label>
            <input type="date" name="start_date" value="<?= htmlspecialchars($start_date) ?>" required class="form-control">
        </div>
    <div class="col-md-3 col-12">
            <label>End Date:</label>
            <input type="date" name="end_date" value="<?= htmlspecialchars($end_date) ?>" required class="form-control">
        </div>
    
    <div class="col-md-3 col-12">
	<label>
	   </label>
        <input type="search" name="search" class="form-control" placeholder="Search by Customer or Item" value="<?php echo htmlspecialchars($search); ?>">
    </div>

    <div class="col-md-3 col-12">
		<label></label>
                <button type="submit" class="btn btn-primary w-100">Filter</button>
           
            </div>
</form>


<!-- Export Button for Weekly Report -->
<form method="POST" action="export_sales.php" class="mb-3">
    <input type="hidden" name="report_type" value="weekly">
    <input type="hidden" name="start_date" value="<?php echo $start_date; ?>">
    <input type="hidden" name="end_date" value="<?php echo $end_date; ?>">
    <input type="hidden" name="office_name" value="<?php echo $office_filter; ?>">
    <input type="hidden" name="search" value="<?php echo htmlspecialchars($search); ?>">
    <button type="submit" class="btn btn-success">Export CSV</button>
</form>


</form>

<!-- Table -->
<div class="table-responsive">
<table class="table table-bordered table-striped">
    <thead class="table-dark">
        <tr>
            <th>Date</th>
            <th>Customer</th>
            <th>Item</th>
            <th>Description</th>
            <th>Amount Payable</th>
            <th>Amount Paid</th>
            <th>Balance</th>
        </tr>
    </thead>
    <tbody>
        <?php if (mysqli_num_rows($result) > 0): ?>
            <?php while ($row = mysqli_fetch_assoc($result)): 
                $total_payable += $row['amount_payable'];
                $total_paid += $row['amount_paid'];
                $total_balance += $row['balance'];
            ?>
                <tr>
                     <td><?= htmlspecialchars(date("d M Y", strtotime($row['sale_date']))) ?></td>
                    <td><?php echo $row['customer_name']; ?></td>
                    <td><?php echo $row['item_name']; ?></td>
                    <td><?php echo $row['description']; ?></td>
                    <td><?php echo number_format($row['amount_payable'], 2); ?></td>
                    <td><?php echo number_format($row['amount_paid'], 2); ?></td>
                    <td><?php echo number_format($row['balance'], 2); ?></td>
                </tr>
            <?php endwhile; ?>
            <tr class="fw-bold table-secondary">
                <td colspan="4" class="text-end">TOTAL</td>
                <td><?php echo number_format($total_payable, 2); ?></td>
                <td><?php echo number_format($total_paid, 2); ?></td>
                <td><?php echo number_format($total_balance, 2); ?></td>
            </tr>
        <?php else: ?>
            <tr><td colspan="7" class="text-center">No sales found for this period.</td></tr>
        <?php endif; ?>
    </tbody>
</table>
</div>

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