<?php
/**
 * Public API Router
 * Routes: /api/v1/
 */

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

// Get request method and path
$method = $_SERVER['REQUEST_METHOD'];
$requestUri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$basePath = '/api/v1';

// Extract endpoint from URI
$endpoint = str_replace($basePath, '', $requestUri);
$endpoint = trim($endpoint, '/');

// Parse endpoint parts
$parts = explode('/', $endpoint);
$resource = $parts[0] ?? '';
$action = $parts[1] ?? '';

// Initialize database
try {
    $db = new \PDO(
        'mysql:host=' . getenv('DB_HOST') . ';dbname=' . getenv('DB_NAME') . ';charset=utf8mb4',
        getenv('DB_USER'),
        getenv('DB_PASS'),
        [\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION]
    );
} catch (\PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Database connection failed']);
    exit;
}

// Load request body
$input = json_decode(file_get_contents('php://input'), true) ?? [];

// Routes
try {
    switch ($resource) {
        case 'auth':
            require __DIR__ . '/../app/api/auth.php';
            break;
            
        case 'services':
            require __DIR__ . '/../app/api/services.php';
            break;
            
        case 'orders':
            require __DIR__ . '/../app/api/orders.php';
            break;
            
        case 'payments':
            require __DIR__ . '/../app/api/payments.php';
            break;
            
        case 'user':
            require __DIR__ . '/../app/api/user.php';
            break;
            
        default:
            http_response_code(404);
            echo json_encode(['error' => 'Endpoint not found']);
            exit;
    }
} catch (\Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
    exit;
}
?>
