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

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

$report_type = $_POST['report_type'] ?? "daily";

// Base query
$query = "SELECT sale_date, office_name, customer_name, item_name, description, amount_payable, amount_paid, balance FROM sales WHERE 1=1";
$params = [];
$types  = "";

// Daily report
if ($report_type === "daily") {
    $sale_date = $_POST['sale_date'] ?? date('Y-m-d');
    $query .= " AND sale_date = ?";
    $params[] = $sale_date;
    $types   .= "s";
}
// Weekly report
elseif ($report_type === "weekly") {
    $start_date = $_POST['start_date'] ?? date('Y-m-d', strtotime('monday this week'));
    $end_date   = $_POST['end_date'] ?? date('Y-m-d', strtotime('sunday this week'));
    $query .= " AND sale_date BETWEEN ? AND ?";
    $params[] = $start_date;
    $params[] = $end_date;
    $types   .= "ss";
}
// Monthly report
elseif ($report_type === "monthly") {
    $month = $_POST['month'] ?? date('Y-m');
    $query .= " AND DATE_FORMAT(sale_date, '%Y-%m') = ?";
    $params[] = $month;
    $types   .= "s";
}

// Optional office filter
if (!empty($_POST['office_name'])) {
    $query .= " AND office_name = ?";
    $params[] = $_POST['office_name'];
    $types   .= "s";
}

// Optional search filter
if (!empty($_POST['search'])) {
    $search = "%" . $_POST['search'] . "%";
    $query .= " AND (customer_name LIKE ? OR item_name LIKE ? OR description LIKE ?)";
    $params[] = $search;
    $params[] = $search;
    $params[] = $search;
    $types   .= "sss";
}

$query .= " ORDER BY sale_date ASC";

// Prepare & execute
$stmt = $conn->prepare($query);
if ($types) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();

// CSV headers
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=admin_sales_report.csv");

// Output CSV
$output = fopen("php://output", "w");
fputcsv($output, ["Date", "Office", "Customer", "Item", "Description", "Amount Payable", "Amount Paid", "Balance"]);

// Track totals
$total_payable = 0;
$total_paid    = 0;
$total_balance = 0;

while ($row = $result->fetch_assoc()) {
    fputcsv($output, [
        $row['sale_date'],
        $row['office_name'],
        $row['customer_name'],
        $row['item_name'],
        $row['description'],
        $row['amount_payable'],
        $row['amount_paid'],
        $row['balance']
    ]);

    $total_payable += $row['amount_payable'];
    $total_paid    += $row['amount_paid'];
    $total_balance += $row['balance'];
}

// Add totals row
if ($result->num_rows > 0) {
    fputcsv($output, ["", "", "", "", "TOTAL", $total_payable, $total_paid, $total_balance]);
}

fclose($output);
exit;
