<?php
require_once('tcpdf-main/tcpdf.php');
include 'db.php';

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

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

$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";
$res = $conn->query($sql);

$pdf = new TCPDF();
$pdf->AddPage();
$pdf->SetFont('helvetica', '', 10);

$html = '<h3>Kitchen Production Report</h3>';
$html .= '<table border="1" cellpadding="4"><thead>
<tr><th>ID</th><th>Meal</th><th>Type</th><th>Number of People</th><th>Produced By</th><th>Produced At</th><th>Status</th></tr></thead><tbody>';

while($row = $res->fetch_assoc()){
    $html .= '<tr>
        <td>'.$row['id'].'</td>
        <td>'.$row['meal_name'].'</td>
        <td>'.$row['meal_type'].'</td>
        <td>'.$row['number_of_people'].'</td>
        <td>'.$row['produced_by'].'</td>
        <td>'.$row['created_at'].'</td>
        <td>'.$row['status'].'</td>
    </tr>';
}

$html .= '</tbody></table>';
$pdf->writeHTML($html, true, false, true, false, '');
$pdf->Output('kitchen_production.pdf', 'I');