package dev.dao;

import dev.database.DatabaseConnection;
import dev.model.OrderDetail;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class OrderDetailDao {

    public void save(OrderDetail detail) {
        String sql = "INSERT INTO order_details (order_id, menu_item_id, quantity, unit_price) VALUES (?, ?, ?, ?)";
        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {

            ps.setInt(1, detail.getOrderId());
            ps.setInt(2, detail.getMenuItemId());
            ps.setInt(3, detail.getQuantity());
            ps.setDouble(4, detail.getPrice());
            ps.executeUpdate();

        } catch (SQLException e) {
            System.out.println("Error saving order detail: " + e.getMessage());
        }
    }

    public List<OrderDetail> findByOrderId(int orderId) {
        List<OrderDetail> details = new ArrayList<>();
        String sql = "SELECT * FROM order_details WHERE order_id = ?";

        try (Connection conn = DatabaseConnection.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {

            ps.setInt(1, orderId);
            ResultSet rs = ps.executeQuery();

            while (rs.next()) {
                OrderDetail d = new OrderDetail();
                d.setId(rs.getInt("id"));
                d.setOrderId(rs.getInt("order_id"));
                d.setMenuItemId(rs.getInt("menu_item_id"));
                d.setQuantity(rs.getInt("quantity"));
                d.setPrice(rs.getDouble("unit_price"));
                details.add(d);
            }

        } catch (SQLException e) {
            System.out.println("Error fetching order details: " + e.getMessage());
        }
        return details;
    }
}