<?php
include 'db.php';

// ================= GET FILTERS =================
$from = $_GET['from'] ?? date('Y-m-d');
$to = $_GET['to'] ?? date('Y-m-d');
$meal_type = $_GET['meal_type'] ?? '';
$search = $_GET['search'] ?? '';

// ================= BUILD WHERE =================
$where = ["mp.created_at >= '$from 00:00:00'", "mp.created_at <= '$to 23:59:59'"];
if($meal_type) $where[] = "mp.meal_type = '".$conn->real_escape_string($meal_type)."'";
if($search) $where[] = "m.meal_name LIKE '%".$conn->real_escape_string($search)."%'";
$where_sql = implode(" AND ", $where);

// ================= FETCH DATA =================
$sql = "SELECT mp.*, m.meal_name 
        FROM meal_production mp 
        LEFT JOIN meals m ON m.id = mp.meal_id
        WHERE $where_sql 
        ORDER BY mp.created_at DESC";

$result = $conn->query($sql);

// ================= EXPORT TO CSV =================
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename="kitchen_production.csv"');
$output = fopen('php://output', 'w');

// HEADER ROW
fputcsv($output, ['ID','Meal','Type','Number of People','Produced By','Produced At','Status']);

// DATA ROWS
if($result && $result->num_rows){
    while($row = $result->fetch_assoc()){
        fputcsv($output, [
            $row['id'],
            $row['meal_name'],
            $row['meal_type'],
            $row['number_of_people'],
            $row['produced_by'],
            $row['created_at'],
            $row['status']
        ]);
    }
}
fclose($output);
exit;