<?php
/**
 * Orders API Endpoint
 * For frontend order operations
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/constants.php';
require_once __DIR__ . '/../includes/Database.php';
require_once __DIR__ . '/../includes/Auth.php';
require_once __DIR__ . '/../includes/Order.php';
require_once __DIR__ . '/../includes/Cart.php';
require_once __DIR__ . '/../includes/EmailService.php';

header('Content-Type: application/json');

$auth = new Auth();
$order = new Order();
$cart = new Cart();
$emailService = new EmailService();
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

$userId = $auth->getUserId();

try {
    switch ($method) {
        case 'GET':
            if ($action === 'list') {
                // Get user orders
                $page = $_GET['page'] ?? 1;
                $orders = $order->getUserOrders($userId, $page);
                
                echo json_encode(['success' => true, 'orders' => $orders]);
            } elseif ($action === 'get') {
                $id = $_GET['id'] ?? 0;
                $orderData = $order->getOrderById($id);
                
                // Verify ownership
                if ($orderData && $orderData['user_id'] == $userId) {
                    $orderItems = $order->getOrderItems($id);
                    $orderData['items'] = $orderItems;
                    echo json_encode(['success' => true, 'order' => $orderData]);
                } else {
                    http_response_code(404);
                    echo json_encode(['success' => false, 'message' => 'Order not found']);
                }
            } elseif ($action === 'get-by-number') {
                $orderNumber = $_GET['order_number'] ?? '';
                $orderData = $order->getOrderByNumber($orderNumber);
                
                // Verify ownership if user is logged in
                if ($orderData && (!$userId || $orderData['user_id'] == $userId)) {
                    $orderItems = $order->getOrderItems($orderData['id']);
                    $orderData['items'] = $orderItems;
                    echo json_encode(['success' => true, 'order' => $orderData]);
                } else {
                    http_response_code(404);
                    echo json_encode(['success' => false, 'message' => 'Order not found']);
                }
            }
            break;

        case 'POST':
            $data = json_decode(file_get_contents('php://input'), true);
            
            if ($action === 'create') {
                // Require login for orders
                if (!$userId) {
                    http_response_code(401);
                    echo json_encode(['success' => false, 'message' => 'Login required']);
                    exit;
                }
                
                $sessionId = $auth->getSessionId();
                $cartData = $cart->getOrCreateCart($userId, $sessionId);
                
                $result = $order->createOrder($cartData['id'], $userId, $data);
                
                if ($result['success']) {
                    // Send confirmation email
                    $orderData = $order->getOrderById($result['order_id']);
                    $user = $auth->getUser();
                    if ($user && $user['email']) {
                        $emailService->sendOrderConfirmation($user['email'], $orderData);
                    }
                }
                
                echo json_encode($result);
            }
            break;

        default:
            http_response_code(405);
            echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>

