<?php
require_once 'vendor/autoload.php';
require_once 'app/include/db_safe.php';


use Core\RouteHandler;
use Core\Autoloader;

// Start session if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

Autoloader::register();

// Get current route
$current_route = $_GET['app_route'] ?? '';

// Define installation routes that don't require full installation
$install_routes = ['onboarding', 'welcome', 'dependency_check', 'register_isp_account', 'install', 'install_process', 'register_process'];

// Check installation status only if not on installation routes
if (!in_array($current_route, $install_routes)) {
    // Special handling for login routes - allow if config exists
    if ($current_route === 'login' || $current_route === 'login_process') {
        if (!configExists()) {
            header('Location: ?app_route=onboarding');
            exit;
        }
        // For login routes, we only check config existence, not full installation
        // This prevents redirect loops after successful installation
    } elseif ($current_route === 'dashboard' && isset($_SESSION['user'])) {
        // Allow dashboard access if user is logged in and config exists
        if (!configExists()) {
            header('Location: ?app_route=onboarding');
            exit;
        }
        // Skip installation check for logged-in users accessing dashboard
    } else {
        // For all other routes, do full installation check
        if (!configExists()) {
            header('Location: ?app_route=onboarding');
            exit;
        }
        
        if (!isInstalled()) {
            header('Location: ?app_route=onboarding');
            exit;
        }
    }
}

// If no route specified, determine appropriate default
if (empty($current_route)) {
    if (!configExists()) {
        header('Location: ?app_route=onboarding');
        exit;
    } elseif (!isInstalled()) {
        header('Location: ?app_route=onboarding');
        exit;
    } else {
        // Check if user is logged in
        if (isset($_SESSION['user'])) {
            header('Location: ?app_route=dashboard');
            exit;
        } else {
            header('Location: ?app_route=login');
            exit;
        }
    }
}


//include config file
if (file_exists('config.php')) {
    include 'config.php';
}
// Define the routes
$router = new RouteHandler();
include 'app/routes/web.php';

// Process the route
$router->handleRequest();
