<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once 'db.php';
require_once 'helpers.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

// Get user info
$user_id = $_SESSION['user_id'];
$stmt = $pdo->prepare("SELECT u.*, r.name as role_name FROM users u JOIN roles r ON u.role_id = r.id WHERE u.id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

// Get institution settings
$institution_stmt = $pdo->query("SELECT * FROM institution_settings LIMIT 1");
$institution_settings = $institution_stmt->fetch(PDO::FETCH_ASSOC);

// Generate dynamic CSS variables if settings exist
$dynamic_css = '';
if ($institution_settings) {
    $dynamic_css = "
    <style>
    :root {
        --primary-blue: " . ($institution_settings['primary_color'] ?? '#27538C') . ";      /* Azul Vibrante */
        --secondary-blue: " . ($institution_settings['secondary_color'] ?? '#204473') . ";    /* Azul Oscuro */
        --accent-blue: " . ($institution_settings['accent_color'] ?? '#9BABBF') . ";       /* Gris Neutral */
        --success-green: " . ($institution_settings['success_color'] ?? '#28A745') . ";     /* Verde Estándar */
        --warning-yellow: " . ($institution_settings['warning_color'] ?? '#FFC107') . ";    /* Amarillo Estándar */
        --danger-red: " . ($institution_settings['danger_color'] ?? '#DC3545') . ";       /* Rojo Estándar */
        --info-cyan: " . ($institution_settings['info_color'] ?? '#17A2B8') . ";         /* Cian Estándar */
        --light-bg: " . ($institution_settings['light_bg_color'] ?? '#F2F2F2') . ";         /* Fondo Claro */
        --dark-text: " . ($institution_settings['dark_text_color'] ?? '#212426') . ";        /* Texto Oscuro */
        --sidebar-bg: " . ($institution_settings['sidebar_bg_color'] ?? '#27538C') . ";      /* Fondo de Barra Lateral */
        --navbar-bg: " . ($institution_settings['navbar_bg_color'] ?? '#FFFFFF') . ";       /* Fondo de Barra Superior */
        --card-bg: " . ($institution_settings['card_bg_color'] ?? '#FFFFFF') . ";           /* Fondo de Tarjetas */
        --border: " . ($institution_settings['border_color'] ?? '#E9ECEF') . ";             /* Color de Bordes */
        --shadow: " . ($institution_settings['shadow_color'] ?? 'rgba(0,0,0,0.1)') . ";    /* Color de Sombras */
        --hover-bg: " . ($institution_settings['hover_bg_color'] ?? '#F8F9FA') . ";         /* Fondo al Pasar Mouse */
        --active-bg: " . ($institution_settings['active_bg_color'] ?? '#E9ECEF') . ";       /* Fondo Activo */
        --celadon: " . ($institution_settings['secondary_color'] ?? '#204473') . ";    /* Verde Menta (para gradientes) */
        --mint-cream: " . ($institution_settings['light_bg_color'] ?? '#F2F2F2') . ";        /* Crema Menta (para fondos) */
        --cambridge-blue: " . ($institution_settings['primary_color'] ?? '#27538C') . ";     /* Alias para Primario */
        --caput-mortuum: " . ($institution_settings['dark_text_color'] ?? '#212426') . ";       /* Texto Principal Oscuro */
        --black-bean: " . ($institution_settings['dark_text_color'] ?? '#212426') . ";       /* Texto Muy Oscuro */
    }
    </style>
    ";
}

// Get role-specific data
$sidebar_items = [];
$notification_count = 0;
switch ($user['role_name']) {
    case 'administrador':
        // Get expired jobs count for notifications
        $expired_jobs_stmt = $pdo->query("SELECT COUNT(*) as count FROM jobs WHERE expiration_date < CURDATE() AND status = 'active'");
        $expired_jobs_count = $expired_jobs_stmt->fetch()['count'];

        // Get inactive graduates count
        $inactive_graduates_stmt = $pdo->query("SELECT COUNT(*) as count FROM graduates WHERE status = 'inactive'");
        $inactive_graduates_count = $inactive_graduates_stmt->fetch()['count'];

        $notification_count = $expired_jobs_count + $inactive_graduates_count;
       
        $sidebar_items = [
            ['route' => 'admin_dashboard', 'icon' => 'fas fa-tachometer-alt', 'text' => 'Dashboard'],
            ['route' => 'admin_jobs', 'icon' => 'fas fa-briefcase', 'text' => 'Ofertas Laborales'],
            ['route' => 'admin_students', 'icon' => 'fas fa-graduation-cap', 'text' => 'Alumnos'],
            ['route' => 'admin_graduates', 'icon' => 'fas fa-award', 'text' => 'Egresados'],
            ['route' => 'admin_teachers', 'icon' => 'fas fa-chalkboard-teacher', 'text' => 'Profesores'],
            ['route' => 'admin_companies', 'icon' => 'fas fa-building', 'text' => 'Empresas'],
            ['route' => 'admin_notifications', 'icon' => 'fas fa-bell', 'text' => 'Notificaciones'],
            ['route' => 'admin_send_notification', 'icon' => 'fas fa-paper-plane', 'text' => 'Enviar Notificación'],
            ['route' => 'admin_careers', 'icon' => 'fas fa-book', 'text' => 'Programas de Estudio'],
            ['route' => 'admin_upload_students', 'icon' => 'fas fa-upload', 'text' => 'Carga Masiva'],
            ['route' => 'admin_custom_reports', 'icon' => 'fas fa-file-alt', 'text' => 'Consultas y Reportes'],
            ['route' => 'admin_users', 'icon' => 'fas fa-users', 'text' => 'Usuarios'],
            // ['route' => 'admin_2fa_setup', 'icon' => 'fas fa-shield-alt', 'text' => 'Configuración 2FA'],
            ['route' => 'admin_institution_settings', 'icon' => 'fas fa-cog', 'text' => 'Configuración Institución'],

        ];
        break;
    case 'empresa':
        $sidebar_items = [
            ['route' => 'company_dashboard', 'icon' => 'fas fa-tachometer-alt', 'text' => 'Dashboard'],
            ['route' => 'company_jobs', 'icon' => 'fas fa-briefcase', 'text' => 'Mis Ofertas'],
            ['route' => 'company_add_job', 'icon' => 'fas fa-plus-circle', 'text' => 'Publicar Oferta'],


        ];
        break;
    case 'alumno':
        // Get unread notifications count
        $notif_stmt = $pdo->query("SELECT COUNT(*) as count FROM notifications WHERE user_id = {$user_id} AND is_read = 0");
        $notification_count = $notif_stmt->fetch()['count'];

        $sidebar_items = [
            ['route' => 'student_dashboard', 'icon' => 'fas fa-tachometer-alt', 'text' => 'Dashboard'],
            ['route' => 'student_jobs', 'icon' => 'fas fa-search', 'text' => 'Buscar Ofertas'],
            ['route' => 'student_applications', 'icon' => 'fas fa-file-alt', 'text' => 'Mis Postulaciones'],
            ['route' => 'student_notifications', 'icon' => 'fas fa-bell', 'text' => 'Notificaciones'],
            ['route' => 'student_languages', 'icon' => 'fas fa-language', 'text' => 'Idiomas'],
            ['route' => 'student_trainings', 'icon' => 'fas fa-graduation-cap', 'text' => 'Capacitaciones y Cursos'],
            ['route' => 'student_work_experience', 'icon' => 'fas fa-briefcase', 'text' => 'Experiencia Laboral'],
            ['route' => 'student_resume', 'icon' => 'fas fa-file-pdf', 'text' => 'Mi CV'],
        ];
        // All student routes are already using friendly URLs via route_url()
        break;
    case 'profesor':
        $sidebar_items = [
            ['route' => 'teacher_dashboard', 'icon' => 'fas fa-tachometer-alt', 'text' => 'Dashboard'],
            ['route' => 'teacher_jobs', 'icon' => 'fas fa-briefcase', 'text' => 'Ofertas Publicadas'],

        ];
        break;
    case 'egresado':
        // Get unread notifications count
        $notif_stmt = $pdo->prepare("SELECT COUNT(*) as count FROM notifications WHERE user_id = ? AND is_read = 0");
        $notif_stmt->execute([$user_id]);
        $notification_count = $notif_stmt->fetch()['count'];

        $sidebar_items = [
            ['route' => 'graduate_dashboard', 'icon' => 'fas fa-tachometer-alt', 'text' => 'Dashboard'],
            ['route' => 'graduate_jobs', 'icon' => 'fas fa-search', 'text' => 'Buscar Ofertas'],
            ['route' => 'graduate_applications', 'icon' => 'fas fa-file-alt', 'text' => 'Mis Postulaciones'],
            ['route' => 'graduate_notifications', 'icon' => 'fas fa-bell', 'text' => 'Notificaciones'],
            ['route' => 'graduate_languages', 'icon' => 'fas fa-language', 'text' => 'Idiomas'],
            ['route' => 'graduate_trainings', 'icon' => 'fas fa-graduation-cap', 'text' => 'Capacitaciones y Cursos'],
            ['route' => 'graduate_work_experience', 'icon' => 'fas fa-briefcase', 'text' => 'Experiencia Laboral'],
            ['route' => 'graduate_resume', 'icon' => 'fas fa-file-pdf', 'text' => 'Mi CV'],
        ];
        break;
}
?>
<!doctype html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title><?php echo htmlspecialchars($institution_settings['institution_name'] ?? 'Bolsa de Trabajo'); ?> - <?php echo ucfirst($user['role_name']); ?> Dashboard</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" />
    <meta name="color-scheme" content="light dark" />
    <meta name="theme-color" content="#007bff" media="(prefers-color-scheme: light)" />
    <meta name="theme-color" content="#1a1a1a" media="(prefers-color-scheme: dark)" />

    <?php if ($institution_settings && $institution_settings['favicon']): ?>
        <link rel="icon" type="image/x-icon" href="<?php echo url($institution_settings['favicon']); ?>">
        <link rel="shortcut icon" type="image/x-icon" href="<?php echo url($institution_settings['favicon']); ?>">
    <?php else: ?>
        <link rel="icon" type="image/x-icon" href="<?php echo url('assets/img/favicon.ico'); ?>">
        <link rel="shortcut icon" type="image/x-icon" href="<?php echo url('assets/img/favicon.ico'); ?>">
    <?php endif; ?>

    <?php if (function_exists('preload_critical_assets')): ?>
        <?php echo preload_critical_assets(); ?>
    <?php endif; ?>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fontsource/source-sans-3@5.0.12/index.css" integrity="sha256-tXJfXfp6Ewt1ilPzLDtQnJV4hclT9XuaZUKyUvmyr+Q=" crossorigin="anonymous" media="print" onload="this.media='all'" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/overlayscrollbars@2.11.0/styles/overlayscrollbars.min.css" crossorigin="anonymous" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.13.1/font/bootstrap-icons.min.css" crossorigin="anonymous" />

    <link rel="stylesheet" href="<?php echo url('assets/css/adminlte.css'); ?>" />
    <link rel="stylesheet" href="<?php echo url('assets/css/custom-theme.css'); ?>" />
    <?php echo $dynamic_css; ?>
    <!-- En el <head> de tu HTML -->
    <style>
    .navbar-badge {
        position: absolute;
        top: -8px;
        right: -8px;
        font-size: 0.7rem;
        padding: 0.25rem 0.4rem;
        border-radius: 10px;
        min-width: 18px;
        text-align: center;
        line-height: 1;
    }
    .user-menu .dropdown-toggle {
        position: relative;
    }
    </style>
    
    <!-- DataTables -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.7/css/dataTables.bootstrap5.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.bootstrap5.min.css">
</head>
<body class="layout-fixed sidebar-expand-lg bg-body-tertiary">
    <div class="app-wrapper">
        <!-- Header -->
        <nav class="app-header navbar navbar-expand bg-body">
            <div class="container-fluid">
                <ul class="navbar-nav">
                    <li class="nav-item">
                        <a class="nav-link" data-lte-toggle="sidebar" href="#" role="button">
                            <i class="fas fa-bars"></i>
                        </a>
                    </li>
                    <li class="nav-item d-none d-md-block">
                        <a href="#" class="nav-link"><?php echo htmlspecialchars($institution_settings['institution_name'] ?? 'Bolsa de Trabajo'); ?></a>
                    </li>
                </ul>
                <ul class="navbar-nav ms-auto">
                    <?php if (($user['role_name'] == 'administrador' || $user['role_name'] == 'alumno' || $user['role_name'] == 'egresado') && $notification_count > 0): ?>
                    <li class="nav-item">
                        <a href="<?php echo route_url($user['role_name'] . '_dashboard'); ?>" class="nav-link">
                            <i class="fas fa-bell"></i>
                            <span class="badge bg-danger"><?php echo $notification_count; ?></span>
                        </a>
                    </li>
                    <?php endif; ?>
                    <li class="nav-item dropdown user-menu">
                        <a href="#" class="nav-link dropdown-toggle" data-bs-toggle="dropdown">
                            <img src="<?php echo (isset($user['photo']) && $user['photo']) ? url($user['photo']) : url('assets/img/avatar.png'); ?>" class="user-image rounded-circle shadow" alt="User Image" />
                            <span class="d-none d-md-inline"><?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?></span>
                            
                        </a>
                        <ul class="dropdown-menu dropdown-menu-lg dropdown-menu-end">
                            <li class="user-header bg-primary text-center text-white">
                                <img src="<?php echo (isset($user['photo']) && $user['photo']) ? url($user['photo']) : url('assets/img/avatar.png'); ?>" class="rounded-circle shadow" alt="User Image" />
                                <p><?php echo htmlspecialchars($user['first_name'] . ' ' . $user['last_name']); ?> - <?php echo ucfirst($user['role_name']); ?></p>
                            </li>
                            <li class="user-footer">
                                <?php
                                $profile_url = '';
                                switch ($user['role_name']) {
                                    case 'administrador':
                                        $profile_url = route_url('admin_profile');
                                        break;
                                    case 'empresa':
                                        $profile_url = route_url('company_profile');
                                        break;
                                    case 'alumno':
                                        $profile_url = route_url('student_profile');
                                        break;
                                    case 'profesor':
                                        $profile_url = route_url('teacher_profile');
                                        break;
                                    case 'egresado':
                                        $profile_url = route_url('graduate_profile');
                                        break;
                                }
                                ?>
                                <a href="<?php echo $profile_url; ?>" class="btn btn-default btn-flat">Perfil</a>
                                <a href="<?php echo route_url('logout'); ?>" class="btn btn-default btn-flat float-end">Cerrar sesión</a>
                            </li>
                        </ul>
                    </li>
                </ul>
            </div>
        </nav>

        <!-- Sidebar -->
        <aside class="app-sidebar shadow" data-bs-theme="dark" style="background-color: var(--primary-blue) !important;">
            <div class="sidebar-brand">
                <a href="../index.php" class="brand-link">
                    <?php if ($institution_settings && $institution_settings['institution_logo']): ?>
                        <img src="<?php echo url($institution_settings['institution_logo']); ?>" alt="Institution Logo" class="brand-image opacity-75 shadow" />
                    <?php else: ?>
                        <img src="<?php echo url('assets/img/logo.png'); ?>" alt="AdminLTE Logo" class="brand-image opacity-75 shadow" />
                    <?php endif; ?>
                    <span class="brand-text fw-light"><?php echo htmlspecialchars($institution_settings['institution_name'] ?? 'Bolsa de Trabajo'); ?></span>
                </a>
            </div>
            <div class="sidebar-wrapper">
                <nav class="mt-2">
                    <ul class="nav sidebar-menu flex-column" data-lte-toggle="treeview" role="navigation" aria-label="Main navigation" data-accordion="false" id="navigation">
                        <?php foreach ($sidebar_items as $item): ?>
                        <li class="nav-item">
                            <a href="<?php echo route_url($item['route']); ?>" class="nav-link">
                                <i class="nav-icon <?php echo $item['icon']; ?>"></i>
                                <p><?php echo $item['text']; ?></p>
                            </a>
                        </li>
                        <?php endforeach; ?>
                    </ul>
                </nav>
            </div>
        </aside>

        <!-- Main Content -->
        <main class="app-main">
            <div class="app-content-header">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-sm-6">
                            <h3 class="mb-0"><?php echo isset($page_title) ? $page_title : 'Dashboard'; ?></h3>
                        </div>
                        <div class="col-sm-6">
                            <ol class="breadcrumb float-sm-end">
                                <li class="breadcrumb-item"><a href="#">Home</a></li>
                                <li class="breadcrumb-item active" aria-current="page"><?php echo isset($page_title) ? $page_title : 'Dashboard'; ?></li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>
            <div class="app-content">
                <div class="container-fluid">
                    <?php
                    // Content will be included here
                    if (isset($content)) {
                        echo $content;
                    } else {
                        echo '<p>Welcome to Bolsa de Trabajo</p>';
                    }
                    ?>
                </div>
            </div>
        </main>

        <!-- Footer -->
        <footer class="app-footer">
            <div class="float-end d-none d-sm-inline">
                <?php if ($institution_settings && $institution_settings['contact_person']): ?>
                    Contacto: <?php echo htmlspecialchars($institution_settings['contact_person']); ?>
                    <?php if ($institution_settings['contact_email']): ?>
                        - <a href="mailto:<?php echo htmlspecialchars($institution_settings['contact_email']); ?>"><?php echo htmlspecialchars($institution_settings['contact_email']); ?></a>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
            <strong>Copyright &copy; 2025 <?php echo htmlspecialchars($institution_settings['institution_name'] ?? 'Bolsa de Trabajo'); ?>.</strong> All rights reserved.
        </footer>
    </div>

    <!-- Scripts -->
    <script src="https://cdn.jsdelivr.net/npm/overlayscrollbars@2.11.0/browser/overlayscrollbars.browser.es6.min.js" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.min.js" crossorigin="anonymous"></script>
    <script src="<?php echo url('assets/js/adminlte.js'); ?>"></script>
    <!-- DataTables -->
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.7/js/dataTables.bootstrap5.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script>
    <script src="https://cdn.datatables.net/responsive/2.5.0/js/responsive.bootstrap5.min.js"></script>
    <script>
        const SELECTOR_SIDEBAR_WRAPPER = '.sidebar-wrapper';
        const Default = {
            scrollbarTheme: 'os-theme-light',
            scrollbarAutoHide: 'leave',
            scrollbarClickScroll: true,
        };
        document.addEventListener('DOMContentLoaded', function () {
            const sidebarWrapper = document.querySelector(SELECTOR_SIDEBAR_WRAPPER);
            const isMobile = window.innerWidth <= 992;
            if (sidebarWrapper && typeof OverlayScrollbarsGlobal !== 'undefined' && OverlayScrollbarsGlobal.OverlayScrollbars !== undefined && !isMobile) {
                OverlayScrollbarsGlobal.OverlayScrollbars(sidebarWrapper, {
                    scrollbars: {
                        theme: Default.scrollbarTheme,
                        autoHide: Default.scrollbarAutoHide,
                        clickScroll: Default.scrollbarClickScroll,
                    },
                });
            }
        });
    </script>

    <!-- DataTables Initialization -->
    <script>
        $(document).ready(function() {
            $('table.table:not(.no-datatable)').DataTable({
                responsive: true,
                pageLength: 10,
                language: {
                    url: '//cdn.datatables.net/plug-ins/1.13.7/i18n/es-ES.json'
                },
                columnDefs: [
                    { orderable: false, targets: -1 } // Disable sorting on last column (actions)
                ]
            });
        });
    </script>

    <!-- Page-specific scripts -->
    <?php if (isset($scripts) && !empty($scripts)): ?>
        <?php echo $scripts; ?>
    <?php endif; ?>
</body>
</html>