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

$user_role = strtolower($_SESSION['role'] ?? 'guest');
$today = date('Y-m-d');

// Check if exporting all
$export_all = isset($_GET['all']) && $_GET['all']==1;

// GET FILTERS
$from = $_GET['from'] ?? $today;
$to   = $_GET['to'] ?? $today;
$payment_method = $_GET['payment_method'] ?? '';
$search = $_GET['search'] ?? '';
$created_by = $_GET['created_by'] ?? '';

$where = "1"; // default for all sales

if(!$export_all){
    $where = "DATE(s.sale_date) BETWEEN '$from' AND '$to'";

    if(!empty($payment_method)){
        $where .= " AND s.payment_method='$payment_method'";
    }

    if(!empty($search)){
        $search_safe = $conn->real_escape_string($search);
        $where .= " AND (
            s.id LIKE '%$search_safe%' OR
            c.name LIKE '%$search_safe%'
        )";
    }

    if(!empty($created_by) && $user_role=='admin'){
        $created_by_safe = $conn->real_escape_string($created_by);
        $where .= " AND s.created_by='$created_by_safe'";
    }
}

// FETCH SALES
$sales = $conn->query("
    SELECT s.*, c.name AS customer_name
    FROM sales s
    LEFT JOIN customers c ON s.customer_id=c.id
    WHERE $where AND s.rest = 0
    ORDER BY s.id DESC
");

// OUTPUT CSV
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=bar_sales_'.date('Ymd_His').'.csv');

$output = fopen('php://output', 'w');

// HEADER ROW
$header = ['#', 'Date', 'Customer', 'Payment', 'Total (MK)'];
if($user_role=='admin') $header[] = 'Created By';
fputcsv($output, $header);

// DATA ROWS
$i = 1;
while($row = $sales->fetch_assoc()){
    $line = [
        $i++,
        $row['sale_date'],
        $row['customer_name'] ?? 'Walk-in',
        $row['payment_method'],
        number_format($row['total'],2)
    ];
    if($user_role=='admin') $line[] = $row['created_by'];
    fputcsv($output, $line);
}

fclose($output);
exit;