<?php
include 'includes/auth.php';
include 'db.php';

// ================= GET FILTERS =================
$from_date   = $_GET['from'] ?? '';
$to_date     = $_GET['to'] ?? '';
$type        = $_GET['type'] ?? '';
$min_amount  = $_GET['min_amount'] ?? '';
$max_amount  = $_GET['max_amount'] ?? '';

$where = [];
if($from_date) $where[] = "DATE(payment_date) >= '".$conn->real_escape_string($from_date)."'";
if($to_date)   $where[] = "DATE(payment_date) <= '".$conn->real_escape_string($to_date)."'";
if($type)      $where[] = "type = '".$conn->real_escape_string($type)."'";
if($min_amount !== '') $where[] = "amount >= ".floatval($min_amount);
if($max_amount !== '') $where[] = "amount <= ".floatval($max_amount);

$where_sql = $where ? "WHERE ".implode(" AND ", $where) : "";

// ================= FETCH DATA =================
$audit = $conn->query("
    SELECT 
        DATE(payment_date) AS date, 
        SUM(amount) AS total_income,
        SUM(CASE WHEN type='Cash' THEN amount ELSE 0 END) AS cash_total,
        SUM(CASE WHEN type='Card' THEN amount ELSE 0 END) AS card_total
    FROM payments
    $where_sql
    GROUP BY DATE(payment_date)
    ORDER BY date DESC
");

// ================= SEND HEADERS =================
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=night_audit.csv');

$output = fopen('php://output', 'w');
fputcsv($output, ['Date','Total Income (MK)','Cash (MK)','Card (MK)']);

while($row = $audit->fetch_assoc()){
    fputcsv($output, [
        $row['date'],
        number_format($row['total_income'],2),
        number_format($row['cash_total'],2),
        number_format($row['card_total'],2)
    ]);
}

fclose($output);
exit;