package dev.dao;

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

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class OrderDetailDao {

    public void save(OrderDetail detail) {

        String quary = "INSERT INTO order_details (order_id, menu_item_id ,quantity , unit_price) VALUES (?, ?, ? ,?)";
        try (Connection c = DatabaseConnection.getConnection();
             PreparedStatement prst = c.prepareStatement(quary)){
            prst.setInt(1, detail.getOrderId());
            prst.setInt(2, detail.getMenuItemId());
            prst.setInt(3, detail.getQuantity());
            prst.setDouble(4 , detail.getPrice());

            int i = prst.executeUpdate();





        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }




    }

    public List<OrderDetail> findByOrderId(int orderId) {

        List<OrderDetail> result = new ArrayList<>();

        String query = "Select * From order_details WHERE order_id = ?";

        try(Connection c = DatabaseConnection.getConnection();
            PreparedStatement pst = c.prepareStatement(query)) {

            pst.setInt(1 , orderId);

            try(ResultSet rst = pst.executeQuery()){
                while (rst.next()){
                    OrderDetail orderDetail = new OrderDetail(rst.getInt("id"),
                            rst.getInt("order_id"),
                            rst.getInt("menu_item_id"),
                            rst.getInt("quantity"),
                            rst.getDouble("unit_price"));
                    result.add(orderDetail);

                }

            }

            return result;

        }catch (SQLException e){
            System.out.println(e.getMessage());
        }

        return null;
    }

}