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

$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
$host = $_SERVER['HTTP_HOST'];
$scriptPath = str_replace(basename($_SERVER['SCRIPT_NAME']), "", $_SERVER['SCRIPT_NAME']);
define('BASE_URL', $protocol . $host . $scriptPath);
define('BASE_RESOURCES_URL', BASE_URL . 'public/');

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

// Only check installation if we're not already on an installation route
if (!in_array($current_route, $install_routes)) {
    // CHECK IF CONFIG FILE EXISTS
    $config_file = '';
    if (file_exists('config.php')) {
        $config_file = 'config.php';
    } else {
        // Only redirect to onboarding if not already logged in
        if (!isset($_SESSION['user'])) {
            header('Location: ?app_route=onboarding');
            exit;
        }
    }

    if ($config_file) {
        include $config_file;
    }

    // CHECK DATABASE CONNECTION (only if config file exists)
    if ($config_file) {
        try {
            // Check if constants are defined
            if (!defined('MYSQL_HOST') && !defined('DB_HOST')) {
                if (!isset($_SESSION['user'])) {
                    header('Location: ?app_route=onboarding');
                    exit;
                }
            } else {
                // Use the appropriate constants based on which file was loaded
                $host_db = 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_db . ";dbname=" . $database,
                    $user,
                    $password
                );
                $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                // Check if tables exist (basic installation check)
                $stmt = $conn->prepare("SHOW TABLES LIKE 'system_user'");
                $stmt->execute();
                if ($stmt->rowCount() == 0 && !isset($_SESSION['user'])) {
                    header('Location: ?app_route=install');
                    exit;
                }
            }
        } catch (Exception $e) {
            // Only redirect if user is not logged in
            if (!isset($_SESSION['user'])) {
                header('Location: ?app_route=onboarding');
                exit;
            }
        }
    }

    // Check if user is logged in (only for protected routes)
    $protected_routes = ['dashboard', 'accounts', 'create_account', 'suspension_page', 'email_smtp_settings', 'sms_settings', 'config_editor', 'currency_settings', 'file_manager', 'cron_job', 'subscription_plans'];
    if (in_array($current_route, $protected_routes) && !isset($_SESSION['user'])) {
        header('Location: ?app_route=login');
        exit;
    }
}


//get the currency settings
// Get currency settings
try {
    $currencySettings = new \App\Controllers\CurrencySettings();
    $currentSettings = $currencySettings->getCurrentSettings();
    $availableCurrencies = $currencySettings->getAvailableCurrencies();
} catch (Exception $e) {
    $_SESSION['error'] = 'Error loading currency settings: ' . $e->getMessage();
    $currentSettings = ['currency_code' => 'USD', 'currency_symbol' => '$', 'currency_position' => 'before'];
    $availableCurrencies = [];
}

?>
<!doctype html>
<html lang="en">

<head>

    <meta charset="utf-8" />
    <title><?= COMPANY_NAME ?> - Admin Dashboard</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta data-react-helmet="true" name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    </meta>
    <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
    <meta content="Premium Multipurpose Admin & Dashboard Template" name="description" />
    <meta content="Themesbrand" name="author" />
    <!-- App favicon -->
    <link rel="shortcut icon" href="<?= BASE_RESOURCES_URL ?>assets/images/favicon.ico">

    <!-- Bootstrap Css -->
    <link href="<?= BASE_RESOURCES_URL ?>assets/css/bootstrap.min.css" id="bootstrap-style" rel="stylesheet" type="text/css" />
    <!-- Icons Css -->
    <link href="<?= BASE_RESOURCES_URL ?>assets/css/icons.min.css" rel="stylesheet" type="text/css" />
    <!-- App Css-->
    <link href="<?= BASE_RESOURCES_URL ?>assets/css/app.min.css" id="app-style" rel="stylesheet" type="text/css" />
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

</head>

<body data-topbar="dark" data-layout="horizontal">
    <?php
    foreach (['error' => 'error', 'success' => 'success'] as $key => $icon) {
        if (isset($_SESSION[$key])) {
            echo "<script>
            document.addEventListener('DOMContentLoaded', function() {
                Swal.fire({
                    icon: '$icon',
                    title: '" . ucfirst($key) . "!',
                    text: '" . addslashes($_SESSION[$key]) . "',
                    confirmButtonColor: '" . ($key === 'error' ? '#d33' : '#3085d6') . "'
                });
            });
        </script>";
            unset($_SESSION[$key]);
        }
    }
    ?>


    <!-- Begin page -->
    <div id="layout-wrapper">

        <header id="page-topbar">
            <div class="navbar-header">
                <div class="d-flex">
                    <!-- LOGO -->
                    <div class="navbar-brand-box" style="min-width: 200px; max-width: 300px;">
                        <h1 class="text-white mb-0" style="font-size: 1.2rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; line-height: 1.4;" title="<?php echo htmlspecialchars(COMPANY_NAME); ?>">
                            <?php echo htmlspecialchars(COMPANY_NAME); ?>
                        </h1>
                    </div>

                    <button type="button" class="btn btn-sm px-3 font-size-16 d-lg-none header-item waves-effect waves-light" data-bs-toggle="collapse" data-bs-target="#topnav-menu-content">
                        <i class="fa fa-fw fa-bars"></i>
                    </button>


                </div>

                <div class="d-flex">


                    <div class="dropdown d-inline-block">
                        <button type="button" class="btn header-item waves-effect" id="page-header-user-dropdown"
                            data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            <img class="rounded-circle header-profile-user" src="<?= BASE_RESOURCES_URL ?>assets/images/users/user_logo.png"
                                alt="Header Avatar">
                            <span class="d-none d-xl-inline-block ms-1" key="t-henry">
                                <?php
                                if (isset($_SESSION['user'])) {
                                    echo $_SESSION['user']['username'];
                                } else {
                                    echo "Guest";
                                }
                                ?>
                            </span>
                            <i class="mdi mdi-chevron-down d-none d-xl-inline-block"></i>
                        </button>
                        <div class="dropdown-menu dropdown-menu-end">
                            <a class="dropdown-item" href="?app_route=change_password"><i class="bx bx-lock-open font-size-16 align-middle me-1"></i> <span key="t-change_password">Change Password</span></a>
                            <a class="dropdown-item text-danger" href="?app_route=logout"><i class="bx bx-power-off font-size-16 align-middle me-1 text-danger"></i> <span key="t-logout">Logout</span></a>
                        </div>
                    </div>


                </div>
            </div>
        </header>

        <div class="topnav">
            <div class="container-fluid">
                <nav class="navbar navbar-light navbar-expand-lg topnav-menu">

                    <div class="collapse navbar-collapse" id="topnav-menu-content">
                        <ul class="navbar-nav">

                            <li class="nav-item dropdown">
                                <a class="nav-link arrow-none" href="?app_route=dashboard" id="topnav-dashboard" role="button">
                                    <i class="bx bx-home-circle me-2"></i>
                                    <span key="t-dashboards">Dashboards</span>
                                </a>
                            </li>

                            <li class="nav-item dropdown">
                                <a class="nav-link arrow-none" href="?app_route=accounts" id="topnav-accounts" role="button">
                                    <i class="bx bx-group me-2"></i>
                                    <span key="t-create_account">ISP Users</span>
                                </a> <!-- Closing </a> tag was missing -->
                            </li>

                            <li class="nav-item dropdown">
                                <a class="nav-link arrow-none" href="?app_route=create_account" id="topnav-create_account" role="button">
                                    <i class="bx bx-user-plus me-2"></i>
                                    <span key="t-create_account">Add ISP User</span>
                                </a>
                            </li>

                            <li class="nav-item dropdown">
                                <a class="nav-link arrow-none" href="?app_route=subscription_plans" id="topnav-subscription_plans" role="button">
                                    <i class="bx bx-package me-2"></i>
                                    <span key="t-subscription_plans">Subscription Plans</span>
                                </a>
                            </li>

                            <li class="nav-item dropdown">
                                <a class="nav-link arrow-none" href="?app_route=file_manager" id="topnav-file_manager" role="button">
                                    <i class="bx bx-folder me-2"></i>
                                    <span key="t-file_manager">File Manager</span>
                                </a>
                            </li>


                            <li class="nav-item dropdown">
                                <a class="nav-link dropdown-toggle arrow-none" href="#" id="topnav-more" role="button">
                                    <i class="bx bx-cog me-2"></i>
                                    <span key="t-extra-pages">Settings</span>`
                                    <div class="arrow-down"></div>
                                </a>
                                <div class="dropdown-menu" aria-labelledby="topnav-more">
                                    <div class="dropdown">
                                        <a class="dropdown-item" href="?app_route=suspension_page" id="topnav-suspension_page" role="button">
                                            <span key="t-invoices">Suspention Page</span>
                                        </a>
                                        <a class="dropdown-item" href="?app_route=email_smtp_settings" id="topnav-smtp_settings" role="button">
                                            <span key="t-invoices">Email SMTP Settings</span>
                                        </a>
                                        <a class="dropdown-item" href="?app_route=sms_settings" id="topnav-sms_settings" role="button">
                                            <span key="t-invoices">SMS Settings</span>
                                        </a>
                                        <a class="dropdown-item" href="?app_route=payment_gateways" id="topnav-payment_gateways" role="button">
                                            <span key="t-invoices">Payment Gateways</span>
                                        </a>
                                        <!-- <a class="dropdown-item" href="?app_route=system_files" id="topnav-system_files" role="button">
                                            <span key="t-invoices">System Files</span>
                                        </a> -->
                                        <a class="dropdown-item" href="?app_route=config_editor" id="topnav-config_editor" role="button">
                                            <span key="t-invoices">Config Editor</span>
                                        </a>
                                        <a class="dropdown-item" href="?app_route=currency_settings" id="topnav-currency_settings" role="button">
                                            <span key="t-invoices">Currency Settings</span>
                                        </a>
                                        <a class="dropdown-item" href="?app_route=cron_job" id="topnav-config_editor" role="button">
                                            <span key="t-invoices">Cron Job</span>
                                        </a>
                                        <a class="dropdown-item" href="?app_route=change_password" id="topnav-change_password" role="button">
                                            <span key="t-invoices">Change Password</span>
                                        </a>
                                    </div>
                                </div>
                            </li>


                            <li class="nav-item dropdown">
                                <a class="nav-link arrow-none text-danger" href="?app_route=logout" id="topnav-logout" role="button">
                                    <i class="bx bx-power-off me-2"></i>
                                    <span key="t-logout">Logout</span>
                                </a>
                            </li>








                        </ul>
                    </div>
                </nav>
            </div>
        </div>

        <div class="main-content">

            <div class="page-content">
                <div class="container-fluid">

                    <div class="row">