<?php
// Get Orders API - Fetch user's orders
session_start();
require_once 'config.php';

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

try {
    // Get user_id from request (passed from client-side localStorage)
    $userId = isset($_GET['user_id']) ? (int)$_GET['user_id'] : null;
    
    // If no user_id provided in request, try to get from session
    if (!$userId && isset($_SESSION['user_id'])) {
        $userId = (int)$_SESSION['user_id'];
    }
    
    // If still no user_id, return error
    if (!$userId) {
        sendResponse(false, 'User not authenticated', []);
    }

    // Verify user exists in database (optional security check)
    $userCheckQuery = "SELECT id FROM users WHERE id = ?";
    $userCheckStmt = $conn->prepare($userCheckQuery);
    if ($userCheckStmt) {
        $userCheckStmt->bind_param("i", $userId);
        $userCheckStmt->execute();
        $userCheckResult = $userCheckStmt->get_result();
        
        if ($userCheckResult->num_rows === 0) {
            $userCheckStmt->close();
            sendResponse(false, 'User not found', []);
        }
        $userCheckStmt->close();
    }

    // Fetch orders for the user
    $ordersQuery = "SELECT id, order_number, full_name, email, phone, address, payment_method, 
                           subtotal, tax, total, status, created_at 
                    FROM orders 
                    WHERE user_id = ? 
                    ORDER BY created_at DESC";
    
    $stmt = $conn->prepare($ordersQuery);
    if (!$stmt) {
        throw new Exception('Prepare statement failed: ' . $conn->error);
    }

    $stmt->bind_param("i", $userId);
    if (!$stmt->execute()) {
        throw new Exception('Execute failed: ' . $stmt->error);
    }

    $result = $stmt->get_result();
    $orders = [];

    while ($order = $result->fetch_assoc()) {
        // Fetch items for this order
        $itemsQuery = "SELECT id, item_name, quantity, price FROM order_items WHERE order_id = ?";
        $itemsStmt = $conn->prepare($itemsQuery);
        
        if (!$itemsStmt) {
            throw new Exception('Prepare statement for items failed: ' . $conn->error);
        }

        $itemsStmt->bind_param("i", $order['id']);
        if (!$itemsStmt->execute()) {
            throw new Exception('Execute failed for items: ' . $itemsStmt->error);
        }

        $itemsResult = $itemsStmt->get_result();
        $items = [];

        while ($item = $itemsResult->fetch_assoc()) {
            $items[] = $item;
        }

        $itemsStmt->close();

        // Add items to order
        $order['items'] = $items;
        $orders[] = $order;
    }

    $stmt->close();

    // Return orders
    sendResponse(true, 'Orders retrieved successfully', $orders);

} catch (Exception $e) {
    error_log('Get orders error: ' . $e->getMessage());
    http_response_code(400);
    sendResponse(false, 'Failed to retrieve orders: ' . $e->getMessage(), []);
}

$conn->close();
?>
