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

    $action = $_POST['action'] ?? '';

    if($action==='list'){
        $meal_id = $_POST['meal_id'] ?? '';
        $from    = $_POST['from'] ?? '';
        $to      = $_POST['to'] ?? '';

        $where = [];
        if($meal_id) $where[] = "mp.meal_id=".intval($meal_id);
        if($from)    $where[] = "DATE(mp.produced_at) >= '".$conn->real_escape_string($from)."'";
        if($to)      $where[] = "DATE(mp.produced_at) <= '".$conn->real_escape_string($to)."'";

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

        $sql = "
            SELECT mp.*, m.meal_name, p.name AS material_name, u.username AS produced_by
            FROM meal_production mp
            LEFT JOIN meals m ON mp.meal_id=m.id
            LEFT JOIN products p ON mp.material_id=p.id
            LEFT JOIN users u ON mp.produced_by=u.id
            $where_sql
            ORDER BY mp.produced_at DESC
        ";

        $res = $conn->query($sql);
        $data = [];
        while($row = $res->fetch_assoc()){
            $data[] = $row;
        }

        echo json_encode($data);
    }
    ?>
