<?php
/**
 * Reportes y Estadísticas - Backoffice administrativo
 * Turpial Airlines, C.A.
 */

$page_title = 'Reportes y Estadísticas';

require_once '../includes/functions.php';
require_once '../includes/JobVacancy.php';
require_once '../includes/Application.php';
require_once '../includes/Division.php';
require_once '../includes/User.php';

// Verificar autenticación
requireLogin();

// Instanciar clases
$jobVacancy = new JobVacancy();
$application = new Application();
$division = new Division();
$user = new User();

// Obtener datos para reportes
$job_stats = $jobVacancy->getStats();
$app_stats = $application->getStats();

// Reportes específicos
$monthly_applications = $application->getMonthlyStats();
$top_vacancies = $jobVacancy->getTopVacancies(10);
$recent_applications = $application->getRecentApplications(10);
$applications_by_status = $application->getApplicationsByStatus();

// Calcular estadísticas de usuarios
$users_list = $user->getAllUsers();
$total_users = count($users_list);
$active_users = 0;
$admin_users = 0;

/*
foreach ($users_list as $user_data) {
    if ($user_data['is_active'] == 1) {
        $active_users++;
    }
    if ($user_data['role'] == 'admin') {
        $admin_users++;
    }
}

*/









// Asegurar que todas las claves necesarias existan en job_stats
if (!isset($job_stats['active_vacancies'])) {
    $job_stats['active_vacancies'] = 0;
}
if (!isset($job_stats['inactive_vacancies'])) {
    $job_stats['inactive_vacancies'] = 0;
}
if (!isset($job_stats['pending_applications'])) {
    $job_stats['pending_applications'] = 0;
}

include 'includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2 class="mb-0">
        <i class="fas fa-chart-line me-2"></i>Reportes y Estadísticas
    </h2>
    <div class="btn-group" role="group">
        <button type="button" class="btn btn-outline-primary" onclick="exportReport('pdf')">
            <i class="fas fa-file-pdf me-2"></i>Exportar PDF
        </button>
        <button type="button" class="btn btn-outline-success" onclick="exportReport('excel')">
            <i class="fas fa-file-excel me-2"></i>Exportar Excel
        </button>
    </div>
</div>

<!-- Resumen Ejecutivo -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card shadow">
            <div class="card-header">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-chart-pie me-2"></i>Resumen Ejecutivo
                </h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-xl-3 col-md-6 mb-3">
                        <div class="card border-left-primary h-100 py-2">
                            <div class="card-body">
                                <div class="row no-gutters align-items-center">
                                    <div class="col mr-2">
                                        <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                            Total Vacantes
                                        </div>
                                        <div class="h5 mb-0 font-weight-bold text-gray-800">
                                            <?php echo number_format($job_stats['total_vacancies']); ?>
                                        </div>
                                    </div>
                                    <div class="col-auto">
                                        <i class="fas fa-briefcase fa-2x text-gray-300"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-xl-3 col-md-6 mb-3">
                        <div class="card border-left-success h-100 py-2">
                            <div class="card-body">
                                <div class="row no-gutters align-items-center">
                                    <div class="col mr-2">
                                        <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                            Total Aplicaciones
                                        </div>
                                        <div class="h5 mb-0 font-weight-bold text-gray-800">
                                            <?php echo number_format($app_stats['total_applications']); ?>
                                        </div>
                                    </div>
                                    <div class="col-auto">
                                        <i class="fas fa-file-alt fa-2x text-gray-300"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-xl-3 col-md-6 mb-3">
                        <div class="card border-left-warning h-100 py-2">
                            <div class="card-body">
                                <div class="row no-gutters align-items-center">
                                    <div class="col mr-2">
                                        <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                                            Divisiones Activas
                                        </div>
                                        <div class="h5 mb-0 font-weight-bold text-gray-800">
                                            <?php echo count($job_stats['vacancies_by_division']); ?>
                                        </div>
                                    </div>
                                    <div class="col-auto">
                                        <i class="fas fa-building fa-2x text-gray-300"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-xl-3 col-md-6 mb-3">
                        <div class="card border-left-info h-100 py-2">
                            <div class="card-body">
                                <div class="row no-gutters align-items-center">
                                    <div class="col mr-2">
                                        <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                                            Usuarios del Sistema
                                        </div>
                                        <div class="h5 mb-0 font-weight-bold text-gray-800">
                                            <?php echo number_format($total_users); ?>
                                        </div>
                                    </div>
                                    <div class="col-auto">
                                        <i class="fas fa-users fa-2x text-gray-300"></i>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Gráficos y estadísticas -->
<div class="row mb-4">
    <!-- Aplicaciones mensuales -->
    <div class="col-xl-8 col-lg-7">
        <div class="card shadow mb-4">
            <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-chart-area me-2"></i>Aplicaciones por Mes (Últimos 12 meses)
                </h6>
            </div>
            <div class="card-body">
                <canvas id="monthlyApplicationsChart" height="100"></canvas>
            </div>
        </div>
    </div>
    
    <!-- Estados de aplicaciones -->
    <div class="col-xl-4 col-lg-5">
        <div class="card shadow mb-4">
            <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-chart-pie me-2"></i>Estados de Aplicaciones
                </h6>
            </div>
            <div class="card-body">
                <canvas id="applicationStatusChart" height="200"></canvas>
            </div>
        </div>
    </div>
</div> 

<!-- Vacantes más populares -->
<div class="row mb-4">
    <div class="col-xl-6 col-lg-6">
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-star me-2"></i>Top 10 Vacantes Más Populares
                </h6>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>Vacante</th>
                                <th>División</th>
                                <th>Aplicaciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($top_vacancies as $vacancy): ?>
                            <tr>
                                <td>
                                    <strong><?php echo escape(substr($vacancy['title'], 0, 40)); ?></strong>
                                    <?php if (strlen($vacancy['title']) > 40): ?>..<?php endif; ?>
                                </td>
                                <td>
                                    <span class="badge bg-primary"><?php echo escape($vacancy['division_name']); ?></span>
                                </td>
                                <td>
                                    <strong><?php echo number_format($vacancy['applications_count']); ?></strong>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Aplicaciones recientes -->
    <div class="col-xl-6 col-lg-6">
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-clock me-2"></i>Aplicaciones Recientes
                </h6>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>Nombre</th>
                                <th>Email</th>
                                <th>Vacante</th>
                                <th>Fecha</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($recent_applications as $app): ?>
                            <tr>
                                <td>
                                    <strong><?php echo escape($app['full_name']); ?></strong>
                                </td>
                                <td>
                                    <small><?php echo escape($app['email']); ?></small>
                                </td>
                                <td>
                                    <small><?php echo escape(substr($app['job_title'], 0, 30)); ?></small>
                                    <?php if (strlen($app['job_title']) > 30): ?>..<?php endif; ?>
                                </td>
                                <td>
                                    <small class="text-muted">
                                        <?php echo date('d/m/Y', strtotime($app['application_date'])); ?>
                                    </small>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Estadísticas por división -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card shadow">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-chart-bar me-2"></i>Estadísticas por División
                </h6>
            </div>
            <div class="card-body">
                <canvas id="divisionStatsChart" height="80"></canvas>
            </div>
        </div>
    </div>
</div>

<!-- Métricas detalladas -->
<div class="row">
    <div class="col-12">
        <div class="card shadow">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">
                    <i class="fas fa-table me-2"></i>Métricas Detalladas del Sistema
                </h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <h6 class="text-primary">📊 Estadísticas de Vacantes</h6>
                        <ul class="list-unstyled">
                            <li><strong>Vacantes Activas:</strong> <?php echo $job_stats['active_vacancies']; ?></li>
                            <li><strong>Vacantes Inactivas:</strong> <?php echo $job_stats['inactive_vacancies']; ?></li>
                            <li><strong>Total de Aplicaciones:</strong> <?php echo number_format($app_stats['total_applications']); ?></li>
                            <li><strong>Aplicaciones Pendientes:</strong> <?php echo number_format($job_stats['pending_applications']); ?></li>
                        </ul>
                        
                        <h6 class="text-primary mt-4">👥 Estadísticas de Usuarios</h6>
                        <ul class="list-unstyled">
                            <li><strong>Total de Usuarios:</strong> <?php echo $total_users; ?></li>
                            <li><strong>Usuarios Activos:</strong> <?php echo $active_users; ?></li>
                            <li><strong>Administradores:</strong> <?php echo $admin_users; ?></li>
                            <li><strong>Usuarios Inactivos:</strong> <?php echo ($total_users - $active_users); ?></li>
                        </ul>
                    </div>
                    
                    <div class="col-md-6">
                        <h6 class="text-primary">🏢 Estadísticas por División</h6>
                        <div class="table-responsive">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>División</th>
                                        <th>Vacantes</th>
                                        <th>Aplicaciones</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($job_stats['vacancies_by_division'] as $div): ?>
                                    <tr>
                                        <td><?php echo escape($div['name']); ?></td>
                                        <td>
                                            <span class="badge bg-primary">
                                                <?php echo isset($div['vacancies_count']) ? $div['vacancies_count'] : 0; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="badge bg-success">
                                                <?php echo isset($div['applications_count']) ? $div['applications_count'] : 0; ?>
                                            </span>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        
                        <h6 class="text-primary mt-4">📈 Rendimiento del Sistema</h6>
                        <ul class="list-unstyled">
                            <?php 
                            $avg_applications = $job_stats['active_vacancies'] > 0 ? 
                                round($app_stats['total_applications'] / $job_stats['active_vacancies'], 2) : 0;
                            ?>
                            <li><strong>Promedio aplicaciones/vacante:</strong> <?php echo $avg_applications; ?></li>
                            <li><strong>Tasa de respuesta:</strong> 
                                <?php 
                                $response_rate = $app_stats['total_applications'] > 0 ? 
                                    round(($app_stats['total_applications'] - $job_stats['pending_applications']) / $app_stats['total_applications'] * 100, 1) : 0;
                                echo $response_rate . '%';
                                ?>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Configuración de gráficos
Chart.defaults.font.family = 'Nunito, sans-serif';
Chart.defaults.color = '#858796';

// Gráfico de aplicaciones mensuales
const monthlyCtx = document.getElementById('monthlyApplicationsChart').getContext('2d');
const monthlyChart = new Chart(monthlyCtx, {
    type: 'line',
    data: {
        labels: <?php echo json_encode(array_column($monthly_applications, 'month')); ?>,
        datasets: [{
            label: 'Aplicaciones',
            data: <?php echo json_encode(array_column($monthly_applications, 'count')); ?>,
            backgroundColor: 'rgba(78, 115, 223, 0.1)',
            borderColor: 'rgba(78, 115, 223, 1)',
            borderWidth: 2,
            fill: true,
            tension: 0.3
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: {
                display: false
            }
        },
        scales: {
            y: {
                beginAtZero: true,
                ticks: {
                    precision: 0
                }
            }
        }
    }
});

// Gráfico de estados de aplicaciones
const statusCtx = document.getElementById('applicationStatusChart').getContext('2d');
const statusChart = new Chart(statusCtx, {
    type: 'doughnut',
    data: {
        labels: <?php echo json_encode(array_column($applications_by_status, 'status')); ?>,
        datasets: [{
            data: <?php echo json_encode(array_column($applications_by_status, 'count')); ?>,
            backgroundColor: [
                '#4e73df',
                '#1cc88a',
                '#36b9cc',
                '#f6c23e',
                '#e74a3b'
            ],
            borderWidth: 2
        }]
    },
    options: {
        responsive: true,
        plugins: {
            legend: {
                position: 'bottom'
            }
        }
    }
});

// Gráfico de estadísticas por división
const divisionCtx = document.getElementById('divisionStatsChart').getContext('2d');
const divisionChart = new Chart(divisionCtx, {
    type: 'bar',
    data: {
        labels: <?php echo json_encode(array_column($job_stats['vacancies_by_division'], 'name')); ?>,
        datasets: [
            {
                label: 'Vacantes',
                data: <?php echo json_encode(array_map(function($d) { return isset($d['vacancies_count']) ? $d['vacancies_count'] : 0; }, $job_stats['vacancies_by_division'])); ?>,
                backgroundColor: 'rgba(78, 115, 223, 0.8)'
            },
            {
                label: 'Aplicaciones',
                data: <?php echo json_encode(array_map(function($d) { return isset($d['applications_count']) ? $d['applications_count'] : 0; }, $job_stats['vacancies_by_division'])); ?>,
                backgroundColor: 'rgba(28, 200, 138, 0.8)'
            }
        ]
    },
    options: {
        responsive: true,
        plugins: {
            legend: {
                position: 'top'
            }
        },
        scales: {
            y: {
                beginAtZero: true,
                ticks: {
                    precision: 0
                }
            }
        }
    }
});

// Función para exportar reportes
function exportReport(format) {
    alert('Función de exportación a ' + format.toUpperCase() + ' estará disponible próximamente.');
    // Aquí se implementaría la lógica de exportación
}

// Auto-actualizar cada 5 minutos
setInterval(function() {
    location.reload();
}, 300000);
</script>

<?php include 'includes/footer.php'; ?>