<?php
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
require_once dirname(__DIR__) . '/includes/helpers.php'; // Usar ruta relativa para inicializar helpers
require_once BASE_PATH . '/includes/db.php';
require_once BASE_PATH . '/includes/auth.php';

check_role('administrador');

// Ejecutar monitoreo de salud del sistema al cargar el dashboard del administrador
monitor_system_health();

$user = get_logged_in_user();

// Iniciar perfilado de rendimiento (solo si la clase existe)
if (class_exists('PerformanceProfiler')) {
    PerformanceProfiler::start_profiling('dashboard_load');
}

// Obtener estadísticas en caché para mejor rendimiento
if (function_exists('get_user_stats_cached')) {
    $stats = get_user_stats_cached();
} else {
    // Fallback si la función no existe
    $stats = [['total_companies' => 0, 'total_students' => 0, 'total_graduates' => 0, 'total_teachers' => 0]];
}
$total_companies = $stats[0]['total_companies'] ?? 0;
$total_students = $stats[0]['total_students'] ?? 0;
$total_graduates = $stats[0]['total_graduates'] ?? 0;
$total_teachers = $stats[0]['total_teachers'] ?? 0;

// Obtener trabajos expirados
$expired_jobs = $pdo->query("SELECT j.id, j.title, c.company_name, j.expiration_date FROM jobs j JOIN companies c ON j.company_id = c.id WHERE j.expiration_date < CURDATE() AND j.status = 'active' ORDER BY j.expiration_date DESC")->fetchAll(PDO::FETCH_ASSOC);

// Obtener egresados inactivos
$inactive_graduates = $pdo->query("SELECT u.first_name, u.last_name, g.dni FROM graduates g JOIN users u ON g.user_id = u.id WHERE g.status = 'inactive' ORDER BY u.created_at DESC")->fetchAll(PDO::FETCH_ASSOC);

// Get applications by month for the last 12 months
$applications_by_month = $pdo->query("SELECT DATE_FORMAT(applied_date, '%Y-%m') as month, COUNT(*) as count FROM applications WHERE applied_date >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH) GROUP BY DATE_FORMAT(applied_date, '%Y-%m') ORDER BY month");
$applications_by_month_data = $applications_by_month->fetchAll(PDO::FETCH_ASSOC);

// Get applications by career for monitoring
$applications_by_career = $pdo->query("SELECT c.name as career_name, COUNT(a.id) as app_count FROM applications a JOIN jobs j ON a.job_id = j.id LEFT JOIN careers c ON j.career_id = c.id GROUP BY j.career_id ORDER BY app_count DESC LIMIT 10");
$applications_by_career_data = $applications_by_career->fetchAll(PDO::FETCH_ASSOC);

// Get recent applications timeline
$recent_applications = $pdo->query("SELECT DATE(a.applied_date) as date, COUNT(a.id) as count FROM applications a WHERE a.applied_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY) GROUP BY DATE(a.applied_date) ORDER BY date");
$recent_applications_data = $recent_applications->fetchAll(PDO::FETCH_ASSOC);

// Get user status distribution (only students and graduates)
$user_status = $pdo->query("SELECT
    SUM(CASE WHEN role_id = (SELECT id FROM roles WHERE name = 'alumno') THEN 1 ELSE 0 END) as students,
    SUM(CASE WHEN role_id = (SELECT id FROM roles WHERE name = 'egresado') THEN 1 ELSE 0 END) as graduates
FROM users");
$user_status_data = $user_status->fetch(PDO::FETCH_ASSOC);

// Get gender distribution of students only
$gender_distribution = $pdo->query("SELECT
    CASE
        WHEN s.gender = 'masculino' THEN 'Masculino'
        WHEN s.gender = 'femenino' THEN 'Femenino'
        ELSE 'No especificado'
    END as gender,
    COUNT(*) as count
FROM students s
WHERE s.gender IS NOT NULL
GROUP BY s.gender
ORDER BY count DESC");
$gender_distribution_data = $gender_distribution->fetchAll(PDO::FETCH_ASSOC);

// Get gender distribution of graduates only
$graduates_gender_distribution = $pdo->query("SELECT
    CASE
        WHEN g.gender = 'masculino' THEN 'Masculino'
        WHEN g.gender = 'femenino' THEN 'Femenino'
        ELSE 'No especificado'
    END as gender,
    COUNT(*) as count
FROM graduates g
WHERE g.gender IS NOT NULL
GROUP BY g.gender
ORDER BY count DESC");
$graduates_gender_distribution_data = $graduates_gender_distribution->fetchAll(PDO::FETCH_ASSOC);

// Get applications by weekday
$applications_by_weekday = $pdo->query("SELECT DAYOFWEEK(applied_date) as weekday, COUNT(*) as count FROM applications WHERE applied_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY) GROUP BY DAYOFWEEK(applied_date) ORDER BY weekday");
$applications_by_weekday_data = $applications_by_weekday->fetchAll(PDO::FETCH_ASSOC);

// Get top jobs by applications
$top_jobs_by_applications = $pdo->query("SELECT j.title, c.company_name, COUNT(a.id) as application_count FROM jobs j JOIN companies c ON j.company_id = c.id LEFT JOIN applications a ON j.id = a.job_id GROUP BY j.id ORDER BY application_count DESC LIMIT 5");
$top_jobs_by_applications_data = $top_jobs_by_applications->fetchAll(PDO::FETCH_ASSOC);

// Get top jobs by views
$top_jobs_by_views = $pdo->query("SELECT j.title, c.company_name, j.view_count FROM jobs j JOIN companies c ON j.company_id = c.id ORDER BY j.view_count DESC LIMIT 5");
$top_jobs_by_views_data = $top_jobs_by_views->fetchAll(PDO::FETCH_ASSOC);


$page_title = 'Dashboard del Administrador';

// Notificaciones para trabajos expirados y egresados inactivos
$notifications = '';
if (count($expired_jobs) > 0) {
    $notifications .= '<div class="alert alert-warning alert-dismissible fade show" role="alert">
        <strong><i class="fas fa-exclamation-triangle"></i> Ofertas Expiradas:</strong> Hay ' . count($expired_jobs) . ' oferta(s) de trabajo que han expirado y aún están activas.<br>';
    foreach ($expired_jobs as $job) {
        $notifications .= '<a href="view-job.php?id=' . $job['id'] . '" class="alert-link">' . htmlspecialchars($job['title']) . ' (' . htmlspecialchars($job['company_name']) . ')</a> - Expiró el ' . date('M d, Y', strtotime($job['expiration_date'])) . '<br>';
    }
    $notifications .= '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>';
}

if (count($inactive_graduates) > 0) {
    $notifications .= '<div class="alert alert-info alert-dismissible fade show" role="alert">
        <strong><i class="fas fa-user-graduate"></i> Egresados Inactivos:</strong> Hay ' . count($inactive_graduates) . ' egresado(s) esperando activación.<br>';
    foreach ($inactive_graduates as $graduate) {
        $notifications .= htmlspecialchars($graduate['first_name'] . ' ' . $graduate['last_name']) . ' (DNI: ' . htmlspecialchars($graduate['dni'] ?? '') . ')<br>';
    }
    $notifications .= '<a href="graduates.php" class="btn btn-primary btn-sm">Gestionar Egresados</a>
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>';
}

$content = $notifications . '
<div class="row">

    <div class="col-lg-3 col-6">
        <a href="companies.php" class="text-decoration-none">
            <div class="small-box text-bg-info">
                <div class="inner">
                    <h3>' . $total_companies . '</h3>
                    <p>Empresas <i class="fas fa-external-link-alt fa-xs"></i></p>
                </div>
                <div class="icon">
                    <i class="ion ion-briefcase"></i>
                </div>
            </div>
        </a>
    </div>
    <div class="col-lg-3 col-6">
        <a href="students.php" class="text-decoration-none">
            <div class="small-box text-bg-warning">
                <div class="inner">
                    <h3>' . $total_students . '</h3>
                    <p>Alumnos <i class="fas fa-external-link-alt fa-xs"></i></p>
                </div>
                <div class="icon">
                    <i class="ion ion-university"></i>
                </div>
            </div>
        </a>
    </div>
    <div class="col-lg-3 col-6">
        <a href="graduates.php" class="text-decoration-none">
            <div class="small-box text-bg-success">
                <div class="inner">
                    <h3>' . $total_graduates . '</h3>
                    <p>Egresados <i class="fas fa-external-link-alt fa-xs"></i></p>
                </div>
                <div class="icon">
                    <i class="ion ion-android-person"></i>
                </div>
            </div>
        </a>
    </div>
    <div class="col-lg-3 col-6">
        <a href="teachers.php" class="text-decoration-none">
            <div class="small-box text-bg-danger">
                <div class="inner">
                    <h3 class="">' . $total_teachers . '</h3>
                    <p>Profesores <i class="fas fa-external-link-alt fa-xs"></i></p>
                </div>
                <div class="icon">
                    <i class="ion ion-ios-people text-dark"></i>
                </div>
            </div>
        </a>
    </div>
</div>
<div class="row">
    <div class="col-lg-6">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Postulantes por Meses</h3>
            </div>
            <div class="card-body">
                <canvas id="applicationsByMonthChart" style="height: 300px;"></canvas>
            </div>
        </div>
    </div>
    <div class="col-lg-6">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Total de Postulantes por Programa</h3>
            </div>
            <div class="card-body">
                <canvas id="applicationsByCareerChart" style="height: 300px;"></canvas>
            </div>
        </div>
    </div>
</div>
<div class="row">
    <div class="col-lg-6">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Tendencia de Postulaciones (Últimos 30 días)</h3>
            </div>
            <div class="card-body">
                <canvas id="applicationsTrendChart" style="height: 300px;"></canvas>
            </div>
        </div>
    </div>
    <div class="col-lg-6">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Estado de Usuarios</h3>
            </div>
            <div class="card-body">
                <canvas id="userStatusChart" style="height: 300px;"></canvas>
            </div>
        </div>
    </div>
</div>
<div class="row">
    <div class="col-lg-6">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Top Ofertas por Postulantes</h3>
            </div>
            <div class="card-body">
                <canvas id="topJobsByApplicationsChart" style="height: 300px;"></canvas>
            </div>
        </div>
    </div>
    <div class="col-lg-6">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Egresados por Género</h3>
            </div>
            <div class="card-body">
                <canvas id="graduatesGenderChart" style="height: 300px;"></canvas>
            </div>
        </div>
    </div>
</div>
<div class="row">
    <div class="col-lg-6">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Top Ofertas por Vistas</h3>
            </div>
            <div class="card-body">
                <canvas id="topJobsByViewsChart" style="height: 300px;"></canvas>
            </div>
        </div>
    </div>
    <div class="col-lg-6">
        <div class="card">
            <div class="card-header">
                <h3 class="card-title">Alumnos por Género</h3>
            </div>
            <div class="card-body">
                <canvas id="genderDistributionChart" style="height: 300px;"></canvas>
            </div>
        </div>
    </div>
</div>

<style>
/* Estilos Responsivos Mejorados */
@media (max-width: 767.98px) {
    .small-box {
        margin-bottom: 1rem;
    }
    .small-box .inner h3 {
        font-size: 1.8rem;
        margin-bottom: 0.2rem;
    }

    .small-box .inner p {
        font-size: 0.9rem;
        margin-bottom: 0;
    }

    .small-box .icon {
        font-size: 2rem;
        top: 0.5rem;
        right: 0.5rem;
    }
}

/* Better spacing for dashboard elements */
.dashboard-row {
    margin-bottom: 1.5rem;
}

@media (max-width: 767.98px) {
    .dashboard-row {
        margin-bottom: 1rem;
    }
}

/* Improve card shadows and spacing */
.card {
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    border: 2px solid #27538c;
    margin-bottom: 1rem;
}

@media (max-width: 767.98px) {
    .card {
        margin-bottom: 0.75rem;
    }
}

/* Better button and link spacing */
.btn {
    margin: 0.125rem;
}

/* Improve table responsiveness if any */
.table-responsive {
    border: none;
}

/* Custom scrollbar for better mobile experience */
::-webkit-scrollbar {
    width: 6px;
    height: 6px;
}

::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}

::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

/* Additional responsive improvements */
@media (max-width: 991.98px) {
    .col-lg-3 {
        flex: 0 0 50%;
        max-width: 50%;
    }
}

@media (max-width: 767.98px) {
    .col-lg-6 {
        flex: 0 0 100%;
        max-width: 100%;
    }
}

/* Improve text readability on small screens */
@media (max-width: 575.98px) {
    body {
        font-size: 0.9rem;
    }

    h1, h2, h3, h4, h5, h6 {
        font-size: 1.1em;
    }
}

/* Better touch targets for mobile */
@media (max-width: 767.98px) {
    .btn {
        min-height: 44px;
        padding: 0.5rem 1rem;
    }

    .small-box {
        cursor: pointer;
        transition: transform 0.2s ease;
    }

    .small-box:hover {
        transform: translateY(-2px);
    }
}

/* Larger icons for small-box */
.small-box .icon {
    font-size: 3rem !important;
    top: 50% !important;
    transform: translateY(-50%);
    opacity: 0.3;
    right: 1rem !important;
}
</style>';

// Finalizar perfilado de rendimiento (solo si la clase existe)
if (class_exists('PerformanceProfiler')) {
    PerformanceProfiler::end_profiling('dashboard_load');
}

// Scripts específicos de la página
$scripts = '<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function() {
    // Applications by Month Chart
    const applicationsByMonthCtx = document.getElementById("applicationsByMonthChart").getContext("2d");
    const applicationsByMonthData = ' . json_encode($applications_by_month_data) . ';
    new Chart(applicationsByMonthCtx, {
        type: "bar",
        data: {
            labels: applicationsByMonthData.map(item => {
                const date = new Date(item.month + "-01");
                return date.toLocaleDateString("es-ES", { year: "numeric", month: "short" });
            }),
            datasets: [{
                label: "Postulantes",
                data: applicationsByMonthData.map(item => item.count),
                backgroundColor: "#007bff",
                borderColor: "#007bff",
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true,
                    ticks: {
                        stepSize: 1
                    }
                }
            },
            plugins: {
                legend: {
                    display: false
                }
            }
        }
    });

    // Applications by Career Chart
    const applicationsByCareerCtx = document.getElementById("applicationsByCareerChart").getContext("2d");
    const applicationsByCareerData = ' . json_encode($applications_by_career_data) . ';
    new Chart(applicationsByCareerCtx, {
        type: "bar",
        data: {
            labels: applicationsByCareerData.map(item => item.career_name || "General"),
            datasets: [{
                label: "Applications",
                data: applicationsByCareerData.map(item => item.app_count),
                backgroundColor: "#17a2b8",
                borderColor: "#17a2b8",
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });

    // Applications Trend Chart
    const applicationsTrendCtx = document.getElementById("applicationsTrendChart").getContext("2d");
    const applicationsTrendData = ' . json_encode($recent_applications_data) . ';
    new Chart(applicationsTrendCtx, {
        type: "line",
        data: {
            labels: applicationsTrendData.map(item => new Date(item.date).toLocaleDateString()),
            datasets: [{
                label: "Postulaciones Diarias",
                data: applicationsTrendData.map(item => item.count),
                borderColor: "#28a745",
                backgroundColor: "rgba(40, 167, 69, 0.1)",
                tension: 0.4,
                fill: true
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });

    // User Status Chart
    const userStatusCtx = document.getElementById("userStatusChart").getContext("2d");
    const userStatusData = ' . json_encode($user_status_data) . ';
    new Chart(userStatusCtx, {
        type: "doughnut",
        data: {
            labels: ["Alumnos", "Egresados"],
            datasets: [{
                data: [userStatusData.students, userStatusData.graduates],
                backgroundColor: ["#ffc107", "#28a745"],
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: "bottom"
                }
            }
        }
    });

    // Gráfico de Distribución de Género de Egresados
    const graduatesGenderCtx = document.getElementById("graduatesGenderChart").getContext("2d");
    const graduatesGenderData = ' . json_encode($graduates_gender_distribution_data) . ';
    const maleGradCount = graduatesGenderData.find(function(item) { return item.gender === "Masculino"; });
    const femaleGradCount = graduatesGenderData.find(function(item) { return item.gender === "Femenino"; });

    new Chart(graduatesGenderCtx, {
        type: "pie",
        data: {
            labels: ["Masculino", "Femenino"],
            datasets: [{
                data: [
                    maleGradCount ? maleGradCount.count : 0,
                    femaleGradCount ? femaleGradCount.count : 0
                ],
                backgroundColor: ["#28a745", "#dc3545"],
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: "bottom"
                }
            }
        }
    });

    // Gender Distribution Chart
    const genderDistributionCtx = document.getElementById("genderDistributionChart").getContext("2d");
    const genderDistributionData = ' . json_encode($gender_distribution_data) . ';
    const maleCount = genderDistributionData.find(function(item) { return item.gender === "Masculino"; });
    const femaleCount = genderDistributionData.find(function(item) { return item.gender === "Femenino"; });

    new Chart(genderDistributionCtx, {
        type: "pie",
        data: {
            labels: ["Masculino", "Femenino"],
            datasets: [{
                data: [
                    maleCount ? maleCount.count : 0,
                    femaleCount ? femaleCount.count : 0
                ],
                backgroundColor: ["#007bff", "#dc3545"],
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: "bottom"
                }
            }
        }
    });

    // Top Jobs by Applications Chart
    const topJobsByApplicationsCtx = document.getElementById("topJobsByApplicationsChart").getContext("2d");
    const topJobsByApplicationsData = ' . json_encode($top_jobs_by_applications_data) . ';
    const colors = ["#FF6384", "#36A2EB", "#FFCE56", "#4BC0C0", "#9966FF"];

    new Chart(topJobsByApplicationsCtx, {
        type: "bar",
        data: {
            labels: topJobsByApplicationsData.map(item => item.title.length > 30 ? item.title.substring(0, 30) + "..." : item.title),
            datasets: [{
                label: "Postulantes",
                data: topJobsByApplicationsData.map(item => item.application_count),
                backgroundColor: topJobsByApplicationsData.map((item, index) => colors[index % colors.length]),
                borderColor: topJobsByApplicationsData.map((item, index) => colors[index % colors.length]),
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            indexAxis: "y",
            scales: {
                x: {
                    beginAtZero: true,
                    ticks: {
                        stepSize: 1
                    }
                }
            },
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    callbacks: {
                        title: function(context) {
                            const dataIndex = context[0].dataIndex;
                            return topJobsByApplicationsData[dataIndex].title + " - " + topJobsByApplicationsData[dataIndex].company_name;
                        }
                    }
                }
            }
        }
    });

    // Top Jobs by Views Chart
    const topJobsByViewsCtx = document.getElementById("topJobsByViewsChart").getContext("2d");
    const topJobsByViewsData = ' . json_encode($top_jobs_by_views_data) . ';
    const viewColors = ["#FF6384", "#36A2EB", "#FFCE56", "#4BC0C0", "#9966FF"];

    new Chart(topJobsByViewsCtx, {
        type: "bar",
        data: {
            labels: topJobsByViewsData.map(item => item.title.length > 30 ? item.title.substring(0, 30) + "..." : item.title),
            datasets: [{
                label: "Vistas",
                data: topJobsByViewsData.map(item => item.view_count),
                backgroundColor: topJobsByViewsData.map((item, index) => viewColors[index % viewColors.length]),
                borderColor: topJobsByViewsData.map((item, index) => viewColors[index % viewColors.length]),
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            indexAxis: "y",
            scales: {
                x: {
                    beginAtZero: true,
                    ticks: {
                        stepSize: 1
                    }
                }
            },
            plugins: {
                legend: {
                    display: false
                },
                tooltip: {
                    callbacks: {
                        title: function(context) {
                            const dataIndex = context[0].dataIndex;
                            return topJobsByViewsData[dataIndex].title + " - " + topJobsByViewsData[dataIndex].company_name;
                        }
                    }
                }
            }
        }
    });
});
</script>' . ($page_specific_scripts ?? '');

// El layout imprimirá la variable $scripts si está configurado para ello.
include BASE_PATH . '/includes/layout.php';
