package dev.service;

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

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class OrderService {

    private final MenuItemDao menuItemDao = new MenuItemDao();
    private final OrderDao orderDao = new OrderDao();
    private final OrderDetailDao orderDetailDao = new OrderDetailDao();
    private final Scanner scanner = new Scanner(System.in);

    public void placeOrder(int userId) {
        List<OrderDetail> cart = new ArrayList<>();
        double totalPrice = 0.0;

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

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

            MenuItem item = menuItemDao.findById(itemId);
            if (item == null) {
                System.out.println("Invalid Item ID! Please try again.");
                continue;
            }

            System.out.print("Enter quantity: ");
            int quantity = scanner.nextInt();
            if (quantity <= 0) {
                System.out.println("Quantity must be greater than zero!");
                continue;
            }

            // ساخت جزئیات سفارش با قیمت زمان خرید
            OrderDetail detail = new OrderDetail();
            detail.setMenuItemId(item.getId());
            detail.setQuantity(quantity);
            detail.setPrice(item.getPrice());

            cart.add(detail);
            totalPrice += item.getPrice() * quantity;

            System.out.printf("Added %dx %s to your cart.\n", quantity, item.getName());
        }

        if (cart.isEmpty()) {
            System.out.println("Order cancelled. Cart is empty.");
            return;
        }

        // ۱. ذخیره سفارش اصلی در دیتابیس و گرفتن آیدی تولید شده
        Order order = new Order();
        order.setUserId(userId);
        order.setTotalPrice(totalPrice);

        int orderId = orderDao.save(order);

        if (orderId != -1) {
            // ۲. ذخیره تک‌تک جزئیات سبد خرید متصل به این اوردر آیدی
            for (OrderDetail detail : cart) {
                detail.setOrderId(orderId);
                orderDetailDao.save(detail);
            }
            System.out.println("\nOrder saved successfully!");
            // ۳. چاپ خودکار رسید بلافاصله پس از ثبت سفارش طبق نیازمندی داک
            printReceipt(orderId);
        } else {
            System.out.println("Failed to save order due to a database error.");
        }
    }

    public void printReceipt(int orderId) {
        List<OrderDetail> details = orderDetailDao.findByOrderId(orderId);
        if (details == null || details.isEmpty()) {
            System.out.println("No receipt details found for Order ID: " + orderId);
            return;
        }

        System.out.println("\n[Order Summary / Receipt]");
        System.out.println("---------------------------------------");
        System.out.printf("%-12s %-5s %-9s %-6s\n", "Item", "Qty", "Unit", "Total");
        System.out.println("---------------------------------------");

        double grandTotal = 0.0;
        for (OrderDetail detail : details) {
            MenuItem item = menuItemDao.findById(detail.getMenuItemId());
            String itemName = (item != null) ? item.getName() : "Unknown";
            double itemTotal = detail.getPrice() * detail.getQuantity();
            grandTotal += itemTotal;

            System.out.printf("%-12s %-5d $%-8.2f $%-6.2f\n", itemName, detail.getQuantity(), detail.getPrice(), itemTotal);
        }

        System.out.println("---------------------------------------");
        System.out.printf("Final Total: $%-6.2f\n", grandTotal);
    }

    public void showOrderHistory(int userId) {
        List<Order> orders = orderDao.findByUserId(userId);

        if (orders == null || orders.isEmpty()) {
            System.out.println("\nYou have no past orders.");
            return;
        }

        System.out.println("\n=======================================");
        System.out.println("          📜 ORDER HISTORY 📜          ");
        System.out.println("=======================================");
        System.out.printf("%-10s | %-20s | %-12s\n", "Order ID", "Date & Time", "Total Price");
        System.out.println("---------------------------------------");

        for (Order o : orders) {
            System.out.printf("%-10d | %-20s | $%-12.2f\n",
                    o.getId(),
                    o.getCreatedAt().toString().replace("T", " ").substring(0, 19),
                    o.getTotalPrice());
        }
        System.out.println("=======================================");
    }
}