package dev.service;

import dev.dao.MenuItemDao;
import dev.dao.OrderDao;
import dev.dao.OrderDetailDao;
import dev.database.DatabaseConnection;
import dev.model.MenuItem;
import dev.model.Order;
import dev.model.OrderDetail;

import java.sql.*;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Scanner;

public class OrderService {

    OrderDetailDao orderDetailDao = new OrderDetailDao();
    OrderDao orderDao = new OrderDao();
    MenuItemDao menuItemDao = new MenuItemDao();

    public void placeOrder(int userId) {

        // TODO:
        // Create order

        System.out.println("[Placing Order]");

        int order_id = orderDao.save(new Order(-1, userId, LocalDateTime.now(), 0));
        if (order_id == -1) {
            System.out.println("Order id was not found.");
            return;
        }

        Scanner scanner = new Scanner(System.in);

        while (true){
            System.out.print("\nEnter the ID of the item to add (or 0 to finish): ");
            int itemId = scanner.nextInt();

            if (itemId == 0) {

                try (Connection c = DatabaseConnection.getConnection()) {

                    double total = 0.0;
                    String selectQuery = "SELECT * FROM order_details";
                    try (Statement stmt = c.createStatement();
                         ResultSet rs = stmt.executeQuery(selectQuery)) {

                        while (rs.next()) {
                            int orderId = rs.getInt("order_id");
                            if (orderId == order_id) {
                                double price = rs.getDouble("unit_price");
                                int quantity = rs.getInt("quantity");
                                total += price * quantity;
                            }
                        }
                    }

                    String insertQuery = "UPDATE orders SET total_price = ? WHERE id = ? ";
                    try (PreparedStatement pstmt = c.prepareStatement(insertQuery)) {
                        pstmt.setDouble(1, total);
                        pstmt.setInt(2, order_id);
                        pstmt.executeUpdate();
                    }
                }
                catch (SQLException e) {
                    //
                }

                break;
            }

            System.out.print("\nEnter quantity: ");
            int quantity = scanner.nextInt();
            System.out.println();

            orderDetailDao.save(new OrderDetail(-1, order_id, itemId, quantity, 0));

            MenuItem item = menuItemDao.findById(itemId);

            System.out.println("Added " + quantity + "x " + item.getName() + " to your cart. \n");
        }

        printReceipt(order_id);

        System.out.println("Order saved successfully!");

    }

    public void printReceipt(int orderId) {

        // TODO:
        // Print order receipt

        System.out.println("[Order Summary / Receipt]");

        try (Connection c = DatabaseConnection.getConnection()) {

            double total_price = 1.0;
            String selectQuery1 = "SELECT * FROM orders";
            try (Statement stmt1 = c.createStatement();
                 ResultSet rs1 = stmt1.executeQuery(selectQuery1)) {

                boolean isInOrders = false;
                while (rs1.next()) {
                    int OrderId = rs1.getInt("id");
                    if (orderId == OrderId) {
                        isInOrders = true;
                        total_price = rs1.getDouble("total_price");
                        break;
                    }
                }
                if (!isInOrders) {
                    System.out.println("Order was not found.");
                    return;
                }
            }

            List<OrderDetail> orderDetails = orderDetailDao.findByOrderId(orderId);

            System.out.println("Item | Unit Price | Quantity | Total");
            System.out.println("---------------------------------------");
            for (OrderDetail od : orderDetails) {
                MenuItem menuItem = menuItemDao.findById(od.getMenuItemId());
                System.out.println(menuItem.getName() + " | " + "$" + od.getPrice() +
                        " | " + od.getQuantity() + " | " + "$" + od.getPrice() * od.getQuantity());
                System.out.println("---------------------------------------");
            }
            System.out.println("Final Total: " + "$" + total_price + "\n");

        }
        catch (SQLException e) {
            System.err.println("Error in connection with database: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public void showOrderHistory(int userId) {

        // TODO:
        // Display user's order history

        List<Order> orders = orderDao.findByUserId(userId);

        System.out.println("Order Id | Date & Time | Total Price");
        for (Order o : orders) {
            System.out.println(o.getId() + " | " + o.getCreatedAt() + " | " + "$" + o.getTotalPrice());
        }

    }

}