<?php
// Enable CORS for all origins (adjust as needed for your security)
$allowed_origins = [
    "https://score-now.com",
    "https://dev.score-now.com",
    "https://education.score-now.com"
];

if (isset($_SERVER['HTTP_ORIGIN']) && in_array($_SERVER['HTTP_ORIGIN'], $allowed_origins)) {
    header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
    header("Access-Control-Allow-Credentials: true"); // If cookies or auth headers are needed
}
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

// If the request is OPTIONS, just return a 200 (or 204) and exit
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Include your database connection
include('dbconnect.php');

/**
 * Example function to retrieve a user by token.
 * Adjust the DB table/column names to match your actual schema.
 */
function getUserByToken($conn, $token)
{
    $sql  = "SELECT * FROM user WHERE bearer = ? LIMIT 1";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $token);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result && $row = $result->fetch_assoc()) {
        return $row; // user row
    }
    return null;
}

// Define a static "public" token. If the request has this token,
// we let it pass even if not in the DB:
define('PUBLIC_BEARER', '50afb255cfa3a36834e0a51185b1eb09');

// 1) Grab the "api" parameter from the query string (e.g., ?api=results)
$api = $_GET['api'] ?? null;

// 2) If it's "login", skip the bearer check
if ($api === 'login') {
    // Just go directly to the switch-case below
    // (No bearer check is required)
} else {
    // Perform the Bearer check for all other $api routes
    $authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
    if (preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
        $providedToken = $matches[1];

        // If it matches the public token => allow
        if ($providedToken === PUBLIC_BEARER) {
            // Do nothing special, let it pass
        } else {
            // Otherwise, do a DB lookup for the user who has this token
            $userRow = getUserByToken($conn, $providedToken);
            if (!$userRow) {
                http_response_code(401);
                echo "Bearer token not recognized or expired.";
                exit;
            }
            // Optionally store the user info: $currentUser = $userRow;
        }
    } else {
        // http_response_code(401);
        // echo "Missing Bearer token!";
        // echo $authHeader;
        // echo "<= token";
        // exit;
    }
}

// 3) Decide what to do based on $api
switch ($api) {
    case '/':
        echo "Welcome to the Score Now API!";
        break;

    // -------------- 
    // src/ folder routes
    // --------------
    case 'bibs':
        include('src/bibs.php');
        break;
    case 'competition':
        include('src/competition.php');
        break;
    case 'dashboard':
        include('src/dashboard.php');
        break;
    case 'import_xml':
        include('src/import_xml.php');
        break;
    case 'export_xml':
        include('src/export_xml.php');
        break;
    case 'results':
        include('src/results.php');
        break;
    case 'scores':
        include('src/scores.php');
        break;
    case 'schedule':
        include('src/schedule.php');
        break;
    case 'updateSchedule':
        include('src/updateSchedule.php');
        break;
    case 'updateScheduleOrder':
        include('src/updateScheduleOrder.php');
        break;
    case 'runs':
        include('src/runs.php');
        break;
    case 'officials':
        include('src/officials.php');
        break;
    case 'panel':
        include('src/panel.php');
        break;
    case 'protests':
        include('src/protests.php');
        break;
    case 'settings':
        include('src/settings.php');
        break;
    case 'tv':
        include('src/tv.php');
        break;
    case 'teamResults':
        include('src/teamResults.php');
        break;
    case 'updateRunTimestamp':
        include('src/updateRunTimestamp.php');
        break;
    case 'roles':
        include('src/roles.php');
        break;
    case 'admin':
        include('src/admin.php');
        break;
    case 'participations':
    include('src/participations.php');
    break;

    // --------------
    // login/ folder routes
    // --------------
    case 'fetch-email':
        include('src/login/fetch-email.php');
        break;
    case 'login':
        include('src/login/login.php');
        break; // <--- no bearer check required for "login"
    case 'reset_password_request':
        include('src/login/reset_password_request.php');
        break;
    case 'reset_password':
        include('src/login/reset_password.php');
        break;
    case 'save-email':
        include('src/login/save-email.php');
        break;
    case 'signup':
        include('src/login/signup.php');
        break;

    // --------------
    // functions/ folder routes
    // --------------
    case 'step-ladder':
        include('functions/step-ladder.php');
        break;
    case 'athletes':
        include('functions/athletes.php');
        break;
    case 'categories':
        include('functions/categories.php');
        break;
    case 'rounds_to_schedule':
        include('functions/rounds_to_schedule.php');
        break;
    case 'runs':
        include('functions/runs.php');
        break;
    case 'snake':
        include('functions/snake.php');
        break;
    case 'ladder':
        include('functions/ladder.php');
        break;
    case 'startlists':
        include('functions/startlists.php');
        break;
    case 'generate_competition':
        include('functions/generate_competition.php');
        break;

    // --------------
    // 404 fallback
    // --------------
    default:
        echo "No matching API route for: " . htmlspecialchars($api ?? '');
        break;
}

// 4) Close the database connection (if opened)
if (isset($conn) && $conn instanceof mysqli) {
    $conn->close();
}

?>
