<?php
include 'db.php';

// ================= DEFAULT TODAY =================
$today = date('Y-m-d');

$from_date = $_GET['from'] ?? $today;
$to_date   = $_GET['to'] ?? $today;
$method    = $_GET['method'] ?? '';
$outlet    = $_GET['outlet'] ?? '';
$search    = $_GET['search'] ?? '';

// ================= BUILD WHERE =================
$where = [];

if($from_date){
    $where[] = "DATE(sales_date) >= '".$conn->real_escape_string($from_date)."'";
}

if($to_date){
    $where[] = "DATE(sales_date) <= '".$conn->real_escape_string($to_date)."'";
}

if($method){
    $where[] = "payment_method = '".$conn->real_escape_string($method)."'";
}

if($outlet !== ''){
    $where[] = "rest = '".$conn->real_escape_string($outlet)."'";
}

if($search){
    $s = $conn->real_escape_string($search);
    $where[] = "(customer_id LIKE '%$s%' OR created_by LIKE '%$s%')";
}

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

// ================= FETCH SALES =================
$data = $conn->query("SELECT * FROM sales $where_sql ORDER BY sales_date DESC");

// ================= EXPORT HEADERS =================
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=sales_report_{$from_date}_to_{$to_date}.xls");

echo "<table border='1'>";
echo "<tr>
<th>Date</th>
<th>Outlet</th>
<th>Payment Method</th>
<th>Customer</th>
<th>Served By</th>
<th>Total</th>
<th>VAT</th>
<th>Discount</th>
</tr>";

if($data && $data->num_rows > 0){
    while($row = $data->fetch_assoc()){
        $outlet_name = $row['rest'] == 2 ? 'Restaurant' : 'Bar';
        echo "<tr>
        <td>{$row['sales_date']}</td>
        <td>{$outlet_name}</td>
        <td>{$row['payment_method']}</td>
        <td>{$row['customer_id']}</td>
        <td>{$row['created_by']}</td>
        <td>{$row['total']}</td>
        <td>{$row['vat_total']}</td>
        <td>{$row['discount']}</td>
        </tr>";
    }
}else{
    echo "<tr><td colspan='8' style='text-align:center;'>No sales found</td></tr>";
}

echo "</table>";
?>