<?php
// Check if we're being included from the main index.php
$config_path = file_exists('../config/config.php') ? '../config/config.php' : 'config/config.php';
require_once $config_path;

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

$method = $_SERVER['REQUEST_METHOD'];
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$uri = str_replace('/api', '', $uri);

$auth = new Auth();

switch ($uri) {
    case '/articles':
        if ($method === 'GET') {
            include 'endpoints/articles.php';
        } elseif ($method === 'POST') {
            $auth->requireAuth();
            include 'endpoints/create-article.php';
        }
        break;

    case '/chat':
        include 'endpoints/chat.php';
        break;

    case '/ai-generate':
        $auth->requireAuth();
        include 'endpoints/ai-generate.php';
        break;

    case '/upload':
        $auth->requireAuth();
        include 'endpoints/upload.php';
        break;

    case '/crawl':
        // Allow crawl without auth for cron jobs, but require admin auth for manual calls
        if (isset($_SERVER['HTTP_X_CRON_TOKEN'])) {
            // For cron jobs - validate token if needed
            include 'endpoints/crawl.php';
        } else {
            $auth->requireAuth();
            include 'endpoints/crawl.php';
        }
        break;

    case '/publish-international':
        $auth->requireAuth();
        include 'endpoints/publish-international.php';
        break;

    case '/selective-publish':
        $auth->requireAuth();
        include 'endpoints/selective-publish.php';
        break;

    case '/platforms':
        $auth->requireAuth();
        include 'endpoints/platforms.php';
        break;

    case '/public/ai-writer':
        include 'endpoints/public-ai-writer.php';
        break;

    default:
        http_response_code(404);
        echo json_encode(['error' => 'Endpoint not found']);
        break;
}
?>