<?php
session_start();

// Check if it's a short URL access FIRST (before session redirect)
$request_uri = $_SERVER['REQUEST_URI'];
$path_info = parse_url($request_uri, PHP_URL_PATH);

// Get the script directory to properly handle subdirectories
$script_dir = dirname($_SERVER['SCRIPT_NAME']);
$script_dir = rtrim($script_dir, '/');

// Remove the script directory from the path to get the relative path
if ($script_dir !== '' && strpos($path_info, $script_dir) === 0) {
    $relative_path = substr($path_info, strlen($script_dir));
} else {
    $relative_path = $path_info;
}

$segments = explode('/', trim($relative_path, '/'));

// If there's a segment that could be a short code, try to redirect
if (!empty($segments[0]) && $segments[0] !== 'index.php' && $segments[0] !== 'login.php' && $segments[0] !== 'dashboard.php' && $segments[0] !== 'api.php' && $segments[0] !== 'redirect.php' && $segments[0] !== 'assets') {
    // Set the short code for redirect.php to use
    $_GET['code'] = $segments[0];
    include 'redirect.php';
    exit;
}

// Redirect to dashboard if already logged in (only for main page access)
if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true) {
    header('Location: dashboard.php');
    exit;
}

// Otherwise, show login page
include 'login.php';
?>
