<?php
require_once 'Database.php';

class Order {
    private $db;

    public function __construct() {
        $this->db = new Database();
    }

    public function createOrder($user_id, $items) {
        if (empty($items)) {
            throw new Exception("Cannot create an empty order.");
        }

        // Check operating hours
        $settings_stmt = $this->db->query("SELECT setting_key, setting_value FROM settings WHERE setting_key IN ('operating_hours_start', 'operating_hours_end')");
        $settings = $settings_stmt->fetchAll(PDO::FETCH_KEY_PAIR);
        
        $start_time = $settings['operating_hours_start'] ?? '00:00';
        $end_time = $settings['operating_hours_end'] ?? '23:59';
        $timezone = new DateTimeZone('UTC'); // Use a consistent timezone like UTC
        $current_time = new DateTime('now', $timezone);
        $start_datetime = DateTime::createFromFormat('H:i', $start_time, $timezone);
        $end_datetime = DateTime::createFromFormat('H:i', $end_time, $timezone);

        $is_open = false;
        if ($start_datetime > $end_datetime) { // Operating hours cross midnight (e.g., 22:00-02:00)
            // Open if current time is after start OR before end
            if ($current_time >= $start_datetime || $current_time <= $end_datetime) {
                $is_open = true;
            }
        } else { // Operating hours are on the same day (e.g., 08:00-22:00)
            if ($current_time >= $start_datetime && $current_time <= $end_datetime) {
                $is_open = true;
            }
        }

        if (!$is_open) {
            throw new Exception("Sorry, we are currently closed. Operating hours are from {$start_time} to {$end_time}.");
        }

        // Assume all items are from the same shop for simplicity
        $shop_id = $items[0]['shop_id'];
        $total_amount = array_reduce($items, function ($sum, $item) {
            return $sum + ($item['price'] * $item['quantity']);
        }, 0);

        try {
            $pdo = $this->db->getConnection();
            $pdo->beginTransaction();

            // Create the main order record
            $order_stmt = $this->db->query(
                "INSERT INTO orders (user_id, shop_id, total_amount, status) VALUES (?, ?, ?, 'pending')",
                [$user_id, $shop_id, $total_amount]
            );
            $order_id = $pdo->lastInsertId();

            // Create order items records
            $item_stmt = $pdo->prepare("INSERT INTO order_items (order_id, product_id, quantity, price) VALUES (?, ?, ?, ?)");
            foreach ($items as $item) {
                $item_stmt->execute([$order_id, $item['id'], $item['quantity'], $item['price']]);
            }

            $pdo->commit();
            return $order_id;

        } catch (Exception $e) {
            if (isset($pdo) && $pdo->inTransaction()) $pdo->rollBack();
            throw new Exception("Order creation failed: " . $e->getMessage());
        }
    }

    public function getOrderDetails($order_id, $user_id) {
        // First, get the main order details and verify ownership
        $order_stmt = $this->db->query(
            "SELECT o.*, s.name as shop_name 
             FROM orders o
             JOIN shops s ON o.shop_id = s.id
             WHERE o.id = ? AND o.user_id = ?",
            [$order_id, $user_id]
        );
        $order = $order_stmt->fetch(PDO::FETCH_ASSOC);

        if (!$order) {
            throw new Exception("Order not found or you do not have permission to view it.");
        }

        // Then, get the items associated with this order
        $items_stmt = $this->db->query(
            "SELECT oi.quantity, oi.price, p.name as product_name, p.image as product_image
             FROM order_items oi
             JOIN products p ON oi.product_id = p.id
             WHERE oi.order_id = ?",
            [$order_id]
        );
        $items = $items_stmt->fetchAll(PDO::FETCH_ASSOC);

        $order['items'] = $items;
        return $order;
    }

    public function getUserOrders($user_id) {
        $stmt = $this->db->query(
            "SELECT o.id, o.total_amount, o.status, o.created_at, s.name as shop_name
             FROM orders o
             JOIN shops s ON o.shop_id = s.id
             WHERE o.user_id = ?
             ORDER BY o.created_at DESC",
            [$user_id]
        );

        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}
?>