<?php
require_once __DIR__ . '/backend/db_connect.php';


header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
header("Content-Type: application/json; charset=UTF-8");


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

$user_id = null;


$requestUri = $_SERVER['REQUEST_URI'];
$method = $_SERVER['REQUEST_METHOD'];


$basePath = '/new-tool/';
$path = substr($requestUri, strlen($basePath));

//remove query string if present
$path = strtok($path, '?');

//trim leading/trailing slashes for easier parsing
$path = trim($path, '/');

$pathSegments = explode('/', $path);
$mainRoute = $pathSegments[0];


switch ($mainRoute) {

    case 'websites':
        require_once __DIR__ . '/backend/websites.php';
        //if method is POST, we handle the creation of a new website
        if ($method === 'POST') {
            handlePostWebsite($method, $pdo);
            break;
        }
        //if method is GET, we handle the retrieval of all websites
        if ($method === 'GET') {
            //if there is a searchTerm query parameter, we handle the search
            if (isset($_GET['searchTerm'])) {
                handleGetAllBySearchTerm($method, $pdo);
                break;
            }
            //otherwise, we handle the retrieval of all websites
            handleGetAllWebsites($method, $pdo);
            break;
        }
        //if method is PUT, we handle the update of a website
        if ($method === 'PUT') {
            handleUpdateWebsite($method, $pdo);
            break;
        }
        break;

    case 'login':
        require_once __DIR__ . '/backend/login.php';
        handleLoginRequest($method, $pdo);
        break;

    case 'screenshot':
        require_once __DIR__ . '/backend/screenshot.php';
        handleGetApiflashScreenshot($method, $_GET['url'] ?? '');
        break;

    case 'logout':
        require_once __DIR__ . '/backend/logout.php';
        handleLogoutRequest($method, $pdo);
        break;

    default:
        http_response_code(404);
        echo json_encode(['message' => 'Endpoint not found: ' . htmlspecialchars($path)]);
        break;
}
?>