<?php
// Lightweight session destroy helper
function lsess_destroy() {
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    session_unset();
    session_destroy();
}

// Get current route to avoid redirect loops
$current_route = $_GET['app_route'] ?? $_GET['page'] ?? '';
$install_routes = ['install', 'onboarding', 'welcome', 'dependency_check', 'register_isp_account', 'install_process', 'register_process'];

// Special check: If trying to access onboarding and system is already installed, redirect to login
if ($current_route === 'onboarding') {
    // Include function helper
    $path = realpath(dirname(__FILE__) . '/function.php');
    if ($path) {
        include $path;
        
        // Check if system is already installed
        if (isSystemInstalled()) {
            lsess_destroy();
            header('Location: ?app_route=login');
            exit;
        }
    }
}

// Only perform checks if we're not already on an installation route
if (!in_array($current_route, $install_routes)) {
    
    // CHECK IF CONFIG FILE EXISTS (check for config.php first.
    $config_file = '';
    if (file_exists('config.php')) {
        $config_file = 'config.php';
    } else {
        // No config file found, redirect to onboarding page
        lsess_destroy();
        header('Location: ?app_route=onboarding');
        exit;
    }
    
    include $config_file;
    
    // CHECK IF DATABASE IS CONNECTED
    try {
        // Check if constants are defined
        if (!defined('MYSQL_HOST') && !defined('DB_HOST')) {
            lsess_destroy();
            header('Location: ?app_route=onboarding');
            exit;
        }
        
        // Use the appropriate constants based on which file was loaded
        $host = defined('DB_HOST') ? constant('DB_HOST') : constant('MYSQL_HOST');
        $database = defined('DB_NAME') ? constant('DB_NAME') : constant('MYSQL_DATABASE');
        $user = defined('DB_USER') ? constant('DB_USER') : constant('MYSQL_USER');
        $password = defined('DB_PASS') ? constant('DB_PASS') : constant('MYSQL_PASSWORD');
        
        $conn = new PDO(
            "mysql:host=" . $host . ";dbname=" . $database,
            $user,
            $password
        );
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        // Check if basic tables exist (installation check)
        $stmt = $conn->prepare("SHOW TABLES LIKE 'system_user'");
        $stmt->execute();
        $system_user_exists = ($stmt->rowCount() > 0);
        
        $stmt = $conn->prepare("SHOW TABLES LIKE 'subscription_plans'");
        $stmt->execute();
        $subscription_plans_exists = ($stmt->rowCount() > 0);
        
        $stmt = $conn->prepare("SHOW TABLES LIKE 'settings'");
        $stmt->execute();
        $settings_exists = ($stmt->rowCount() > 0);
        
        // If core tables don't exist, system is not installed
        if (!$system_user_exists || !$subscription_plans_exists || !$settings_exists) {
            lsess_destroy();
            header('Location: ?app_route=install');
            exit;
        }
        
        $has_subscription_tables = $subscription_plans_exists;
        
        // Store connection in global variable for use in other files
        $GLOBALS['db_connection'] = $conn;
        
    } catch (Exception $e) {
        lsess_destroy();
        header('Location: ?app_route=onboarding');
        exit;
    }
    
} else {
    // We're on an installation route, try to include config if it exists but don't redirect
    if (file_exists('config.php')) {
        include_once 'config.php';
        try {
            $host = defined('DB_HOST') ? constant('DB_HOST') : (defined('MYSQL_HOST') ? constant('MYSQL_HOST') : 'localhost');
            $database = defined('DB_NAME') ? constant('DB_NAME') : (defined('MYSQL_DATABASE') ? constant('MYSQL_DATABASE') : '');
            $user = defined('DB_USER') ? constant('DB_USER') : (defined('MYSQL_USER') ? constant('MYSQL_USER') : '');
            $password = defined('DB_PASS') ? constant('DB_PASS') : (defined('MYSQL_PASSWORD') ? constant('MYSQL_PASSWORD') : '');
            
            if (!empty($database)) {
                $conn = new PDO(
                    "mysql:host=" . $host . ";dbname=" . $database,
                    $user,
                    $password
                );
                $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                $GLOBALS['db_connection'] = $conn;
            }
        } catch (Exception $e) {
            // Connection failed, but we're on install route so continue
        }
    }
}
