<?php
/**
 * API: Orders Endpoints
 * Routes:
 * GET /api/v1/orders - List user's orders
 * GET /api/v1/orders/{id} - Get order details
 * POST /api/v1/orders - Create new order
 */

require_once __DIR__ . '/../../app/controller/OrderController.php';

$orderController = new \App\Controller\OrderController($db);

// Check authentication
$apiKey = $_GET['api_key'] ?? $_POST['api_key'] ?? null;
if (!$apiKey) {
    http_response_code(401);
    echo json_encode(['error' => 'API key required']);
    exit;
}

$stmt = $db->prepare('SELECT id FROM users WHERE api_key = ? AND status = "active"');
$stmt->execute([$apiKey]);
$user = $stmt->fetch(\PDO::FETCH_ASSOC);

if (!$user) {
    http_response_code(401);
    echo json_encode(['error' => 'Invalid API key']);
    exit;
}

$userId = $user['id'];

switch ($method) {
    case 'GET':
        if ($action === '') {
            listOrders($db, $userId);
        } elseif ($action) {
            getOrder($db, $userId, $action);
        }
        break;
        
    case 'POST':
        if ($action === '') {
            createOrder($db, $userId, $input);
        }
        break;
        
    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
}

/**
 * List user's orders
 */
function listOrders($db, $userId) {
    try {
        $page = $_GET['page'] ?? 1;
        $limit = $_GET['limit'] ?? 20;
        
        $page = max(1, intval($page));
        $limit = min(100, max(1, intval($limit)));
        $offset = ($page - 1) * $limit;
        
        // Get total
        $countStmt = $db->prepare('SELECT COUNT(*) as total FROM orders WHERE user_id = ?');
        $countStmt->execute([$userId]);
        $total = $countStmt->fetch(\PDO::FETCH_ASSOC)['total'];
        
        // Get orders
        $stmt = $db->prepare('
            SELECT o.id, o.order_id, o.service_id, s.name, o.quantity, o.price, o.status, o.created_at
            FROM orders o
            JOIN services s ON o.service_id = s.id
            WHERE o.user_id = ?
            ORDER BY o.created_at DESC
            LIMIT ? OFFSET ?
        ');
        $stmt->execute([$userId, $limit, $offset]);
        $orders = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        
        http_response_code(200);
        echo json_encode([
            'success' => true,
            'data' => $orders,
            'pagination' => [
                'page' => $page,
                'limit' => $limit,
                'total' => $total
            ]
        ]);
        
    } catch (\Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
    }
}

/**
 * Get order details
 */
function getOrder($db, $userId, $orderId) {
    try {
        $stmt = $db->prepare('
            SELECT o.id, o.order_id, o.service_id, s.name, o.quantity, o.price, o.status, o.created_at
            FROM orders o
            JOIN services s ON o.service_id = s.id
            WHERE o.id = ? AND o.user_id = ?
        ');
        $stmt->execute([$orderId, $userId]);
        $order = $stmt->fetch(\PDO::FETCH_ASSOC);
        
        if (!$order) {
            http_response_code(404);
            echo json_encode(['error' => 'Order not found']);
            return;
        }
        
        http_response_code(200);
        echo json_encode([
            'success' => true,
            'data' => $order
        ]);
        
    } catch (\Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
    }
}

/**
 * Create new order
 */
function createOrder($db, $userId, $input) {
    try {
        // Validate input
        $serviceId = $input['service_id'] ?? null;
        $quantity = $input['quantity'] ?? null;
        $link = $input['link'] ?? null;
        
        if (!$serviceId || !$quantity || !$link) {
            http_response_code(400);
            echo json_encode(['error' => 'Missing required fields']);
            return;
        }
        
        $quantity = intval($quantity);
        if ($quantity < 1) {
            http_response_code(400);
            echo json_encode(['error' => 'Invalid quantity']);
            return;
        }
        
        // Get service
        $stmt = $db->prepare('SELECT id, base_price, min_quantity, max_quantity FROM services WHERE id = ? AND status = "active"');
        $stmt->execute([$serviceId]);
        $service = $stmt->fetch(\PDO::FETCH_ASSOC);
        
        if (!$service) {
            http_response_code(404);
            echo json_encode(['error' => 'Service not found']);
            return;
        }
        
        // Check quantity limits
        if ($quantity < $service['min_quantity'] || $quantity > $service['max_quantity']) {
            http_response_code(400);
            echo json_encode(['error' => "Quantity must be between {$service['min_quantity']} and {$service['max_quantity']}"]);
            return;
        }
        
        // Calculate price with 80% markup
        $displayPrice = $service['base_price'] * $quantity * 1.80;
        
        // Check user balance
        $stmt = $db->prepare('SELECT balance FROM users WHERE id = ?');
        $stmt->execute([$userId]);
        $user = $stmt->fetch(\PDO::FETCH_ASSOC);
        
        if ($user['balance'] < $displayPrice) {
            http_response_code(400);
            echo json_encode(['error' => 'Insufficient balance']);
            return;
        }
        
        // Create order
        $db->beginTransaction();
        
        try {
            // Insert order
            $insertStmt = $db->prepare('
                INSERT INTO orders (user_id, service_id, quantity, price, link, status, created_at)
                VALUES (?, ?, ?, ?, ?, "pending", NOW())
            ');
            $insertStmt->execute([$userId, $serviceId, $quantity, $displayPrice, $link]);
            $orderId = $db->lastInsertId();
            
            // Deduct balance
            $db->prepare('UPDATE users SET balance = balance - ? WHERE id = ?')->execute([$displayPrice, $userId]);
            
            // Log transaction
            $db->prepare('
                INSERT INTO transactions (user_id, type, amount, reference, description, created_at)
                VALUES (?, "order", ?, ?, ?, NOW())
            ')->execute([$userId, -$displayPrice, "ORD-$orderId", "Order placed"]);
            
            $db->commit();
            
            http_response_code(201);
            echo json_encode([
                'success' => true,
                'order_id' => $orderId,
                'price' => $displayPrice,
                'message' => 'Order created successfully'
            ]);
            
        } catch (\Exception $e) {
            $db->rollBack();
            throw $e;
        }
        
    } catch (\Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Order creation failed: ' . $e->getMessage()]);
    }
}
?>
