<?php
session_start();
require 'conexion.php';

// Asegurar autenticación (roles 9 o 11)
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || !in_array($_SESSION['role'], [9, 11])) {
    $_SESSION['error'] = 'Acceso no autorizado. Por favor, inicia sesión con una cuenta de RRHH válida.';
    header("Location: login.php");
    exit;
}

$user_id = $_SESSION['user_id'];
$nombre_usuario = $_SESSION['Nom'];
$es_consulta = ($_SESSION['role'] == 11);

// === Resumen tarjetas (mes actual) ===
$current_month = date('m');
$current_year = date('Y');

$sql_pendientes = "SELECT COUNT(*) as total FROM solicitudes WHERE estado = 'Pendiente' AND MONTH(fecha_solicitud) = ? AND YEAR(fecha_solicitud) = ?";
$stmt_pendientes = $conn->prepare($sql_pendientes);
$stmt_pendientes->bind_param('ii', $current_month, $current_year);
$stmt_pendientes->execute();
$pendientes = $stmt_pendientes->get_result()->fetch_assoc()['total'];
$stmt_pendientes->close();

$sql_aprobadas = "SELECT COUNT(*) as total FROM solicitudes WHERE estado = 'Aprobada por Recursos Humanos' AND MONTH(fecha_solicitud) = ? AND YEAR(fecha_solicitud) = ?";
$stmt_aprobadas = $conn->prepare($sql_aprobadas);
$stmt_aprobadas->bind_param('ii', $current_month, $current_year);
$stmt_aprobadas->execute();
$aprobadas = $stmt_aprobadas->get_result()->fetch_assoc()['total'];
$stmt_aprobadas->close();

$sql_rechazadas = "SELECT COUNT(*) as total FROM solicitudes WHERE estado = 'Rechazada por Recursos Humanos' AND MONTH(fecha_solicitud) = ? AND YEAR(fecha_solicitud) = ?";
$stmt_rechazadas = $conn->prepare($sql_rechazadas);
$stmt_rechazadas->bind_param('ii', $current_month, $current_year);
$stmt_rechazadas->execute();
$rechazadas = $stmt_rechazadas->get_result()->fetch_assoc()['total'];
$stmt_rechazadas->close();

$sql_urgentes = "SELECT COUNT(*) as total FROM solicitudes WHERE estado = 'Pendiente' AND fecha_salida <= DATE_ADD(CURDATE(), INTERVAL 3 DAY)";
$stmt_urgentes = $conn->prepare($sql_urgentes);
$stmt_urgentes->execute();
$urgentes = $stmt_urgentes->get_result()->fetch_assoc()['total'];
$stmt_urgentes->close();

$sql_aprobadas_jefe = "SELECT COUNT(*) as total FROM solicitudes WHERE estado = 'Aprobada por Jefe Inmediato' AND MONTH(fecha_solicitud) = ? AND YEAR(fecha_solicitud) = ?";
$stmt_aprobadas_jefe = $conn->prepare($sql_aprobadas_jefe);
$stmt_aprobadas_jefe->bind_param('ii', $current_month, $current_year);
$stmt_aprobadas_jefe->execute();
$aprobadas_jefe = $stmt_aprobadas_jefe->get_result()->fetch_assoc()['total'];
$stmt_aprobadas_jefe->close();

// === Solicitudes pendientes (tabla) ===
$sql_solicitudes_pendientes = "SELECT s.id, s.tipo_permiso, s.fecha_solicitud, s.fecha_salida, s.descripcion_motivo, a.Nom, a.Ape 
                               FROM solicitudes s 
                               JOIN accounts a ON s.id_usuario = a.ID 
                               WHERE s.estado = 'Pendiente' 
                               ORDER BY s.fecha_solicitud DESC";
$result_solicitudes_pendientes = $conn->query($sql_solicitudes_pendientes);

// === Acciones aprobar/rechazar ===
if (!$es_consulta && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'], $_POST['solicitud_id'])) {
    $solicitud_id = (int)$_POST['solicitud_id'];
    $action = $_POST['action'];
    $estado = ($action === 'aprobar') ? 'Aprobada por Recursos Humanos' : 'Rechazada por Recursos Humanos';

    $sql_update = "UPDATE solicitudes SET estado = ?, id_usuario = ? WHERE id = ?";
    if ($stmt = $conn->prepare($sql_update)) {
        $stmt->bind_param('sii', $estado, $user_id, $solicitud_id);
        $stmt->execute();
        $stmt->close();
        header("Location: dashboard_rrhh.php");
        exit;
    }
}

// === Calendario (mes/año seleccionados) ===
$selected_month = isset($_GET['month']) ? (int)$_GET['month'] : date('n');
$selected_year  = isset($_GET['year'])  ? (int)$_GET['year']  : date('Y');

if ($selected_month < 1 || $selected_month > 12) $selected_month = date('n');
if ($selected_year < 2000 || $selected_year > 2100) $selected_year = date('Y');

$days_in_month = cal_days_in_month(CAL_GREGORIAN, $selected_month, $selected_year);

// Cargar fechas con estado + tipo + detalle por día
$sql_fechas = "SELECT DATE(s.fecha_salida) AS fecha,
                      s.estado,
                      s.tipo_permiso,
                      s.descripcion_motivo,
                      a.Nom, a.Ape
               FROM solicitudes s
               JOIN accounts a ON a.ID = s.id_usuario
               WHERE YEAR(s.fecha_salida) = ?
                 AND MONTH(s.fecha_salida) = ?";
$stmt_fechas = $conn->prepare($sql_fechas);
$stmt_fechas->bind_param('ii', $selected_year, $selected_month);
$stmt_fechas->execute();
$result_fechas = $stmt_fechas->get_result();

/**
 * $cal['YYYY-MM-DD'] = [
 *   'count'         => N,
 *   'estados'       => [ 'pendiente'=>true, 'aprobada-por-rrhh'=>true, ... ], // set (para color/tooltip)
 *   'estados_count' => [ 'pendiente'=>2, 'aprobada-por-rrhh'=>1, ... ],       // conteo por estado
 *   'tipos'         => [ 'Personal'=>2, 'Vacaciones'=>1, 'Oficial'=>1 ]
 * ]
 * $calDetails['YYYY-MM-DD'][] = [
 *   'empleado','tipo','estado','motivo'
 * ]
 */
$cal = [];
$calDetails = [];
if ($result_fechas) {
    while ($row = $result_fechas->fetch_assoc()) {
        $f = $row['fecha'];
        if (!isset($cal[$f])) {
            $cal[$f] = ['count'=>0, 'estados'=>[], 'estados_count'=>[], 'tipos'=>[]];
        }
        $cal[$f]['count']++;

        // Normalizar clase de estado
        $estado_class = strtolower(str_replace(' ', '-', str_replace('Recursos Humanos', 'rrhh', $row['estado'])));
        $cal[$f]['estados'][$estado_class] = true;
        if (!isset($cal[$f]['estados_count'][$estado_class])) $cal[$f]['estados_count'][$estado_class] = 0;
        $cal[$f]['estados_count'][$estado_class]++;

        // Tipos
        $tipo = $row['tipo_permiso'] ?: 'Sin tipo';
        if (!isset($cal[$f]['tipos'][$tipo])) $cal[$f]['tipos'][$tipo] = 0;
        $cal[$f]['tipos'][$tipo]++;

        // Detalle
        if (!isset($calDetails[$f])) $calDetails[$f] = [];
        $nombreCompleto = trim(($row['Nom'] ?? '').' '.($row['Ape'] ?? ''));
        $calDetails[$f][] = [
            'empleado' => $nombreCompleto ?: '—',
            'tipo'     => $row['tipo_permiso'] ?: '—',
            'estado'   => $row['estado'] ?: '—',
            'motivo'   => $row['descripcion_motivo'] ?: '—',
        ];
    }
}
$stmt_fechas->close();

// Auxiliares
function estado_legible($class){
    return str_replace(
        ['pendiente','aprobada-por-jefe-inmediato','aprobada-por-rrhh','rechazada-por-jefe-inmediato','rechazada-por-rrhh','-'],
        ['Pendiente','Aprobada por Jefe Inmediato','Aprobada por RRHH','Rechazada por Jefe Inmediato','Rechazada por RRHH',' '],
        $class
    );
}
function estado_principal_css($estadosSet){
    $prioridad = ['pendiente','rechazada-por-rrhh','rechazada-por-jefe-inmediato','aprobada-por-rrhh','aprobada-por-jefe-inmediato'];
    foreach ($prioridad as $e) if (isset($estadosSet[$e])) return $e;
    return '';
}

// === Notificaciones (límite mensual) ===
$current_month = date('m');
$current_year = date('Y');
$max_requests_per_month = 3;

$sql_limited_users = "SELECT a.Nom, a.Ape, COUNT(s.id) as total 
                     FROM accounts a 
                     JOIN solicitudes s ON a.ID = s.id_usuario 
                     WHERE MONTH(s.fecha_solicitud) = ? 
                       AND YEAR(s.fecha_solicitud) = ? 
                     GROUP BY a.ID, a.Nom, a.Ape 
                     HAVING total >= ?";
$stmt_limited = $conn->prepare($sql_limited_users);
$stmt_limited->bind_param('iii', $current_month, $current_year, $max_requests_per_month);
$stmt_limited->execute();
$result_limited_users = $stmt_limited->get_result();
$limited_users = [];
if ($result_limited_users) {
    while ($row = $result_limited_users->fetch_assoc()) {
        $limited_users[] = $row;
    }
}
$stmt_limited->close();

$conn->close();
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Panel de Recursos Humanos</title>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Roboto', sans-serif; }
        body { background-color: #f0f4f8; color: #2c3e50; line-height: 1.6; }
        .container { display: flex; min-height: 100vh; overflow: hidden; }

        /* Sidebar */
        .sidebar { width: 260px; background: linear-gradient(135deg, #2c3e50, #34495e); color: white; padding: 20px 15px; position: fixed; height: 100%; transition: transform 0.3s ease, width 0.3s ease; z-index: 1000; }
        .sidebar.collapsed { transform: translateX(-260px); width: 0; }
        .sidebar h2 { font-size: 24px; margin-bottom: 30px; text-align: center; color: #68c8d8; }
        .sidebar ul { list-style: none; }
        .sidebar ul li { margin-bottom: 15px; }
        .sidebar ul li a { color: #ecf0f1; text-decoration: none; font-size: 16px; display: flex; align-items: center; padding: 10px 15px; border-radius: 5px; transition: background 0.3s, color 0.3s; }
        .sidebar ul li a:hover { background: #465c71; color: #68c8d8; }
        .sidebar ul li a i { margin-right: 10px; }
        .toggle-btn { display: none; position: fixed; left: 10px; top: 10px; background: #68c8d8; color: white; border: none; padding: 10px; border-radius: 5px; cursor: pointer; z-index: 1001; }

        /* Main Content */
        .main-content { margin-left: 260px; padding: 30px; width: calc(100% - 260px); transition: margin-left 0.3s ease, width 0.3s ease; }
        .welcome-message { font-size: 28px; color: #2c3e50; margin-bottom: 25px; text-align: center; font-weight: 500; }

        /* Cards Section */
        .cards-section { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 30px; }
        .card { background: white; padding: 20px; border-radius: 10px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); text-align: center; transition: transform 0.2s; }
        .card:hover { transform: translateY(-5px); }
        .card h3 { font-size: 18px; color: #7f8c8d; margin-bottom: 10px; }
        .card p { font-size: 32px; font-weight: 700; color: #2c3e50; }
        .card.pendientes { border-left: 5px solid #f39c12; }
        .card.aprobadas { border-left: 5px solid #27ae60; }
        .card.rechazadas { border-left: 5px solid #c0392b; }
        .card.urgentes { border-left: 5px solid #e74c3c; }
        .card.aprobadas-jefe { border-left: 5px solid #3498db; }

        /* Request Section */
        .request-section { background: white; padding: 20px; border-radius: 10px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); margin-bottom: 30px; text-align: center; }
        .request-section h2 { font-size: 22px; color: #2c3e50; margin-bottom: 20px; }
        .request-buttons { display: flex; justify-content: center; gap: 15px; flex-wrap: wrap; }
        .request-buttons button { padding: 12px 20px; background: linear-gradient(135deg, #68c8d8, #5dade2); color: white; border: none; border-radius: 8px; font-size: 16px; cursor: pointer; transition: transform 0.2s, background 0.3s; }
        .request-buttons button:hover:not(:disabled) { background: linear-gradient(135deg, #5dade2, #3498db); transform: translateY(-2px); }
        .request-buttons button:disabled { background: #b0bec5; cursor: not-allowed; opacity: 0.7; }

        /* Notifications */
        .notifications-section { background: white; padding: 20px; border-radius: 10px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); margin-bottom: 30px; }
        .notifications-section h2 { font-size: 22px; color: #2c3e50; margin-bottom: 15px; }
        .notifications-section ul { list-style: none; }
        .notifications-section li { padding: 12px 15px; margin-bottom: 10px; border-left: 5px solid #f39c12; background: #fffaf0; border-radius: 5px; font-size: 15px; color: #555; transition: background 0.3s; }
        .notifications-section li.limit { border-left-color: #c0392b; background: #ffebee; }
        .notifications-section li:hover { background: #fef9f3; }

        /* Pending Requests */
        .pending-requests { background: white; padding: 20px; border-radius: 10px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); margin-bottom: 30px; }
        .pending-requests h2 { font-size: 22px; color: #2c3e50; margin-bottom: 15px; }
        .pending-requests table { width: 100%; border-collapse: collapse; }
        .pending-requests th, .pending-requests td { padding: 12px; text-align: left; border-bottom: 1px solid #ecf0f1; }
        .pending-requests th { background: #2c3e50; color: white; }
        .pending-requests td { color: #7f8c8d; }
        .pending-requests .action-buttons { display: <?= $es_consulta ? 'none' : 'inline-flex' ?>; gap: 10px; }
        .pending-requests .action-buttons form { display: inline; }
        .pending-requests .action-buttons button { padding: 8px 15px; border: none; border-radius: 5px; font-size: 14px; cursor: pointer; transition: background 0.3s; }
        .pending-requests .action-buttons .approve { background: #27ae60; color: white; }
        .pending-requests .action-buttons .approve:hover { background: #219653; }
        .pending-requests .action-buttons .reject { background: #c0392b; color: white; }
        .pending-requests .action-buttons .reject:hover { background: #a93226; }

        /* ===== CALENDARIO NUEVO ===== */
        .calendar-section { background: white; padding: 22px; border-radius: 14px; box-shadow: 0 6px 18px rgba(0,0,0,0.08); margin-bottom: 32px; border: 1px solid #eef2f5; }
        .calendar-section h2 { font-size: 20px; color: #1f2937; margin-bottom: 14px; display: flex; align-items: center; gap: 8px; }

        .cal-header { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 14px; flex-wrap: wrap; }
        .cal-nav { display: flex; align-items: center; gap: 8px; }
        .cal-nav form, .cal-nav .nav-btns { display: flex; gap: 8px; flex-wrap: wrap; }

        .cal-select, .cal-button { border: 1px solid #e5e7eb; background: #fff; color: #374151; padding: 8px 10px; border-radius: 10px; font-size: 14px; cursor: pointer; transition: box-shadow .2s, transform .05s, border-color .2s; }
        .cal-select:focus { outline: none; border-color: #68c8d8; box-shadow: 0 0 0 3px rgba(104,200,216,.2); }
        .cal-button { display: inline-flex; align-items: center; gap: 6px; text-decoration: none; }
        .cal-button:hover { border-color: #cbd5e1; }
        .cal-button:active { transform: translateY(1px); }

        .cal-legend { display: flex; flex-wrap: wrap; gap: 8px; }
        .legend-chip { display: inline-flex; align-items: center; gap: 6px; padding: 6px 10px; border-radius: 999px; font-size: 12px; background: #f8fafc; border: 1px solid #eef2f5; }
        .legend-dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; }
        .dot-pendiente { background: #f39c12; }
        .dot-aprobada-rrhh { background: #27ae60; }
        .dot-aprobada-jefe { background: #3498db; }
        .dot-rechazada-rrhh { background: #c0392b; }
        .dot-rechazada-jefe { background: #e74c3c; }

        .pro-calendar { display: grid; gap: 8px; margin-top: 10px; grid-template-columns: repeat(7, minmax(0,1fr)); }
        .cal-colhead { font-weight: 600; font-size: 12px; text-transform: uppercase; color: #6b7280; padding: 8px 6px; text-align: center; letter-spacing: .03em; }

        .cal-cell { background: #fbfdff; border: 1px solid #eef2f5; border-radius: 12px; min-height: 100px; padding: 10px; position: relative; overflow: hidden; display: flex; flex-direction: column; gap: 8px; transition: box-shadow .2s, transform .05s; cursor: default; }
        .cal-cell.clickable { cursor: pointer; }
        .cal-cell:hover { box-shadow: 0 6px 16px rgba(0,0,0,.06); }
        .cal-cell.weekend { background: #f9fbfd; }
        .cal-empty { background: transparent; border: none; }

        .cal-daynumber { font-weight: 700; color: #111827; font-size: 14px; display: inline-flex; align-items: center; gap: 8px; }
        .badge-today { font-size: 10px; padding: 2px 6px; border-radius: 999px; background: #68c8d8; color: #fff; letter-spacing: .02em; }

        .status-chip { align-self: flex-start; font-size: 11px; padding: 3px 8px; border-radius: 999px; color: #fff; font-weight: 700; line-height: 1.2; }
        .status-chips{ display:flex; flex-wrap:wrap; gap:6px; }

        .chip-pendiente { background: #f39c12; }
        .chip-aprobada-por-jefe-inmediato { background: #3498db; }
        .chip-aprobada-por-rrhh { background: #27ae60; }
        .chip-rechazada-por-jefe-inmediato { background: #e74c3c; }
        .chip-rechazada-por-rrhh { background: #c0392b; }

        /* Tooltip base */
        .cal-cell[data-tip]:hover::after { 
            content: attr(data-tip); position: absolute; left: 8px; right: 8px; bottom: 8px; 
            background: rgba(17,24,39,.95); color: #fff; padding: 8px 10px; border-radius: 10px; 
            font-size: 12px; line-height: 1.3; white-space: pre-line;
        }

        /* Badge de conteo (2+ solicitudes) */
        .count-badge{
            position:absolute; top:8px; right:8px;
            min-width:22px; height:22px; padding:0 6px;
            border-radius:999px; background:#111827; color:#fff;
            font-size:12px; line-height:22px; text-align:center; font-weight:700;
            box-shadow:0 2px 6px rgba(0,0,0,.2);
        }

        /* Modales */
        .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.6); backdrop-filter: blur(4px); justify-content: center; align-items: center; z-index: 3000; }
        .modal-content { background: #fff; padding: 30px; border-radius: 15px; width: 95%; max-width: 800px; box-shadow: 0 6px 25px rgba(0, 0, 0, 0.3); position: relative; animation: modalScale 0.3s ease; }
        @keyframes modalScale { from { transform: scale(0.95); opacity: 0; } to { transform: scale(1); opacity: 1; } }
        .modal-content h3 { font-size: 20px; color: #1f2937; margin-bottom: 12px; }
        .modal-content .close { position: absolute; top: 15px; right: 20px; font-size: 24px; color: #888; cursor: pointer; transition: color 0.3s; }
        .modal-content .close:hover { color: #e74c3c; }
        .day-table { width: 100%; border-collapse: collapse; margin-top: 8px; }
        .day-table th, .day-table td { padding: 10px; border-bottom: 1px solid #eef2f5; text-align: left; font-size: 14px; }
        .day-table th { background: #f8fafc; color: #374151; }
        .muted { color: #6b7280; font-size: 13px; }

        /* Responsive */
        @media (max-width: 1024px) {
            .sidebar { width: 220px; }
            .main-content { margin-left: 220px; width: calc(100% - 220px); padding: 25px; }
            .cards-section { grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); }
        }
        @media (max-width: 768px) {
            .toggle-btn { display: block; }
            .sidebar { transform: translateX(-260px); }
            .sidebar.open { transform: translateX(0); }
            .main-content { margin-left: 0; width: 100%; padding: 20px; }
            .cards-section { grid-template-columns: 1fr 1fr; }
            .calendar-section .cal-cell { min-height: 86px; }
            .pending-requests th, .pending-requests td { padding: 10px; font-size: 13px; }
        }
        @media (max-width: 480px) {
            .cards-section { grid-template-columns: 1fr; }
            .request-buttons button { width: 100%; margin-bottom: 10px; }
            .pending-requests th, .pending-requests td { padding: 8px; font-size: 12px; }
            .pending-requests .action-buttons button { padding: 6px 12px; font-size: 12px; }
            .notifications-section li { font-size: 14px; padding: 10px; }
        }

        /* Botón flotante (password) */
        .floating-btn { position: fixed; bottom: 25px; right: 25px; background: linear-gradient(135deg, #e74c3c, #c0392b); color: white; border: none; padding: 15px; border-radius: 50%; font-size: 20px; cursor: pointer; box-shadow: 0 0 15px rgba(231, 76, 60, 0.8); transition: background 0.3s, transform 0.2s; z-index: 2000; animation: pulseGlowRed 1.8s infinite; }
        .floating-btn:hover { background: linear-gradient(135deg, #c0392b, #96281b); transform: translateY(-3px); }
    </style>
</head>
<body>
    <button class="toggle-btn" onclick="toggleSidebar()"><i class="fas fa-bars"></i></button>
    <div class="container">
        <!-- Sidebar -->
        <div class="sidebar" id="sidebar">
            <h2>Panel RRHH</h2>
            <ul>
                <li><a href="dashboard_rrhh.php"><i class="fas fa-home"></i> Inicio</a></li>
                <?php if ($_SESSION['role'] != 11): ?>
                    <li><a href="gestionar_solicitudes_rrhh.php"><i class="fas fa-tasks"></i> Gestionar Solicitudes</a></li>
                <?php endif; ?>
                <li><a href="panel_jefe_rrhh.php"><i class="fas fa-chart-bar"></i>Solicitudes Unidad RRHH</a></li>
                <li><a href="panel_rrhh_vacaciones.php"><i class="fas fa-chart-bar"></i>Solicitudes Vacaciones RRHH</a></li>
                <li><a href="estadisticas_rrhh.php"><i class="fas fa-chart-bar"></i> Estadísticas</a></li>
                <li><a href="solicitudes_aprobadas_rrhh.php"><i class="fas fa-check"></i> Historial de Solicitudes Aprobadas</a></li>
                <li><a href="ver_solicitudes.php"><i class="fas fa-eye"></i> Más Solicitudes</a></li>
                <?php if ($_SESSION['role'] != 11): ?>
                    <li><a href="gestionar_empleados.php"><i class="fas fa-users"></i> Gestión de Empleados</a></li>
                <?php endif; ?>
                <li><a href="panel_vacaciones_rrhh.php"><i class="fas fa-umbrella-beach"></i> Gestión de Vacaciones</a></li>
                <?php if ($_SESSION['role'] != 11): ?>
                    <li><a href="gestionar_unidades_puestos.php"><i class="fas fa-building"></i> Unidades y Puestos</a></li>
                    <li><a href="asignar_privilegios_rrhh.php"><i class="fas fa-user-shield"></i> Asignar Rol</a></li>
                <?php endif; ?>
                <li>
                    <a href="https://sistemas.proasol.gob.hn/denuncias_proasol/index.html?src=rrhh_sidebar" target="_blank" rel="noopener">
                        <i class="fas fa-shield-alt"></i> Denuncia-CPEP
                    </a>
                </li>
                <li><a href="panel_rrhh_user.php"><i class="fas fa-user"></i> Perfil</a></li>
                <li><a href="logout.php"><i class="fas fa-sign-out-alt"></i> Cerrar Sesión</a></li>
            </ul>
        </div>

        <!-- Main -->
        <div class="main-content">
            <div class="welcome-message">Bienvenido, <?= htmlspecialchars($nombre_usuario) ?> <span style="font-size: 14px; color: #7f8c8d;"></span></div>

            <!-- Resumen -->
            <div class="cards-section">
                <div class="card pendientes"><h3>Pendientes</h3><p><?= $pendientes ?></p></div>
                <div class="card aprobadas"><h3>Aprobadas</h3><p><?= $aprobadas ?></p></div>
                <div class="card rechazadas"><h3>Rechazadas</h3><p><?= $rechazadas ?></p></div>
                <div class="card urgentes"><h3>Urgentes</h3><p><?= $urgentes ?></p></div>
                <div class="card aprobadas-jefe"><h3>Aprobadas por Jefe</h3><p><?= $aprobadas_jefe ?></p></div>
            </div>

            <!-- Acciones rápidas -->
            <div class="request-section">
                <h2>Nueva Solicitud de Permiso</h2>
                <div class="request-buttons">
                    <button onclick="window.location.href='pase_salida.php'" <?= isset($monthly_requests) && $monthly_requests >= $max_requests_per_month ? 'disabled' : '' ?>>
                        <i class="fas fa-plus"></i> Generar Permiso
                    </button>
                    <button onclick="window.location.href='pase_vacaciones.php'">
                        <i class="fas fa-umbrella-beach"></i> Generar Vacaciones
                    </button>
                    <button onclick="openMoreRequestsModal()">
                        <i class="fas fa-ellipsis-h"></i> Más Solicitudes
                    </button>
                </div>
            </div>

            <!-- ===== Calendario ===== -->
            <div class="calendar-section">
                <h2><i class="fas fa-calendar-alt"></i> Mis Permisos (Fecha de Salida)</h2>
                <?php
                    // Mes anterior / siguiente
                    $prevMonth = $selected_month - 1; $prevYear = $selected_year;
                    if ($prevMonth < 1) { $prevMonth = 12; $prevYear--; }
                    $nextMonth = $selected_month + 1; $nextYear = $selected_year;
                    if ($nextMonth > 12) { $nextMonth = 1; $nextYear++; }
                ?>
                <div class="cal-header">
                    <div class="cal-nav">
                        <div class="nav-btns">
                            <a class="cal-button" href="dashboard_rrhh.php?month=<?= $prevMonth ?>&year=<?= $prevYear ?>">
                                <i class="fas fa-chevron-left"></i> Anterior
                            </a>
                            <a class="cal-button" href="dashboard_rrhh.php?month=<?= $nextMonth ?>&year=<?= $nextYear ?>">
                                Siguiente <i class="fas fa-chevron-right"></i>
                            </a>
                        </div>
                        <form method="GET" action="dashboard_rrhh.php">
                            <select class="cal-select" name="month" onchange="this.form.submit()">
                                <?php
                                $months = [1=>'Enero',2=>'Febrero',3=>'Marzo',4=>'Abril',5=>'Mayo',6=>'Junio',7=>'Julio',8=>'Agosto',9=>'Septiembre',10=>'Octubre',11=>'Noviembre',12=>'Diciembre'];
                                foreach ($months as $num => $name) {
                                    $sel = $selected_month == $num ? 'selected' : '';
                                    echo "<option value='$num' $sel>$name</option>";
                                }
                                ?>
                            </select>
                            <select class="cal-select" name="year" onchange="this.form.submit()">
                                <?php
                                for ($y = date('Y') + 1; $y >= date('Y') - 5; $y--) {
                                    $sel = $selected_year == $y ? 'selected' : '';
                                    echo "<option value='$y' $sel>$y</option>";
                                }
                                ?>
                            </select>
                        </form>
                    </div>

                    <div class="cal-legend">
                        <span class="legend-chip"><span class="legend-dot dot-pendiente"></span>Pendiente</span>
                        <span class="legend-chip"><span class="legend-dot dot-aprobada-rrhh"></span>Aprobada RRHH</span>
                        <span class="legend-chip"><span class="legend-dot dot-aprobada-jefe"></span>Aprobada Jefe</span>
                        <span class="legend-chip"><span class="legend-dot dot-rechazada-rrhh"></span>Rechazada RRHH</span>
                        <span class="legend-chip"><span class="legend-dot dot-rechazada-jefe"></span>Rechazada Jefe</span>
                    </div>
                </div>

                <div class="pro-calendar">
                    <div class="cal-colhead">Lun</div>
                    <div class="cal-colhead">Mar</div>
                    <div class="cal-colhead">Mié</div>
                    <div class="cal-colhead">Jue</div>
                    <div class="cal-colhead">Vie</div>
                    <div class="cal-colhead">Sáb</div>
                    <div class="cal-colhead">Dom</div>

                    <?php
                    // Alinear inicio en lunes
                    $startDow = date('w', strtotime(sprintf('%04d-%02d-01', $selected_year, $selected_month))); // 0=Dom
                    $offset = ($startDow + 6) % 7; // Lunes=0
                    for ($i=0; $i<$offset; $i++) echo "<div class='cal-cell cal-empty'></div>";

                    $today = date('Y-m-d');
                    for ($day=1; $day<=$days_in_month; $day++) {
                        $dateStr = sprintf('%04d-%02d-%02d', $selected_year, $selected_month, $day);
                        $dow = date('N', strtotime($dateStr)); // 1..7
                        $weekend = ($dow >= 6) ? 'weekend' : '';

                        $count = 0;
                        $estadoClassPrincipal = '';
                        $tip = date('d/m/Y', strtotime($dateStr)) . ' · Sin solicitudes';

                        if (isset($cal[$dateStr])) {
                            $info = $cal[$dateStr];
                            $count = (int)$info['count'];
                            $estadoClassPrincipal  = estado_principal_css($info['estados']);

                            // Tooltip: estado principal + desglose por tipo
                            $estadoTextPrincipal = $estadoClassPrincipal ? estado_legible($estadoClassPrincipal) : 'Con solicitudes';
                            $lineas = [];
                            foreach ($info['tipos'] as $tipo => $n) { $lineas[] = "$tipo: $n"; }
                            $tip = date('d/m/Y', strtotime($dateStr)) . ' · ' . $estadoTextPrincipal . "\n" . implode("\n", $lineas);
                        }

                        $attrs = ($count>0 ? "data-tip='".htmlspecialchars($tip, ENT_QUOTES)."'" : "");
                        $clickCls = ($count>0 ? "clickable" : "");
                        $onclick = ($count>0 ? "onclick=\"openDayDetail('$dateStr')\"" : "");

                        echo "<div class='cal-cell $weekend $clickCls' $attrs $onclick>";
                            echo "<div class='cal-daynumber'>";
                                echo $day;
                                if ($dateStr === $today) echo "<span class='badge-today'>Hoy</span>";
                            echo "</div>";

                            // === Chips múltiples por estado (con conteo) ===
                            if (isset($cal[$dateStr]) && !empty($cal[$dateStr]['estados_count'])) {
                                $prioridad = ['pendiente','rechazada-por-rrhh','rechazada-por-jefe-inmediato','aprobada-por-rrhh','aprobada-por-jefe-inmediato'];
                                $counts = $cal[$dateStr]['estados_count'];
                                $ordenados = [];
                                foreach ($prioridad as $e) {
                                    if (isset($counts[$e])) { $ordenados[$e] = $counts[$e]; unset($counts[$e]); }
                                }
                                foreach ($counts as $k => $v) { $ordenados[$k] = $v; }

                                echo "<div class='status-chips'>";
                                foreach ($ordenados as $estadoCls => $n) {
                                    $texto = estado_legible($estadoCls);
                                    $label = $n > 1 ? "$texto ($n)" : $texto;
                                    echo "<span class='status-chip chip-$estadoCls'>".htmlspecialchars($label)."</span>";
                                }
                                echo "</div>";
                            }

                            // Badge total (2+)
                            if ($count > 1) {
                                echo "<span class='count-badge'>".$count."</span>";
                            }
                        echo "</div>";
                    }
                    ?>
                </div>
            </div>
            <!-- ===== /Calendario ===== -->

        </div>
    </div>

    <!-- Modal: Más Solicitudes -->
    <div id="moreRequestsModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeMoreRequestsModal()">×</span>
            <h3>Más Solicitudes</h3>
            <form id="moreRequestsForm" action="procesar_solicitud_documento.php" method="POST">
                <label for="tipo_solicitud">Tipo de Solicitud:</label>
                <select id="tipo_solicitud" name="tipo_solicitud" required>
                    <option value="">Seleccione una opción</option>
                    <option value="Constancia de trabajo">Constancia de trabajo</option>
                    <option value="Constancia de trabajo con deducciones">Constancia de trabajo con deducciones</option>
                    <option value="Constancia para Embajadas">Constancia para Embajadas</option>
                    <option value="Declaración de impuestos">Declaración de impuestos</option>
                    <option value="Voucher de pagos">Voucher de pagos</option>
                </select>
                <label for="comentarios">Comentarios:</label>
                <textarea id="comentarios" name="comentarios" placeholder="Escribe un comentario breve sobre lo que estás solicitando"></textarea>
                <div class="modal-buttons" style="display:flex;gap:10px;justify-content:flex-end;margin-top:12px">
                    <button type="button" class="cancel" onclick="closeMoreRequestsModal()">Cancelar</button>
                    <button type="submit" class="submit" style="background:#27ae60;color:#fff;border:none;border-radius:8px;padding:10px 16px;">Enviar</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Modal: Detalle del día -->
    <div id="dayDetailModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closeDayDetail()">×</span>
            <h3 id="dayDetailTitle">Detalle del día</h3>
            <div id="dayDetailBody" class="muted">Cargando...</div>
        </div>
    </div>

    <!-- Modal cambiar contraseña -->
    <div id="passwordModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closePasswordModal()">×</span>
            <h3><i class="fas fa-lock"></i> Cambiar Contraseña</h3>
            <form action="cambiar_password.php" method="POST">
                <div class="input-group" style="position:relative;margin-bottom:12px">
                    <i class="fas fa-key" style="position:absolute;left:12px;top:50%;transform:translateY(-50%);color:#aaa"></i>
                    <input style="width:100%;padding:12px 12px 12px 40px;border:1px solid #ddd;border-radius:8px" type="password" id="password" name="password" required minlength="6" placeholder="Nueva contraseña">
                </div>
                <div class="input-group" style="position:relative;margin-bottom:12px">
                    <i class="fas fa-check-circle" style="position:absolute;left:12px;top:50%;transform:translateY(-50%);color:#aaa"></i>
                    <input style="width:100%;padding:12px 12px 12px 40px;border:1px solid #ddd;border-radius:8px" type="password" id="confirm_password" name="confirm_password" required placeholder="Confirmar contraseña">
                </div>
                <div id="password-alert" class="muted" style="display:none;color:#e74c3c">⚠️ Las contraseñas no coinciden.</div>
                <div class="modal-buttons" style="display:flex;gap:10px;justify-content:flex-end;margin-top:12px">
                    <button type="button" class="cancel" onclick="closePasswordModal()">Cancelar</button>
                    <button type="submit" class="submit" style="background:#27ae60;color:#fff;border:none;border-radius:8px;padding:10px 16px;">Guardar</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Botón flotante password -->
    <button class="floating-btn" onclick="openPasswordModal()"><i class="fas fa-key"></i></button>

    <script>
        // Sidebar
        function toggleSidebar() {
            const sidebar = document.getElementById('sidebar');
            sidebar.classList.toggle('open');
            const mainContent = document.querySelector('.main-content');
            if (sidebar.classList.contains('open')) {
                mainContent.style.marginLeft = '260px';
                mainContent.style.width = 'calc(100% - 260px)';
            } else {
                mainContent.style.marginLeft = '0';
                mainContent.style.width = '100%';
            }
        }

        // Modal "Más Solicitudes"
        function openMoreRequestsModal() { document.getElementById('moreRequestsModal').style.display = 'flex'; }
        function closeMoreRequestsModal() {
            document.getElementById('moreRequestsModal').style.display = 'none';
            const f = document.getElementById('moreRequestsForm');
            if (f) f.reset();
        }

        // Modal Password
        function openPasswordModal() { document.getElementById('passwordModal').style.display = 'flex'; }
        function closePasswordModal() { document.getElementById('passwordModal').style.display = 'none'; }

        const passForm = document.querySelector("form[action='cambiar_password.php']");
        if (passForm) {
            passForm.addEventListener("submit", function(e) {
                const pass = document.getElementById("password").value;
                const confirm = document.getElementById("confirm_password").value;
                const alertBox = document.getElementById("password-alert");
                if (pass !== confirm) {
                    e.preventDefault();
                    alertBox.style.display = "block";
                } else {
                    alertBox.style.display = "none";
                }
            });
        }

        // ===== Detalle del día =====
        const CAL_DETAILS = <?= json_encode($calDetails ?? [], JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP); ?>;

        function openDayDetail(dateStr){
            const modal = document.getElementById('dayDetailModal');
            const title = document.getElementById('dayDetailTitle');
            const body  = document.getElementById('dayDetailBody');

            const parts = dateStr.split('-'); // yyyy-mm-dd
            const pretty = `${parts[2]}/${parts[1]}/${parts[0]}`;
            title.textContent = `Detalle del ${pretty}`;

            const items = CAL_DETAILS[dateStr] || [];
            if (items.length === 0) {
                body.innerHTML = `<div class="muted">Sin solicitudes.</div>`;
            } else {
                let rows = items.map(it => {
                    const emp = escapeHTML(it.empleado || '—');
                    const tipo = escapeHTML(it.tipo || '—');
                    const est = escapeHTML(it.estado || '—');
                    const mot = escapeHTML(it.motivo || '—');
                    return `<tr>
                        <td>${emp}</td>
                        <td>${tipo}</td>
                        <td>${est}</td>
                        <td>${mot}</td>
                    </tr>`;
                }).join('');

                body.innerHTML = `
                    <div class="muted">Total: <strong>${items.length}</strong></div>
                    <table class="day-table">
                        <thead>
                            <tr>
                                <th>Empleado</th>
                                <th>Tipo</th>
                                <th>Estado</th>
                                <th>Motivo</th>
                            </tr>
                        </thead>
                        <tbody>${rows}</tbody>
                    </table>
                `;
            }

            modal.style.display = 'flex';
        }
        function closeDayDetail(){ document.getElementById('dayDetailModal').style.display = 'none'; }

        // Cerrar modales al hacer clic fuera
        window.addEventListener('click', function(ev){
            const m1 = document.getElementById('moreRequestsModal');
            const m2 = document.getElementById('passwordModal');
            const m3 = document.getElementById('dayDetailModal');
            if (ev.target === m1) closeMoreRequestsModal();
            if (ev.target === m2) closePasswordModal();
            if (ev.target === m3) closeDayDetail();
        });

        // Utilidad simple de escape
        function escapeHTML(str){
            return String(str).replace(/[&<>"']/g, function(m){
                return ({
                    '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'
                })[m];
            });
        }
    </script>
</body>
</html>
