<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

require_once '../config/database.php';

// API authentication
function authenticate() {
    session_start();
    if (!isset($_SESSION['user_id'])) {
        http_response_code(401);
        echo json_encode(['error' => 'Unauthorized']);
        exit;
    }
    return $_SESSION['user_id'];
}

// Get request method and path
$method = $_SERVER['REQUEST_METHOD'];
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$path_parts = explode('/', trim($path, '/'));

// Remove 'api' from path
if ($path_parts[0] === 'api') {
    array_shift($path_parts);
}

$endpoint = $path_parts[0] ?? '';
$resource_id = $path_parts[1] ?? null;

switch ($endpoint) {
    case 'devices':
        require_once 'devices.php';
        break;
    case 'sensors':
        require_once 'sensors.php';
        break;
    case 'buttons':
        require_once 'buttons.php';
        break;
    case 'commands':
        require_once 'commands.php';
        break;
    case 'logs':
        require_once 'logs.php';
        break;
    case 'firmware':
        require_once 'firmware.php';
        break;
    case 'auth':
        require_once 'auth.php';
        break;
    case 'claim':
        require_once 'claim.php';
        break;
    case 'heartbeat':
        require_once 'heartbeat.php';
        break;
    case 'device_config':
        require_once 'device_config.php';
        break;
    case 'sensor_assignment':
        require_once 'sensor_assignment.php';
        break;
    default:
        http_response_code(404);
        echo json_encode(['error' => 'Endpoint not found']);
        break;
}
?>
