<?php
session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require 'conexion.php';

// Asegurarse de que el usuario esté autenticado y tenga el rol correcto (cod_rol = 7)
if (!isset($_SESSION['user_id']) || !isset($_SESSION['role']) || $_SESSION['role'] != 7) {
    $_SESSION['error'] = 'Acceso no autorizado. Por favor, inicia sesión con una cuenta de usuario válida.';
    header("Location: login.php");
    exit;
}

$user_id = $_SESSION['user_id'];
$nombre_usuario = $_SESSION['Nom']; // Usar el nombre directamente desde la sesión

// 🛑 BLOQUEO VACACIONES: IDs que NO pueden generar vacaciones
$blocked_ids = [146,129,138,55,17,151,69,101,127,8,63,60,96,161,154,87,44,65];
$is_vac_blocked = in_array((int)$user_id, $blocked_ids, true);

// Obtener el mes y año actual
$current_month = date('m');
$current_year = date('Y');

// Obtener estadísticas de solicitudes del usuario con nuevos estados para el mes actual
$sql_pendientes = "SELECT COUNT(*) as total FROM solicitudes WHERE id_usuario = ? AND estado = 'Pendiente' AND MONTH(fecha_solicitud) = ? AND YEAR(fecha_solicitud) = ?";
$stmt_pendientes = $conn->prepare($sql_pendientes);
$stmt_pendientes->bind_param('iii', $user_id, $current_month, $current_year);
$stmt_pendientes->execute();
$pendientes = $stmt_pendientes->get_result()->fetch_assoc()['total'];
$stmt_pendientes->close();

$sql_aprobadas_jefe = "SELECT COUNT(*) as total FROM solicitudes WHERE id_usuario = ? AND 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('iii', $user_id, $current_month, $current_year);
$stmt_aprobadas_jefe->execute();
$aprobadas_jefe = $stmt_aprobadas_jefe->get_result()->fetch_assoc()['total'];
$stmt_aprobadas_jefe->close();

$sql_aprobadas_rrhh = "SELECT COUNT(*) as total FROM solicitudes WHERE id_usuario = ? AND estado = 'Aprobada por Recursos Humanos' AND MONTH(fecha_solicitud) = ? AND YEAR(fecha_solicitud) = ?";
$stmt_aprobadas_rrhh = $conn->prepare($sql_aprobadas_rrhh);
$stmt_aprobadas_rrhh->bind_param('iii', $user_id, $current_month, $current_year);
$stmt_aprobadas_rrhh->execute();
$aprobadas_rrhh = $stmt_aprobadas_rrhh->get_result()->fetch_assoc()['total'];
$stmt_aprobadas_rrhh->close();

$sql_rechazadas_jefe = "SELECT COUNT(*) as total FROM solicitudes WHERE id_usuario = ? AND estado = 'Rechazada por Jefe Inmediato' AND MONTH(fecha_solicitud) = ? AND YEAR(fecha_solicitud) = ?";
$stmt_rechazadas_jefe = $conn->prepare($sql_rechazadas_jefe);
$stmt_rechazadas_jefe->bind_param('iii', $user_id, $current_month, $current_year);
$stmt_rechazadas_jefe->execute();
$rechazadas_jefe = $stmt_rechazadas_jefe->get_result()->fetch_assoc()['total'];
$stmt_rechazadas_jefe->close();

$sql_rechazadas_rrhh = "SELECT COUNT(*) as total FROM solicitudes WHERE id_usuario = ? AND estado = 'Rechazada por Recursos Humanos' AND MONTH(fecha_solicitud) = ? AND YEAR(fecha_solicitud) = ?";
$stmt_rechazadas_rrhh = $conn->prepare($sql_rechazadas_rrhh);
$stmt_rechazadas_rrhh->bind_param('iii', $user_id, $current_month, $current_year);
$stmt_rechazadas_rrhh->execute();
$rechazadas_rrhh = $stmt_rechazadas_rrhh->get_result()->fetch_assoc()['total'];
$stmt_rechazadas_rrhh->close();

// Obtener fechas de solicitudes para el calendario (por defecto, mes y año actuales)
$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);
$first_day_of_month = date('w', strtotime("$selected_year-$selected_month-01"));

// 1) Colorear por estado (clase)
$sql_fechas = "SELECT DATE(fecha_salida) as fecha, estado 
               FROM solicitudes 
               WHERE id_usuario = ? 
               AND YEAR(fecha_salida) = ? 
               AND MONTH(fecha_salida) = ?";
$stmt_fechas = $conn->prepare($sql_fechas);
$stmt_fechas->bind_param('iii', $user_id, $selected_year, $selected_month);
$stmt_fechas->execute();
$result_fechas = $stmt_fechas->get_result();
$fechas_solicitudes = [];
if ($result_fechas) {
    while ($row = $result_fechas->fetch_assoc()) {
        $fechas_solicitudes[$row['fecha']] = strtolower(str_replace(' ', '-', str_replace('Recursos Humanos', 'rrhh', $row['estado'])));
    }
}
$stmt_fechas->close();

// 2) Detalles por día (para modal)
$sql_det = "SELECT DATE(fecha_salida) as fecha, tipo_permiso, estado, descripcion_motivo
            FROM solicitudes
            WHERE id_usuario = ?
              AND YEAR(fecha_salida) = ?
              AND MONTH(fecha_salida) = ?
            ORDER BY fecha_solicitud DESC";
$stmt_det = $conn->prepare($sql_det);
$stmt_det->bind_param('iii', $user_id, $selected_year, $selected_month);
$stmt_det->execute();
$res_det = $stmt_det->get_result();

$detalles_por_fecha = []; // 'Y-m-d' => [ {tipo_permiso, estado, descripcion_motivo}, ...]
if ($res_det) {
    while ($r = $res_det->fetch_assoc()) {
        $f = $r['fecha'];
        if (!isset($detalles_por_fecha[$f])) $detalles_por_fecha[$f] = [];
        $detalles_por_fecha[$f][] = [
            'tipo_permiso' => $r['tipo_permiso'] ?? '',
            'estado'       => $r['estado'] ?? '',
            'descripcion_motivo' => $r['descripcion_motivo'] ?? '',
        ];
    }
}
$stmt_det->close();

/**
 * NUEVA LÓGICA DE LÍMITE:
 * Contar SOLO permisos tipo 'Personal' con estado 'Aprobada por Recursos Humanos'
 * en el mes actual, para mostrar mensaje pero SIN bloquear el botón.
 */
$sql_personal_aprobadas_rrhh_limit = "SELECT COUNT(*) AS total
    FROM solicitudes
    WHERE id_usuario = ?
      AND tipo_permiso = 'Personal'
      AND estado = 'Aprobada por Recursos Humanos'
      AND MONTH(fecha_solicitud) = ?
      AND YEAR(fecha_solicitud) = ?";
$stmt_personal_aprob_rrhh = $conn->prepare($sql_personal_aprobadas_rrhh_limit);
$stmt_personal_aprob_rrhh->bind_param('iii', $user_id, $current_month, $current_year);
$stmt_personal_aprob_rrhh->execute();
$personal_aprobadas_rrhh_limit = $stmt_personal_aprob_rrhh->get_result()->fetch_assoc()['total'];
$stmt_personal_aprob_rrhh->close();

$max_requests_per_month = 3; // límite de Personales aprobados por RRHH
$remaining_requests = max(0, $max_requests_per_month - $personal_aprobadas_rrhh_limit);

$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 Solicitante</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; }
    .main-content h1 { font-size: 32px; color: #2c3e50; margin-bottom: 30px; text-align: center; border-bottom: 3px solid #68c8d8; padding-bottom: 10px; font-weight: 700; }

    /* Sections Grid */
    .dashboard-grid { display: grid; grid-template-columns: 2fr 1fr; gap: 30px; margin-bottom: 20px; }
    .top-sections { display: grid; gap: 20px; margin-bottom: 30px; }

    /* Request Section */
    .request-section { background: white; padding: 20px; border-radius: 10px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); 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 { background: linear-gradient(135deg, #5dade2, #3498db); transform: translateY(-2px); }
    .request-buttons button.blocked { background: #b0bec5 !important; opacity: 0.85; cursor: not-allowed; box-shadow: none; }

    /* Limit Notification */
    .limit-notification { background: white; padding: 20px; border-radius: 10px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); }
    .limit-notification h2 { font-size: 22px; color: #2c3e50; margin-bottom: 15px; }
    .limit-notification .warning { color: #e74c3c; font-weight: 500; }
    .limit-notification p { font-size: 16px; color: #7f8c8d; }

    /* Calendario (igual que lo tenías) */
    .calendar-section {
      background: white;
      padding: 22px;
      border-radius: 16px;
      box-shadow: 0 6px 28px rgba(0,0,0,.06);
      border: 1px solid #eef2f6;
    }

    .calendar-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      gap: 12px;
      margin-bottom: 16px;
      flex-wrap: wrap;
    }

    .calendar-header .title {
      font-size: 20px;
      font-weight: 600;
      color: #1f2d3d;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .calendar-header form select {
      padding: 10px 12px;
      border: 1px solid #e5e9f2;
      border-radius: 10px;
      background: #fff;
      font-size: 14px;
      transition: box-shadow .2s, border-color .2s;
    }
    .calendar-header form select:focus {
      outline: none;
      border-color: #68c8d8;
      box-shadow: 0 0 0 4px rgba(104,200,216,.15);
    }

    .calendar-legend {
      display: flex;
      flex-wrap: wrap;
      gap: 8px 12px;
      margin-bottom: 12px;
    }
    .calendar-legend .item {
      display: inline-flex;
      align-items: center;
      gap: 8px;
      font-size: 12px;
      color: #54627a;
      background: #f6f9fc;
      padding: 6px 10px;
      border-radius: 999px;
      border: 1px solid #edf2f7;
    }
    .calendar-legend .dot { width: 10px; height: 10px; border-radius: 50%; }

    .calendar-grid {
      display: grid;
      grid-template-columns: repeat(7, minmax(90px, 1fr));
      gap: 10px;
    }
    .weekday {
      background: #1f2d3d;
      color: #fff;
      padding: 8px 0;
      border-radius: 10px;
      font-weight: 600;
      font-size: 13px;
      letter-spacing: .3px;
      text-transform: uppercase;
      text-align: center;
    }

    .day-slot {}
    .day-slot.empty .day-card {
      background: #fbfdff;
      border-style: dashed;
      color: #9aa8b6;
    }
    .day-card {
      position: relative;
      display: flex;
      flex-direction: column;
      gap: 8px;
      background: #ffffff;
      border: 1px solid #eef2f6;
      border-radius: 14px;
      box-shadow: 0 2px 10px rgba(31,45,61,.04);
      padding: 10px;
      min-height: 84px;
      transition: transform .15s ease, box-shadow .15s ease, border-color .15s ease;
      aspect-ratio: 1 / 1;
      cursor: pointer;
    }
    .day-card:hover {
      transform: translateY(-2px);
      box-shadow: 0 8px 24px rgba(31,45,61,.08);
      border-color: #e2e8f0;
    }
    .day-card .date {
      font-weight: 700;
      color: #2c3e50;
      font-size: 16px;
      align-self: flex-start;
      background: #f5f9fc;
      border: 1px solid #edf2f7;
      border-radius: 8px;
      padding: 4px 7px;
      line-height: 1;
    }

    .state-chip {
      position: absolute;
      right: 8px;
      top: 8px;
      font-size: 11px;
      font-weight: 600;
      padding: 4px 8px;
      border-radius: 999px;
      border: 1px solid transparent;
      background: #f1f5f9;
      color: #334155;
    }

    .counter-badge {
      position: absolute;
      left: 8px;
      bottom: 8px;
      font-size: 12px;
      font-weight: 700;
      padding: 3px 7px;
      border-radius: 999px;
      background: #111827;
      color: #fff;
      opacity: .9;
    }

    .day-card.pendiente        { border-left: 4px solid #f39c12; }
    .day-card.aprobada-por-jefe-inmediato { border-left: 4px solid #3498db; }
    .day-card.aprobada-por-rrhh           { border-left: 4px solid #27ae60; }
    .day-card.rechazada-por-jefe-inmediato{ border-left: 4px solid #e74c3c; }
    .day-card.rechazada-por-rrhh          { border-left: 4px solid #c0392b; }

    .day-card.pendiente .state-chip { background:#fff4e1; color:#7a4d00; border-color:#ffd79a; }
    .day-card.aprobada-por-jefe-inmediato .state-chip { background:#e7f3ff; color:#0c4a78; border-color:#b3dcff; }
    .day-card.aprobada-por-rrhh .state-chip { background:#e9f8ef; color:#0f5132; border-color:#bbe5c9; }
    .day-card.rechazada-por-jefe-inmediato .state-chip { background:#ffebee; color:#7a1c1c; border-color:#ffc2c7; }
    .day-card.rechazada-por-rrhh .state-chip { background:#ffe9e6; color:#7a2020; border-color:#ffb5ab; }

    .day-card.day--today {
      box-shadow: 0 0 0 3px rgba(104,200,216,.35);
      border-color: #68c8d8;
    }

    .calendar-grid .day-slot.weekend .day-card {
      background: linear-gradient(180deg,#ffffff 0%, #fbfdff 100%);
    }

    .cards-section { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; }
    .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-jefe { border-left: 5px solid #3498db; }
    .card.aprobadas-rrhh { border-left: 5px solid #27ae60; }
    .card.rechazadas-jefe { border-left: 5px solid #e74c3c; }
    .card.rechazadas-rrhh { border-left: 5px solid #c0392b; }

    .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.5); justify-content: center; align-items: center; z-index: 2000; backdrop-filter: blur(4px); }
    .modal-content { background: white; padding: 22px; border-radius: 14px; width: 92%; max-width: 680px; box-shadow: 0 6px 25px rgba(0, 0, 0, 0.25); position: relative; }
    .modal-content h2 { font-size: 20px; color: #1f2d3d; margin-bottom: 12px; }
    .modal-content .close { position: absolute; top: 12px; right: 16px; font-size: 24px; color: #7f8c8d; cursor: pointer; transition: color 0.2s; }
    .modal-content .close:hover { color: #c0392b; }
    .details-subtitle { color:#6b7280; font-size:13px; margin-bottom:10px; }
    .state-group { margin-top: 10px; border-top:1px solid #edf2f7; padding-top:10px; }
    .state-title { font-weight:700; font-size:14px; margin-bottom:6px; display:flex; align-items:center; gap:8px; }
    .state-count { font-size:12px; background:#111827; color:#fff; border-radius:999px; padding:2px 7px; }
    .req-item { background:#f9fbfd; border:1px solid #ecf0f1; border-radius:10px; padding:10px; margin-bottom:8px; }
    .req-item .tag { font-size:12px; font-weight:700; background:#eef2f6; border:1px solid #e5e7eb; color:#374151; padding:2px 8px; border-radius:999px; margin-right:8px; }
    .req-item .desc { color:#6b7280; font-size:13px; margin-top:6px; }

    .dot { width:10px; height:10px; border-radius:50%; display:inline-block; }
    .dot.pendiente { background:#f39c12; }
    .dot.jefe { background:#3498db; }
    .dot.rrhh { background:#27ae60; }
    .dot.rjefe { background:#e74c3c; }
    .dot.rrrhh { background:#c0392b; }

    @media (max-width: 1024px) {
        .sidebar { width: 220px; }
        .main-content { margin-left: 220px; width: calc(100% - 220px); padding: 25px; }
        .dashboard-grid { grid-template-columns: 1fr; }
    }
    @media (max-width: 900px) {
      .calendar-grid { grid-template-columns: repeat(7, minmax(64px, 1fr)); gap: 8px; }
      .day-card { min-height: 72px; }
      .day-card .date { font-size: 14px; }
    }
    @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; }
        .top-sections, .dashboard-grid { grid-template-columns: 1fr; }
    }
    @media (max-width: 600px) {
      .calendar-header .title { font-size: 18px; }
      .state-chip { display: none; }
    }
    @media (max-width: 480px) {
        .cards-section { grid-template-columns: 1fr; }
        .request-buttons button { width: 100%; margin-bottom: 10px; }
        .modal-content { padding: 16px; }
    }

    .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); }
    @keyframes pulseGlowRed {
        0% { box-shadow: 0 0 10px rgba(231, 76, 60, 0.8), 0 0 20px rgba(231, 76, 60, 0.5); }
        50% { box-shadow: 0 0 20px rgba(231, 76, 60, 1), 0 0 40px rgba(231, 76, 60, 0.7); }
        100% { box-shadow: 0 0 10px rgba(231, 76, 60, 0.8), 0 0 20px rgba(231, 76, 60, 0.5); }
    }

    #password-alert { color: #e74c3c; font-size: 14px; margin: 8px 0; display: none; text-align: center; }

    .modal-buttons {
        margin-top: 15px;
        display: flex;
        justify-content: flex-end;
        gap: 10px;
    }
    .modal-buttons .cancel {
        background: #bdc3c7;
        border: none;
        padding: 8px 14px;
        border-radius: 6px;
        color: #fff;
        cursor: pointer;
    }
    .modal-buttons .submit {
        background: #68c8d8;
        border: none;
        padding: 8px 14px;
        border-radius: 6px;
        color: #fff;
        cursor: pointer;
    }
    .input-group {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 10px;
        border: 1px solid #e5e7eb;
        padding: 8px 10px;
        border-radius: 8px;
    }
    .input-group i {
        color: #9ca3af;
    }
    .input-group input {
        border: none;
        outline: none;
        flex: 1;
    }
</style>
</head>
<body>
    <button class="toggle-btn" onclick="toggleSidebar()"><i class="fas fa-bars"></i></button>
    <div class="container">
        <!-- Menú lateral -->
        <div class="sidebar" id="sidebar">
            <h2>Panel Solicitante</h2>
            <ul>
                <li><a href="dashboard_usuario.php"><i class="fas fa-tachometer-alt"></i> Inicio</a></li>
                <li><a href="historial_solicitudes.php"><i class="fas fa-list"></i> Mis Solicitudes</a></li>
                <li><a id="perfilLink" href="panel_empleado.php"><i class="fas fa-user"></i> Perfil</a></li>
                <li><a href="vacaciones.php"><i class="fas fa-umbrella-beach"></i> Vacaciones</a></li>
                <li>
                    <a href="https://sistemas.proasol.gob.hn/denuncias_proasol/index.html?src=myhr_sidebar" target="_blank" rel="noopener">
                        <i class="fas fa-shield-alt"></i> Denuncia-CPEP
                    </a>
                </li>
                <li><a href="logout.php"><i class="fas fa-sign-out-alt"></i> Cerrar Sesión</a></li>
            </ul>
        </div>

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

            <!-- Top Sections -->
            <div class="top-sections">
                <!-- Request Section -->
                <div class="request-section">
                    <h2><i class="fas fa-plus"></i> Nueva Solicitud de Permiso</h2>
                    <div class="request-buttons">
                        <!-- El botón YA NO se bloquea, siempre está activo -->
                        <button onclick="window.location.href='pase_salida.php'">
                            <i class="fas fa-plus"></i> Generar Nuevo Permiso
                        </button>
                        <button id="btnVacaciones"
                                class="<?= $is_vac_blocked ? 'blocked' : '' ?>"
                                onclick="genVacaciones()"
                                title="<?= $is_vac_blocked ? 'Bloqueado: consulta en RRHH' : '' ?>">
                            <i class="fas fa-umbrella-beach"></i> Generar Vacaciones
                        </button>
                        <button onclick="openModal()">
                            <i class="fas fa-ellipsis-h"></i> Más Solicitudes
                        </button>
                    </div>
                </div>

                <!-- Limit Notification -->
                <div class="limit-notification">
                    <h2><i class="fas fa-exclamation-triangle"></i> Límite de Solicitudes</h2>
                    <?php if ($personal_aprobadas_rrhh_limit >= $max_requests_per_month): ?>
                        <p class="warning">
                            ⚠️ Has alcanzado el límite de <?= $max_requests_per_month ?> permisos <strong>Personales</strong>
                            <strong>aprobados por Recursos Humanos</strong> este mes.<br>
                            A partir de ahora <strong>solo puedes usar permisos de tipo Oficial</strong>.
                        </p>
                    <?php else: ?>
                        <p>
                            ℹ️ Tienes <?= $personal_aprobadas_rrhh_limit ?> permisos <strong>Personales</strong> aprobados por Recursos Humanos
                            este mes. Te quedan <strong><?= $remaining_requests ?></strong> personales disponibles para aprobación.
                        </p>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Dashboard Grid -->
            <div class="dashboard-grid">
                <!-- Calendar -->
                <div class="calendar-section">
                    <div class="calendar-header">
                        <div class="title">
                            <i class="fas fa-calendar-alt"></i>
                            Mis Permisos (Fecha de Salida)
                        </div>
                        <form method="GET" action="dashboard_usuario.php">
                            <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) {
                                    $selected = $selected_month == $num ? 'selected' : '';
                                    echo "<option value='$num' $selected>$name</option>";
                                }
                                ?>
                            </select>
                            <select name="year" onchange="this.form.submit()">
                                <?php
                                for ($year = date('Y') + 1; $year >= date('Y') - 5; $year--) {
                                    $selected = $selected_year == $year ? 'selected' : '';
                                    echo "<option value='$year' $selected>$year</option>";
                                }
                                ?>
                            </select>
                        </form>
                    </div>

                    <!-- Leyenda -->
                    <div class="calendar-legend">
                        <span class="item"><span class="dot" style="background:#f39c12"></span>Pendiente</span>
                        <span class="item"><span class="dot" style="background:#3498db"></span>Aprobada por Jefe</span>
                        <span class="item"><span class="dot" style="background:#27ae60"></span>Aprobada por RRHH</span>
                        <span class="item"><span class="dot" style="background:#e74c3c"></span>Rechazada por Jefe</span>
                        <span class="item"><span class="dot" style="background:#c0392b"></span>Rechazada por RRHH</span>
                        <span class="item"><span class="dot" style="background:#68c8d8"></span>Hoy</span>
                    </div>

                    <div class="calendar-grid">
                        <!-- Cabeceras -->
                        <div class="weekday">Lun</div>
                        <div class="weekday">Mar</div>
                        <div class="weekday">Mié</div>
                        <div class="weekday">Jue</div>
                        <div class="weekday">Vie</div>
                        <div class="weekday">Sáb</div>
                        <div class="weekday">Dom</div>

                        <?php
                        // Alinear al lunes
                        $first_day_of_month = ($first_day_of_month + 6) % 7;

                        // Celdas vacías antes del día 1
                        for ($i = 0; $i < $first_day_of_month; $i++) {
                            echo "<div class='day-slot empty'><div class='day-card'><span class=\"date\">&nbsp;</span></div></div>";
                        }

                        $today = date('Y-m-d');

                        for ($day = 1; $day <= $days_in_month; $day++) {
                            $current_date = "$selected_year-" . str_pad($selected_month, 2, "0", STR_PAD_LEFT) . "-" . str_pad($day, 2, "0", STR_PAD_LEFT);
                            $estadoClass = isset($fechas_solicitudes[$current_date]) ? $fechas_solicitudes[$current_date] : "";
                            $label = '';
                            if ($estadoClass) {
                                $label = ucwords(str_replace(['-', 'rrhh'], [' ', 'RRHH'], $estadoClass));
                            }

                            $dayCount = isset($detalles_por_fecha[$current_date]) ? count($detalles_por_fecha[$current_date]) : 0;

                            $pos = ($first_day_of_month + ($day - 1)) % 7; // 0..6 (0=Lun)
                            $isWeekend = ($pos == 5 || $pos == 6);

                            $slotClasses = 'day-slot' . ($isWeekend ? ' weekend' : '');
                            $cardClasses = 'day-card' . ($estadoClass ? ' ' . $estadoClass . ' day--has-state' : '') . ($current_date === $today ? ' day--today' : '');

                            echo "<div class='$slotClasses'>";
                              echo "<div class='$cardClasses' data-date='".htmlspecialchars($current_date, ENT_QUOTES)."' data-state='".htmlspecialchars($label, ENT_QUOTES)."'>";
                                echo "<span class='date'>$day</span>";
                                if ($label) echo "<span class='state-chip'>".htmlspecialchars($label)."</span>";
                                if ($dayCount > 1) echo "<span class='counter-badge'>+$dayCount</span>";
                              echo "</div>";
                            echo "</div>";
                        }
                        ?>
                    </div>
                </div>

                <!-- Stats -->
                <div class="cards-section">
                    <div class="card pendientes">
                        <h3>Pendientes</h3>
                        <p><?= $pendientes ?></p>
                    </div>
                    <div class="card aprobadas-jefe">
                        <h3>Aprobadas por Jefe</h3>
                        <p><?= $aprobadas_jefe ?></p>
                    </div>
                    <div class="card aprobadas-rrhh">
                        <h3>Aprobadas por RRHH</h3>
                        <p><?= $aprobadas_rrhh ?></p>
                    </div>
                    <div class="card rechazadas-jefe">
                        <h3>Rechazadas por Jefe</h3>
                        <p><?= $rechazadas_jefe ?></p>
                    </div>
                    <div class="card rechazadas-rrhh">
                        <h3>Rechazadas por RRHH</h3>
                        <p><?= $rechazadas_rrhh ?></p>
                    </div>
                </div>
            </div>

            <!-- Modal "Más Solicitudes" -->
            <div id="moreRequestsModal" class="modal">
                <div class="modal-content">
                    <span class="close" onclick="closeModal()">×</span>
                    <h2><i class="fas fa-plus"></i> Más Solicitudes</h2>
                    <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>
                            <option value="Otros">Otros</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">
                            <button type="button" class="cancel" onclick="closeModal()">Cancelar</button>
                            <button type="submit" class="submit">Enviar Solicitud</button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Modal Detalles Día -->
            <div id="dayDetailsModal" class="modal">
              <div class="modal-content">
                <span class="close" onclick="closeDayDetails()">×</span>
                <h2 id="detailsTitle">Detalles del día</h2>
                <div class="details-subtitle" id="detailsSubtitle"></div>
                <div id="detailsBody"></div>
              </div>
            </div>

        </div>
    </div>

    <!-- Modal para cambiar contraseña -->
    <div id="passwordModal" class="modal">
        <div class="modal-content">
            <span class="close" onclick="closePasswordModal()">×</span>
            <h2><i class="fas fa-lock"></i> Cambiar Contraseña</h2>
            <form action="cambiar_password.php" method="POST">
                <div class="input-group">
                    <i class="fas fa-key"></i>
                    <input type="password" id="password" name="password" required minlength="6" placeholder="Nueva contraseña">
                </div>
                <div class="input-group">
                    <i class="fas fa-check-circle"></i>
                    <input type="password" id="confirm_password" name="confirm_password" required placeholder="Confirmar contraseña">
                </div>
                <div id="password-alert">⚠️ Las contraseñas no coinciden.</div>
                <div class="modal-buttons">
                    <button type="button" class="cancel" onclick="closePasswordModal()">Cancelar</button>
                    <button type="submit" class="submit">Guardar</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Botón flotante para cambiar contraseña -->
    <button class="floating-btn" onclick="openPasswordModal()">
        <i class="fas fa-key"></i>
    </button>

    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <script>
        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%';
            }
        }

        function openModal() {
            document.getElementById('moreRequestsModal').style.display = 'flex';
        }
        function closeModal() {
            document.getElementById('moreRequestsModal').style.display = 'none';
            document.getElementById('moreRequestsForm').reset();
        }
        window.onclick = function(event) {
            const modal1 = document.getElementById('moreRequestsModal');
            const modal2 = document.getElementById('dayDetailsModal');
            const modal3 = document.getElementById('passwordModal');
            if (event.target === modal1) closeModal();
            if (event.target === modal2) closeDayDetails();
            if (event.target === modal3) closePasswordModal();
        }

        const UID = <?= json_encode($user_id) ?>;
        const IS_VAC_BLOCKED = <?= $is_vac_blocked ? 'true' : 'false' ?>;
        const k = (suffix) => `u:${UID}:${suffix}`;
        const markProfile  = () => localStorage.setItem(k('didProfile'), '1');
        const markPassword = () => localStorage.setItem(k('didPassword'), '1');
        const hasProfile   = () => localStorage.getItem(k('didProfile')) === '1';
        const hasPassword  = () => localStorage.getItem(k('didPassword')) === '1';
        const isComplete   = () => hasProfile() && hasPassword();

        function genVacaciones() {
            if (IS_VAC_BLOCKED) {
                Swal.fire({
                    icon: 'warning',
                    title: 'No puedes generar vacaciones',
                    text: 'Acércate a Recursos Humanos para más información.',
                    confirmButtonText: 'Entendido',
                    confirmButtonColor: '#e74c3c'
                });
                return;
            }
            window.location.href = 'pase_vacaciones.php';
        }

        function openPasswordModal() {
            markPassword();
            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";
                }
            });
        }

        function wireProfileLinks() {
            document.querySelectorAll("a[href='panel_empleado.php']").forEach(a => {
                a.addEventListener('click', () => { markProfile(); });
            });
        }
        wireProfileLinks();

        async function showOnboarding() {
            if (isComplete()) return;
            const htmlStatus = () => `
                <div style="text-align:left; font-size:15px; line-height:1.5;">
                    <p style="margin-bottom:8px;"><i class="fas fa-user-edit"></i>
                        <strong>Actualiza tus datos personales</strong> en la pestaña <strong>Perfil</strong> del menú lateral.
                    </p>
                    <p><i class="fas fa-key"></i>
                        <strong>Cambia tu contraseña</strong> dando clic en el <strong>icono rojo</strong> en la parte <strong>inferior derecha</strong>.
                    </p>
                    <hr style="margin:10px 0;">
                    <p style="margin:4px 0;">Estado actual:</p>
                    <ul style="margin-left:18px;">
                        <li>Perfil: ${hasProfile() ? '✅ hecho' : '❌ pendiente'}</li>
                        <li>Contraseña: ${hasPassword() ? '✅ hecho' : '❌ pendiente'}</li>
                    </ul>
                </div>
            `;
            const result = await Swal.fire({
                icon: 'info',
                title: 'Antes de continuar',
                html: htmlStatus(),
                showConfirmButton: !hasProfile(),
                confirmButtonText: 'Ir a Perfil',
                showDenyButton: !hasPassword(),
                denyButtonText: 'Cambiar Contraseña',
                confirmButtonColor: '#68c8d8',
                denyButtonColor: '#e74c3c',
                allowOutsideClick: false,
                allowEscapeKey: false,
                allowEnterKey: false,
                showCloseButton: false
            });
            if (result.isConfirmed) { markProfile(); window.location.href = 'panel_empleado.php'; return; }
            if (result.isDenied) { openPasswordModal(); return; }
            if (!isComplete()) showOnboarding();
        }
        window.addEventListener('load', () => { if (!isComplete()) showOnboarding(); });

        const detallesPorFecha = <?= json_encode($detalles_por_fecha, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;

        function estadoDotClass(estado) {
          const e = (estado||'').toLowerCase();
          if (e.includes('aprobada por recursos humanos')) return 'rrhh';
          if (e.includes('aprobada por jefe inmediato'))   return 'jefe';
          if (e.includes('rechazada por recursos humanos')) return 'rrrhh';
          if (e.includes('rechazada por jefe inmediato'))   return 'rjefe';
          return 'pendiente';
        }

        function openDayDetails(dateStr) {
          const modal = document.getElementById('dayDetailsModal');
          const title = document.getElementById('detailsTitle');
          const subtitle = document.getElementById('detailsSubtitle');
          const body = document.getElementById('detailsBody');

          const f = new Date(dateStr + 'T00:00:00');
          const opts = { day: '2-digit', month: 'long', year: 'numeric' };
          const pretty = f.toLocaleDateString('es-ES', opts);

          title.textContent = `Detalles del ${pretty}`;

          const items = detallesPorFecha[dateStr] || [];
          subtitle.textContent = items.length
            ? `Se encontraron ${items.length} solicitud(es).`
            : 'No hay solicitudes para este día.';

          const groups = {};
          items.forEach(it => {
            const est = it.estado || 'Sin estado';
            if (!groups[est]) groups[est] = [];
            groups[est].push(it);
          });

          body.innerHTML = '';
          if (items.length) {
            Object.keys(groups).forEach(estado => {
              const arr = groups[estado];
              const dotC = estadoDotClass(estado);
              const wrapper = document.createElement('div');
              wrapper.className = 'state-group';
              wrapper.innerHTML = `
                <div class="state-title">
                  <span class="dot ${dotC}"></span>
                  <span>${estado}</span>
                  <span class="state-count">${arr.length}</span>
                </div>
              `;
              arr.forEach(it => {
                const div = document.createElement('div');
                div.className = 'req-item';
                const tipo = it.tipo_permiso ? `<span class="tag">${it.tipo_permiso}</span>` : '';
                const desc = it.descripcion_motivo
                    ? `<div class="desc">${(it.descripcion_motivo+'').slice(0,220)}${it.descripcion_motivo.length>220?'…':''}</div>`
                    : '';
                div.innerHTML = `${tipo}${desc}`;
                wrapper.appendChild(div);
              });
              body.appendChild(wrapper);
            });
          }

          modal.style.display = 'flex';
        }

        function closeDayDetails(){ document.getElementById('dayDetailsModal').style.display = 'none'; }

        document.addEventListener('click', (e) => {
          const card = e.target.closest('.day-card');
          if (!card) return;
          const date = card.getAttribute('data-date');
          if (!date) return;
          openDayDetails(date);
        });

        const INACTIVITY_LIMIT_MS = 5 * 60 * 1000; // 5 minutos
        let inactivityTimer = null;
        let sessionExpired = false;

        function startInactivityTimer() {
            clearTimeout(inactivityTimer);
            if (sessionExpired) return;

            inactivityTimer = setTimeout(() => {
                sessionExpired = true;
                Swal.fire({
                    title: 'Sesión suspendida',
                    text: 'Tu sesión ha sido suspendida por inactividad. Por seguridad debes iniciar sesión nuevamente.',
                    icon: 'warning',
                    confirmButtonText: 'Aceptar'
                }).then(() => {
                    window.location.href = 'logout.php?reason=timeout';
                });
            }, INACTIVITY_LIMIT_MS);
        }

        function resetInactivityTimer() {
            if (sessionExpired) return;
            startInactivityTimer();
        }

        ['load', 'mousemove', 'mousedown', 'click', 'scroll', 'keypress', 'touchstart', 'touchmove'].forEach(evt => {
            window.addEventListener(evt, resetInactivityTimer, true);
        });

        startInactivityTimer();
    </script>
</body>
</html>
