<?php
/**
 * API: Services Endpoints
 * Routes:
 * GET /api/v1/services - List all services
 * GET /api/v1/services/{id} - Get service details
 */

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

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

switch ($method) {
    case 'GET':
        if ($action === '') {
            // List services
            listServices($db);
        } elseif ($action) {
            // Get service details
            getService($db, $action);
        } else {
            http_response_code(404);
            echo json_encode(['error' => 'Invalid request']);
        }
        break;
        
    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method not allowed']);
}

/**
 * List all services
 */
function listServices($db) {
    try {
        // Get pagination
        $page = $_GET['page'] ?? 1;
        $limit = $_GET['limit'] ?? 20;
        $category = $_GET['category'] ?? '';
        
        $page = max(1, intval($page));
        $limit = min(100, max(1, intval($limit)));
        $offset = ($page - 1) * $limit;
        
        // Build query
        $query = 'SELECT * FROM services WHERE status = "active"';
        $params = [];
        
        if ($category) {
            $query .= ' AND category = ?';
            $params[] = $category;
        }
        
        // Get total count
        $countStmt = $db->prepare('SELECT COUNT(*) as total FROM services WHERE status = "active"' . ($category ? ' AND category = ?' : ''));
        $countStmt->execute($params);
        $total = $countStmt->fetch(\PDO::FETCH_ASSOC)['total'];
        
        // Get services
        $query .= ' LIMIT ? OFFSET ?';
        $params[] = $limit;
        $params[] = $offset;
        
        $stmt = $db->prepare($query);
        $stmt->execute($params);
        $services = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        
        // Apply markup to prices
        $services = array_map(function($service) {
            $service['display_price'] = $service['base_price'] * 1.80;
            return $service;
        }, $services);
        
        http_response_code(200);
        echo json_encode([
            'success' => true,
            'data' => $services,
            'pagination' => [
                'page' => $page,
                'limit' => $limit,
                'total' => $total,
                'pages' => ceil($total / $limit)
            ]
        ]);
        
    } catch (\Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => 'Failed to fetch services: ' . $e->getMessage()]);
    }
}

/**
 * Get service details
 */
function getService($db, $serviceId) {
    try {
        $stmt = $db->prepare('SELECT * 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;
        }
        
        // Apply markup
        $service['display_price'] = $service['base_price'] * 1.80;
        
        http_response_code(200);
        echo json_encode([
            'success' => true,
            'data' => $service
        ]);
        
    } catch (\Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
    }
}
?>
