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.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Scanner;

public class orderService {

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

    public void placeOrder(int userId) {

        // TODO:
        // Create order
        System.out.println("\n[Placing Order]");
        menuService.showMenu();
        List<OrderDetail> cart = new ArrayList<>();
        double totalPrice = 0.0;
        while (true) {
            System.out.print("\nEnter 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 always be greater than zero!");
                continue;
            }
            double itemPrice = item.getPrice();
            double subTotal = itemPrice * quantity;
            totalPrice += subTotal;
            OrderDetail orderDetail = new OrderDetail(itemId, quantity, itemPrice);
            cart.add(orderDetail);
            System.out.printf("Added %dx %s to your cart.%n", quantity, item.getName());
        }

        if (cart.isEmpty()) {
            System.out.println("Order cancelled. Your cart is empty.");
            return;
        }
        Order order = new Order(userId, totalPrice);
        int generatedOrderId = orderDao.save(order); // متد save باید آی‌دیِ ایجاد شده را برگرداند

        if (generatedOrderId > 0) {
            for (OrderDetail detail : cart) {
                detail.setOrderId(generatedOrderId);
                orderDetailDao.save(detail);
            }
            System.out.println("\nOrder saved successfully!");
            printReceipt(generatedOrderId);
        } else {
            System.out.println("Failed to save order due to a database error.");
        }
    }

    public void printReceipt(int orderId) {

        // TODO:
        // Print order receipt
        //AI generated
        List<OrderDetail> orderDetails = orderDetailDao.findByOrderId(orderId);
        if (orderDetails.isEmpty()) {
            System.out.println("Receipt error: Order not found.");
            return;
        }

        // ۲. چاپ فاکتور دقیقاً بر اساس قالب ریدمی
        System.out.println("\n[Order Summary / Receipt]");
        System.out.println("---------------------------------------");
        System.out.printf("%-12s %-7s %-9s %-7s%n", "Item", "Qty", "Unit", "Total");
        System.out.println("---------------------------------------");

        for (OrderDetail detail : orderDetails) {
            // برای نمایش نام غذا، آن را با آی‌دی از جدول منو می‌خوانیم
            MenuItem item = menuItemDao.findById(detail.getMenuItemId());
            String itemName = (item != null) ? item.getName() : "Unknown Item";

            double totalItemPrice = detail.getPrice() * detail.getQuantity();

            System.out.printf("%-12s %-7d $%-8.2f $%-7.2f%n",
                    itemName,
                    detail.getQuantity(),
                    detail.getPrice(),
                    totalItemPrice
            );
        }
    }

    public void showOrderHistory(int userId) {

        // TODO:
        // Display user's order history
        //AI generated
        System.out.println("\n[Order History]");


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

        if (orders == null || orders.isEmpty()) {
            System.out.println("You haven't placed any orders yet.");
            return;
        }

        System.out.println("--------------------------------------------");
        System.out.printf("%-10s %-22s %-10s%n", "Order ID", "Date & Time", "Amount Spent");
        System.out.println("--------------------------------------------");

        for (Order o : orders) {
            System.out.printf("ID: %-6d %-22s $%-10.2f%n",
                    o.getId(),
                    o.getCreatedAt(), // این فیلد از نوع Timestamp یا String در مدل شماست
                    o.getTotalPrice()
            );
        }
        System.out.println("--------------------------------------------");
    }

}