<?php
/**
 * Dashboard principal - Backoffice administrativo
 * Turpial Airlines, C.A.
 */

$page_title = 'Dashboard';

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

// Verificar autenticación
requireLogin();

// Obtener estadísticas
$jobVacancy = new JobVacancy();
$application = new Application();
$division = new Division();

$job_stats = $jobVacancy->getStats();
$app_stats = $application->getStats();
$recent_applications = $application->getRecentApplications(5);
$application_stats_chart = $jobVacancy->getApplicationStats();

include 'includes/header.php';
?>

<!-- Estadísticas principales -->
<div class="row mb-4">
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card border-left-primary shadow 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">
                            Vacantes Activas
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800">
                            <?php echo $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-4">
        <div class="card border-left-success shadow 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 $job_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-4">
        <div class="card border-left-warning shadow 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">
                            Pendientes de Revisión
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800">
                            <?php echo $job_stats['pending_applications']; ?>
                        </div>
                    </div>
                    <div class="col-auto">
                        <i class="fas fa-hourglass-half fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card border-left-info shadow 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">
                            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>

<div class="row">
    <!-- Gráfica de aplicaciones por vacante -->
    <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-bar me-2"></i>Aplicaciones por Vacante (Top 10)
                </h6>
            </div>
            <div class="card-body">
                <canvas id="applicationsChart" height="100"></canvas>
            </div>
        </div>
    </div>
    
    <!-- Gráfica de vacantes por división -->
    <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>Vacantes por División
                </h6>
            </div>
            <div class="card-body">
                <canvas id="divisionsChart" height="200"></canvas>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- Aplicaciones recientes -->
    <div class="col-lg-8 mb-4">
        <div class="card shadow">
            <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-clock me-2"></i>Aplicaciones Recientes
                </h6>
                <a href="applications.php" class="btn btn-primary btn-sm">
                    Ver Todas
                </a>
            </div>
            <div class="card-body">
                <?php if (empty($recent_applications)): ?>
                    <div class="text-center py-4">
                        <i class="fas fa-inbox fa-3x text-muted mb-3"></i>
                        <p class="text-muted">No hay aplicaciones recientes</p>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Candidato</th>
                                    <th>Vacante</th>
                                    <th>Fecha</th>
                                    <th>Estado</th>
                                    <th>Acciones</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($recent_applications as $app): ?>
                                    <tr>
                                        <td>
                                            <div>
                                                <strong><?php echo escape($app['full_name']); ?></strong><br>
                                                <small class="text-muted"><?php echo escape($app['email']); ?></small>
                                            </div>
                                        </td>
                                        <td>
                                            <div>
                                                <?php echo escape($app['job_title']); ?><br>
                                                <small class="text-muted"><?php echo escape($app['category_name']); ?></small>
                                            </div>
                                        </td>
                                        <td><?php echo formatDateTime($app['application_date']); ?></td>
                                        <td>
                                            <span class="badge status-<?php echo strtolower(str_replace(' ', '', $app['status'])); ?>">
                                                <?php echo escape($app['status']); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <a href="applications.php?view=<?php echo $app['id']; ?>" 
                                               class="btn btn-outline-primary btn-sm">
                                                <i class="fas fa-eye"></i>
                                            </a>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <!-- Estadísticas por estado de aplicación -->
    <div class="col-lg-4 mb-4">
        <div class="card shadow">
            <div class="card-header py-3">
                <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">
                <?php if (!empty($app_stats['applications_by_status'])): ?>
                    <?php foreach ($app_stats['applications_by_status'] as $status): ?>
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <div>
                                <span class="badge status-<?php echo strtolower(str_replace(' ', '', $status['status'])); ?> me-2">
                                    <?php echo escape($status['status']); ?>
                                </span>
                            </div>
                            <div>
                                <strong><?php echo $status['count']; ?></strong>
                            </div>
                        </div>
                        <div class="progress mb-3" style="height: 6px;">
                            <?php 
                            $percentage = ($status['count'] / $app_stats['total_applications']) * 100;
                            ?>
                            <div class="progress-bar" role="progressbar" 
                                 style="width: <?php echo $percentage; ?>%"
                                 aria-valuenow="<?php echo $percentage; ?>" 
                                 aria-valuemin="0" aria-valuemax="100">
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <p class="text-muted text-center">No hay datos disponibles</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<!-- Acciones rápidas -->
<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-bolt me-2"></i>Acciones Rápidas
                </h6>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-3 mb-3">
                        <a href="vacancies.php?action=create" class="btn btn-turpial w-100">
                            <i class="fas fa-plus-circle me-2"></i>Nueva Vacante
                        </a>
                    </div>
                    <div class="col-md-3 mb-3">
                        <a href="applications.php?status=Pendiente" class="btn btn-warning w-100">
                            <i class="fas fa-hourglass-half me-2"></i>Revisar Pendientes
                        </a>
                    </div>
                    <div class="col-md-3 mb-3">
                        <a href="divisions.php?action=create" class="btn btn-info w-100">
                            <i class="fas fa-building me-2"></i>Nueva División
                        </a>
                    </div>
                    <div class="col-md-3 mb-3">
                        <a href="reports.php" class="btn btn-success w-100">
                            <i class="fas fa-chart-line me-2"></i>Ver Reportes
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php
$additional_js = '
<script>
// Gráfica de aplicaciones por vacante
const applicationsData = ' . json_encode($application_stats_chart) . ';
const ctx1 = document.getElementById("applicationsChart").getContext("2d");
new Chart(ctx1, {
    type: "bar",
    data: {
        labels: applicationsData.map(item => item.title.length > 30 ? item.title.substring(0, 30) + "..." : item.title),
        datasets: [{
            label: "Aplicaciones",
            data: applicationsData.map(item => item.application_count),
            backgroundColor: "rgba(255, 215, 0, 0.8)",
            borderColor: "rgba(255, 215, 0, 1)",
            borderWidth: 1
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                display: false
            }
        },
        scales: {
            y: {
                beginAtZero: true
            }
        }
    }
});

// Gráfica de vacantes por división
const divisionsData = ' . json_encode($job_stats['vacancies_by_division']) . ';
const ctx2 = document.getElementById("divisionsChart").getContext("2d");
new Chart(ctx2, {
    type: "doughnut",
    data: {
        labels: divisionsData.map(item => item.name),
        datasets: [{
            data: divisionsData.map(item => item.count),
            backgroundColor: [
                "#FFD700",
                "#FFA500",
                "#FF8C00",
                "#FF6347",
                "#DC143C"
            ],
            borderWidth: 2,
            borderColor: "#fff"
        }]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
            legend: {
                position: "bottom"
            }
        }
    }
});
</script>
';
?>

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