<?php
/**
 * FLOWB0T NEXUS - Enterprise Web Crawler System
 * Main Entry Point
 *
 * @version 1.0.0
 * @url https://flowb0t.com/nexus/
 */

// Error reporting for development
error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

// Set timezone
date_default_timezone_set('America/Sao_Paulo');

// Define base paths
define('NEXUS_ROOT', __DIR__);
define('NEXUS_VERSION', '1.0.0');

// Autoloader
spl_autoload_register(function ($class) {
    $prefix = 'Flowb0t\\';
    $baseDir = NEXUS_ROOT . '/';

    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        return;
    }

    $relativeClass = substr($class, $len);
    $file = $baseDir . str_replace('\\', '/', $relativeClass) . '.php';

    // Convert namespace to directory (Core -> core, Engine -> engine)
    $file = preg_replace_callback('/\/([A-Z])/', function($m) {
        return '/' . strtolower($m[1]);
    }, $file);

    if (file_exists($file)) {
        require $file;
    }
});

// Load environment variables
$envFile = NEXUS_ROOT . '/.env';
if (file_exists($envFile)) {
    $lines = file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        if (strpos($line, '#') === 0) continue;
        if (strpos($line, '=') !== false) {
            list($key, $value) = explode('=', $line, 2);
            $_ENV[trim($key)] = trim($value);
            putenv(trim($key) . '=' . trim($value));
        }
    }
}

// Start session
session_start();

// Get requested page
$page = $_GET['page'] ?? 'dashboard';
$action = $_GET['action'] ?? null;

// Security: Validate page name
$allowedPages = [
    'dashboard', 'new-job', 'jobs', 'job-detail',
    'seeds', 'results', 'exports', 'settings', 'logs'
];

if (!in_array($page, $allowedPages)) {
    $page = 'dashboard';
}

// Handle AJAX requests
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
    strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
    header('Content-Type: application/json');
    require NEXUS_ROOT . '/api/ajax_handler.php';
    exit;
}

// Page title mapping
$pageTitles = [
    'dashboard' => 'Dashboard',
    'new-job' => 'Create New Job',
    'jobs' => 'All Jobs',
    'job-detail' => 'Job Details',
    'seeds' => 'Seed Management',
    'results' => 'Results Browser',
    'exports' => 'Export Manager',
    'settings' => 'Settings',
    'logs' => 'System Logs'
];

$pageTitle = $pageTitles[$page] ?? 'Dashboard';

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($pageTitle) ?> - FLOWB0T NEXUS</title>

    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">

    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.2/font/bootstrap-icons.css">

    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js"></script>

    <!-- Custom Styles -->
    <style>
        :root {
            --nexus-primary: #6366f1;
            --nexus-secondary: #8b5cf6;
            --nexus-success: #10b981;
            --nexus-warning: #f59e0b;
            --nexus-danger: #ef4444;
            --nexus-dark: #1e1e2e;
            --nexus-darker: #11111b;
            --nexus-light: #cdd6f4;
            --nexus-surface: #313244;
        }

        body {
            background-color: var(--nexus-darker);
            color: var(--nexus-light);
            font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
        }

        /* Sidebar */
        .sidebar {
            width: 260px;
            height: 100vh;
            position: fixed;
            left: 0;
            top: 0;
            background: var(--nexus-dark);
            border-right: 1px solid var(--nexus-surface);
            z-index: 1000;
        }

        .sidebar-brand {
            padding: 1.5rem;
            border-bottom: 1px solid var(--nexus-surface);
        }

        .sidebar-brand h1 {
            font-size: 1.5rem;
            font-weight: 700;
            background: linear-gradient(135deg, var(--nexus-primary), var(--nexus-secondary));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            margin: 0;
        }

        .sidebar-brand small {
            color: #6c7086;
            font-size: 0.75rem;
        }

        .sidebar-nav {
            padding: 1rem 0;
        }

        .nav-link {
            color: var(--nexus-light);
            padding: 0.75rem 1.5rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
            transition: all 0.2s;
            border-left: 3px solid transparent;
        }

        .nav-link:hover {
            background: var(--nexus-surface);
            color: #fff;
        }

        .nav-link.active {
            background: rgba(99, 102, 241, 0.1);
            border-left-color: var(--nexus-primary);
            color: var(--nexus-primary);
        }

        .nav-link i {
            font-size: 1.1rem;
            width: 24px;
        }

        /* Main Content */
        .main-content {
            margin-left: 260px;
            padding: 2rem;
            min-height: 100vh;
        }

        /* Cards */
        .card {
            background: var(--nexus-dark);
            border: 1px solid var(--nexus-surface);
            border-radius: 12px;
        }

        .card-header {
            background: transparent;
            border-bottom: 1px solid var(--nexus-surface);
            padding: 1rem 1.25rem;
        }

        /* Stats Cards */
        .stat-card {
            background: var(--nexus-surface);
            border-radius: 12px;
            padding: 1.5rem;
            transition: transform 0.2s;
        }

        .stat-card:hover {
            transform: translateY(-2px);
        }

        .stat-card .icon {
            width: 48px;
            height: 48px;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
        }

        .stat-card .value {
            font-size: 2rem;
            font-weight: 700;
        }

        .stat-card .label {
            color: #6c7086;
            font-size: 0.875rem;
        }

        /* Progress Bars */
        .progress {
            background: var(--nexus-surface);
            border-radius: 8px;
            height: 8px;
        }

        .progress-bar {
            background: linear-gradient(90deg, var(--nexus-primary), var(--nexus-secondary));
            border-radius: 8px;
        }

        /* Tables */
        .table {
            color: var(--nexus-light);
        }

        .table thead th {
            border-bottom: 1px solid var(--nexus-surface);
            font-weight: 600;
            text-transform: uppercase;
            font-size: 0.75rem;
            letter-spacing: 0.5px;
            color: #6c7086;
        }

        .table td {
            border-bottom: 1px solid var(--nexus-surface);
            vertical-align: middle;
        }

        /* Status Badges */
        .badge-running {
            background: rgba(16, 185, 129, 0.2);
            color: var(--nexus-success);
        }

        .badge-paused {
            background: rgba(245, 158, 11, 0.2);
            color: var(--nexus-warning);
        }

        .badge-completed {
            background: rgba(99, 102, 241, 0.2);
            color: var(--nexus-primary);
        }

        .badge-failed {
            background: rgba(239, 68, 68, 0.2);
            color: var(--nexus-danger);
        }

        /* Buttons */
        .btn-primary {
            background: linear-gradient(135deg, var(--nexus-primary), var(--nexus-secondary));
            border: none;
        }

        .btn-primary:hover {
            background: linear-gradient(135deg, #5558eb, #7c4fdb);
        }

        /* Forms */
        .form-control, .form-select {
            background: var(--nexus-surface);
            border: 1px solid #45475a;
            color: var(--nexus-light);
        }

        .form-control:focus, .form-select:focus {
            background: var(--nexus-surface);
            border-color: var(--nexus-primary);
            color: var(--nexus-light);
            box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.25);
        }

        .form-control::placeholder {
            color: #6c7086;
        }

        /* Tooltips */
        .form-text {
            color: #6c7086;
            font-size: 0.8rem;
        }

        .tooltip-icon {
            color: #6c7086;
            cursor: help;
        }

        /* Log viewer */
        .log-viewer {
            background: var(--nexus-darker);
            border-radius: 8px;
            padding: 1rem;
            font-family: 'Consolas', 'Monaco', monospace;
            font-size: 0.85rem;
            max-height: 400px;
            overflow-y: auto;
        }

        .log-entry {
            padding: 0.25rem 0;
            border-bottom: 1px solid #1e1e2e;
        }

        .log-time {
            color: #6c7086;
        }

        .log-level-INFO { color: var(--nexus-primary); }
        .log-level-WARNING { color: var(--nexus-warning); }
        .log-level-ERROR { color: var(--nexus-danger); }
        .log-level-DEBUG { color: #6c7086; }

        /* Animation */
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }

        .pulse {
            animation: pulse 2s infinite;
        }
    </style>
</head>
<body>
    <!-- Sidebar -->
    <nav class="sidebar">
        <div class="sidebar-brand">
            <h1><i class="bi bi-robot"></i> FLOWB0T</h1>
            <small>NEXUS v<?= NEXUS_VERSION ?></small>
        </div>
        <div class="sidebar-nav">
            <a href="?page=dashboard" class="nav-link <?= $page === 'dashboard' ? 'active' : '' ?>">
                <i class="bi bi-grid-1x2"></i> Dashboard
            </a>
            <a href="?page=new-job" class="nav-link <?= $page === 'new-job' ? 'active' : '' ?>">
                <i class="bi bi-plus-circle"></i> New Job
            </a>
            <a href="?page=jobs" class="nav-link <?= $page === 'jobs' ? 'active' : '' ?>">
                <i class="bi bi-list-task"></i> All Jobs
            </a>
            <a href="?page=results" class="nav-link <?= $page === 'results' ? 'active' : '' ?>">
                <i class="bi bi-database"></i> Results
            </a>
            <a href="?page=exports" class="nav-link <?= $page === 'exports' ? 'active' : '' ?>">
                <i class="bi bi-download"></i> Exports
            </a>
            <a href="?page=logs" class="nav-link <?= $page === 'logs' ? 'active' : '' ?>">
                <i class="bi bi-terminal"></i> Logs
            </a>
            <a href="?page=settings" class="nav-link <?= $page === 'settings' ? 'active' : '' ?>">
                <i class="bi bi-gear"></i> Settings
            </a>
        </div>
        <div style="position: absolute; bottom: 1rem; left: 1rem; right: 1rem;">
            <div class="d-flex align-items-center gap-2 text-muted" style="font-size: 0.8rem;">
                <i class="bi bi-circle-fill text-success" style="font-size: 0.5rem;"></i>
                System Online
            </div>
        </div>
    </nav>

    <!-- Main Content -->
    <main class="main-content">
        <?php
        $pageFile = NEXUS_ROOT . '/ui/pages/' . $page . '.php';
        if (file_exists($pageFile)) {
            include $pageFile;
        } else {
            echo '<div class="alert alert-warning">Page not found: ' . htmlspecialchars($page) . '</div>';
        }
        ?>
    </main>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

    <!-- Custom JS -->
    <script>
        // NEXUS Core JavaScript
        const NEXUS = {
            // API base URL
            apiUrl: '?ajax=1',

            // Make API request
            async api(endpoint, data = {}) {
                const response = await fetch(this.apiUrl + '&endpoint=' + endpoint, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: JSON.stringify(data)
                });
                return response.json();
            },

            // Format number with commas
            formatNumber(num) {
                return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            },

            // Format time duration
            formatDuration(seconds) {
                if (seconds < 60) return seconds + 's';
                if (seconds < 3600) return Math.floor(seconds / 60) + 'm ' + (seconds % 60) + 's';
                const h = Math.floor(seconds / 3600);
                const m = Math.floor((seconds % 3600) / 60);
                return h + 'h ' + m + 'm';
            },

            // Show toast notification
            toast(message, type = 'info') {
                const toast = document.createElement('div');
                toast.className = 'toast show position-fixed bottom-0 end-0 m-3';
                toast.innerHTML = `
                    <div class="toast-header bg-${type === 'error' ? 'danger' : type}">
                        <strong class="me-auto text-white">${type.toUpperCase()}</strong>
                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="toast"></button>
                    </div>
                    <div class="toast-body">${message}</div>
                `;
                document.body.appendChild(toast);
                setTimeout(() => toast.remove(), 5000);
            },

            // Refresh page section
            async refresh(section) {
                const el = document.getElementById(section);
                if (el) {
                    el.style.opacity = '0.5';
                    const data = await this.api('get_' + section);
                    el.innerHTML = data.html;
                    el.style.opacity = '1';
                }
            }
        };

        // Initialize tooltips
        document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(el => {
            new bootstrap.Tooltip(el);
        });

        // Auto-refresh for dashboard
        <?php if ($page === 'dashboard' || $page === 'job-detail'): ?>
        setInterval(() => {
            NEXUS.refresh('active-jobs');
            NEXUS.refresh('stats');
        }, 5000);
        <?php endif; ?>
    </script>
</body>
</html>
