package dev.dao;

import dev.database.DatabaseConnection;

import dev.model.OrderDetail;


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 sql = "INSERT INTO order_details (order_id, menu_id, quantity, item_price) VALUES (?,?,?,?)";

        try (PreparedStatement ps = DatabaseConnection
                                    .getConnection()
                                    .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(e.getStackTrace());
        }

    }

    public List<OrderDetail> findByOrderId(int orderId) {

       String sql = "SELECT * FROM order_details WHERE order_id=?";

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

       try (PreparedStatement ps = DatabaseConnection
                                    .getConnection()
                                    .prepareStatement(sql))
       {
           ps.setInt(1,orderId);
           ResultSet rs = ps.executeQuery();

           while(rs.next())
           {
               OrderDetail detail = new OrderDetail();

               detail.setOrderId(rs.getInt("order_id"));
               detail.setMenuItemId(rs.getInt("menu_id"));
               detail.setPrice(rs.getDouble("item_price"));
               detail.setQuantity(rs.getInt("quantity"));

               details.add(detail);
           }

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

        return details;
    }

}