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

// 🔧 Modo depuración (quítalo en producción)
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
ini_set('display_errors', 1);
error_reporting(E_ALL);

// ✅ Permitir acceso a roles 8 y 12
if (
    !isset($_SESSION['user_id']) ||
    !isset($_SESSION['role']) ||
    ($_SESSION['role'] != 8 && $_SESSION['role'] != 12)
) {
    $_SESSION['error'] = 'Acceso no autorizado. Por favor, inicia sesión con una cuenta válida.';
    header("Location: login.php");
    exit;
}

$userId = (int)$_SESSION['user_id'];

/**
 * =========================
 *   🔁 Jerarquía (sub-árbol)
 * =========================
 */
function getSubtreeUserIds(mysqli $conn, int $viewerId): array {
    $ids = [$viewerId];
    $q = [$viewerId];
    $stmt = $conn->prepare("SELECT ID FROM accounts WHERE superior_id = ?");
    while ($q) {
        $next = [];
        foreach ($q as $p) {
            $stmt->bind_param('i', $p);
            $stmt->execute();
            $r = $stmt->get_result();
            while ($row = $r->fetch_assoc()) {
                $id = (int)$row['ID'];
                if (!in_array($id, $ids, true)) {
                    $ids[] = $id;
                    $next[] = $id;
                }
            }
        }
        $q = $next;
    }
    $stmt->close();
    return $ids;
}

// 🔹 IDs de todo el subárbol del jefe
$ids = getSubtreeUserIds($conn, $userId);
$ids = array_values(array_unique($ids));
if (count($ids) === 0) { $ids = [$userId]; }

$ph = implode(',', array_fill(0, count($ids), '?'));

// =========================
//  Consulta principal (solo jerarquía)
// =========================
$sql = "
  SELECT 
      s.*, 
      CONCAT_WS(' ', u.Nom, u.Nom2, u.Ape, u.Ape2) AS nombre_funcionario
  FROM solicitudes s
  JOIN accounts u ON u.ID = s.id_usuario
  WHERE s.estado = 'Pendiente'
    AND s.tipo_permiso IN ('Personal','Oficial')
    AND s.id_usuario IN ($ph)           -- subárbol por superior_id
    AND u.ID <> ?                       -- no mostrar mis propias solicitudes
    AND u.superior_id = 1    
  ORDER BY s.fecha_salida DESC, s.id DESC
";

$stmt   = $conn->prepare($sql);
$types  = str_repeat('i', count($ids)) . 'i';
$params = [...$ids, $userId];
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Panel Jefe de Departamento - Solicitudes Pendientes</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>
:root{
    --color-bg:#f2f5fa;
    --color-surface:#ffffff;
    --color-primary:#68c8d8;
    --color-primary-dark:#2196b5;
    --color-accent:#2c3e50;
    --color-text:#2c3e50;
    --color-muted:#7b8a9a;
    --radius-lg:14px;
    --shadow-soft:0 8px 18px rgba(0,0,0,0.06);
    --shadow-hover:0 12px 26px rgba(0,0,0,0.10);
}

*{
    margin:0;
    padding:0;
    box-sizing:border-box;
    font-family:'Roboto',sans-serif;
}

body{
    background:var(--color-bg);
    color:var(--color-text);
    line-height:1.6;
}

/* ========== LAYOUT GENERAL ========== */
.container{
    display:flex;
    min-height:100vh;
}

/* ========== SIDEBAR ========== */
.sidebar{
    width:260px;
    background:linear-gradient(145deg,#2c3e50,#34495e);
    color:white;
    padding:20px 16px;
    position:fixed;
    inset:0 auto 0 0;
    height:100%;
    z-index:1000;
    box-shadow:4px 0 12px rgba(0,0,0,0.18);
    transform:translateX(0);
    transition:transform .3s ease;
}

.sidebar-header{
    display:flex;
    align-items:center;
    justify-content:center;
    gap:8px;
    margin-bottom:28px;
}

.sidebar-header-icon{
    width:36px;
    height:36px;
    border-radius:50%;
    background:rgba(104,200,216,0.14);
    display:flex;
    align-items:center;
    justify-content:center;
    font-size:18px;
    color:#68c8d8;
}

.sidebar h2{
    font-size:20px;
    font-weight:600;
    color:#ecf0f1;
}

.sidebar ul{
    list-style:none;
}

.sidebar ul li{
    margin-bottom:10px;
}

.sidebar ul li a{
    color:#ecf0f1;
    text-decoration:none;
    font-size:15px;
    display:flex;
    align-items:center;
    padding:10px 12px;
    border-radius:8px;
    transition:background .25s ease,color .25s ease,transform .1s ease;
}

.sidebar ul li a i{
    margin-right:10px;
    font-size:15px;
    width:18px;
    text-align:center;
}

.sidebar ul li a:hover{
    background:rgba(104,200,216,0.20);
    color:#ffffff;
    transform:translateX(2px);
}

.sidebar ul li a:active{
    transform:translateX(0);
}

/* ========== TOPBAR / CONTENIDO ========== */
.main-content{
    flex-grow:1;
    padding:24px 30px 32px;
    margin-left:260px;
    width:calc(100% - 260px);
    transition:margin-left .3s ease,width .3s ease;
}

.topbar{
    display:flex;
    align-items:center;
    justify-content:space-between;
    margin-bottom:18px;
    gap:12px;
}

.topbar-left{
    display:flex;
    flex-direction:column;
    gap:4px;
}

.topbar-title{
    font-size:22px;
    font-weight:600;
    display:flex;
    align-items:center;
    gap:8px;
}

.topbar-title i{
    color:var(--color-primary);
}

.topbar-subtitle{
    font-size:13px;
    color:var(--color-muted);
}

.topbar-user{
    display:flex;
    align-items:center;
    gap:10px;
    background:var(--color-surface);
    padding:8px 12px;
    border-radius:999px;
    box-shadow:var(--shadow-soft);
}

.topbar-user-avatar{
    width:30px;
    height:30px;
    border-radius:50%;
    background:linear-gradient(135deg,#68c8d8,#2c3e50);
    display:flex;
    align-items:center;
    justify-content:center;
    color:#fff;
    font-size:14px;
    font-weight:600;
}

.topbar-user-name{
    font-size:14px;
    font-weight:500;
}

/* Título sección */
.main-content h1{
    font-size:18px;
    margin:10px 0 22px;
    font-weight:600;
    color:#1c2733;
    border-bottom:2px solid rgba(104,200,216,0.35);
    padding-bottom:6px;
}

/* ========== BOTÓN TOGGLE MOBILE ========== */
.toggle-btn{
    display:none;
    position:fixed;
    left:16px;
    top:16px;
    background:var(--color-primary);
    color:#ffffff;
    border:none;
    padding:9px 11px;
    border-radius:999px;
    cursor:pointer;
    z-index:1100;
    box-shadow:0 4px 10px rgba(0,0,0,0.25);
    display:flex;
    align-items:center;
    justify-content:center;
}

.toggle-btn i{
    font-size:18px;
}

/* ========== GRID DE TARJETAS ========== */
.dashboard-grid{
    display:grid;
    grid-template-columns:repeat(auto-fit,minmax(320px,1fr));
    gap:20px;
}

/* CARD */
.solicitud-card{
    background:var(--color-surface);
    border-radius:var(--radius-lg);
    box-shadow:var(--shadow-soft);
    border:1px solid #e3e9f2;
    display:flex;
    flex-direction:column;
    transition:transform .18s ease,box-shadow .18s ease,border-color .18s ease;
    overflow:hidden;
}

.solicitud-card:hover{
    transform:translateY(-4px);
    box-shadow:var(--shadow-hover);
    border-color:rgba(104,200,216,0.4);
}

.card-header{
    display:flex;
    justify-content:space-between;
    align-items:center;
    padding:12px 16px;
    border-bottom:1px solid #edf1f7;
    background:linear-gradient(180deg,#ffffff 0%,#f7fbff 100%);
}

.title{
    font-weight:600;
    display:flex;
    align-items:center;
    gap:8px;
    font-size:15px;
    color:#1f2933;
}

.title i{
    font-size:18px;
    color:var(--color-primary-dark);
}

.badges{
    display:flex;
    flex-wrap:wrap;
    gap:6px;
    justify-content:flex-end;
}

.badge{
    font-size:11px;
    padding:4px 8px;
    border-radius:999px;
    background:#eef7ff;
    color:#1f6fb2;
    font-weight:500;
}

.badge-warning{
    background:#fff4e5;
    color:#ad6b1f;
}

/* CUERPO CARD */
.card-body{
    padding:12px 16px 10px;
    display:grid;
    gap:6px;
}

.row{
    display:grid;
    grid-template-columns:120px 1fr;
    gap:6px;
    align-items:flex-start;
}

.row .label{
    color:#6b7c93;
    font-weight:500;
    font-size:13px;
}

.row .value{
    font-size:14px;
    color:#2b3a4a;
}

/* ACCIONES */
.actions{
    margin-top:auto;
    padding:12px 14px 14px;
    border-top:1px solid #edf1f7;
    background:#f9fbff;
}

.actions textarea{
    width:100%;
    padding:9px 10px;
    border:1px solid #d1d9e6;
    border-radius:8px;
    resize:vertical;
    font-size:13px;
    min-height:70px;
    outline:none;
    transition:border-color .2s ease,box-shadow .2s ease;
}

.actions textarea:focus{
    border-color:var(--color-primary);
    box-shadow:0 0 0 1px rgba(104,200,216,0.45);
}

.actions-top{
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:8px;
    margin-bottom:10px;
}

.btn-preview{
    background:#e9f3ff;
    color:#0b5cab;
    border:1px solid #cfe0ff;
    font-size:12px;
    padding:6px 10px;
    border-radius:999px;
    cursor:pointer;
    display:inline-flex;
    align-items:center;
    gap:5px;
    flex-shrink:0;
}

.btn-preview i{
    font-size:12px;
}

.btn-preview:hover{
    background:#f3f9ff;
}

.button-group{
    display:flex;
    gap:8px;
    flex-wrap:wrap;
    margin-top:10px;
}

.btn{
    flex:1;
    padding:9px 10px;
    border:none;
    border-radius:8px;
    cursor:pointer;
    font-size:14px;
    font-weight:600;
    display:flex;
    align-items:center;
    justify-content:center;
    gap:6px;
    transition:transform .1s ease,box-shadow .12s ease,opacity .12s ease;
}

.btn-approve{
    background:linear-gradient(135deg,#27ae60,#219653);
    color:#fff;
    box-shadow:0 4px 12px rgba(39,174,96,0.35);
}

.btn-reject{
    background:linear-gradient(135deg,#c0392b,#a93226);
    color:#fff;
    box-shadow:0 4px 12px rgba(192,57,43,0.35);
}

.btn:active{
    transform:scale(.97);
    box-shadow:none;
}

/* TARJETA VACÍA */
.card-empty{
    max-width:480px;
    margin:0 auto;
    text-align:center;
    padding:26px 20px 28px;
}

.card-empty p{
    color:#7a899c;
    font-size:14px;
}

/* ========== MODAL PREVIEW ========== */
.modal{
    display:none;
    position:fixed;
    inset:0;
    background:rgba(0,0,0,.45);
    z-index:2000;
    align-items:center;
    justify-content:center;
    padding:16px;
}

.modal.open{
    display:flex;
}

.modal-card{
    width:min(1100px,100%);
    height:min(85vh,900px);
    background:#fff;
    border-radius:14px;
    overflow:hidden;
    box-shadow:0 16px 50px rgba(0,0,0,.35);
    display:flex;
    flex-direction:column;
}

.modal-header{
    display:flex;
    justify-content:space-between;
    align-items:center;
    padding:10px 16px;
    border-bottom:1px solid #e2e8f0;
    background:#f8fbff;
}

.modal-title{
    font-weight:600;
    font-size:14px;
    display:flex;
    align-items:center;
    gap:6px;
}

.modal-title i{
    color:var(--color-primary-dark);
}

.modal-close{
    background:none;
    border:none;
    font-size:13px;
    cursor:pointer;
    color:#54657f;
    padding:6px 10px;
    border-radius:999px;
}

.modal-close:hover{
    background:#e3edf9;
}

.modal-iframe{
    width:100%;
    height:100%;
    border:0;
}

/* ========== RESPONSIVE ========== */
@media (max-width: 992px){
    .sidebar{
        transform:translateX(-260px);
    }
    .sidebar.open{
        transform:translateX(0);
    }
    .toggle-btn{
        display:flex;
    }
    .main-content{
        margin-left:0;
        width:100%;
        padding:70px 16px 24px;
    }
    .topbar{
        flex-direction:column;
        align-items:flex-start;
    }
    .topbar-user{
        align-self:flex-end;
    }
}

@media (max-width: 600px){
    .dashboard-grid{
        grid-template-columns:1fr;
    }
    .row{
        grid-template-columns:1fr;
    }
    .row .label{
        font-size:12px;
    }
    .row .value{
        font-size:13px;
    }
    .topbar-user{
        width:100%;
        justify-content:flex-start;
    }
}
</style>
</head>
<body>

<button class="toggle-btn" onclick="toggleSidebar()">
    <i class="fas fa-bars"></i>
</button>

<div class="container">
    <!-- SIDEBAR -->
    <aside class="sidebar" id="sidebar">
        <div class="sidebar-header">
            <div class="sidebar-header-icon">
                <i class="fas fa-user-tie"></i>
            </div>
            <h2>Panel Jefe</h2>
        </div>
        <ul>
            <li><a href="dashboard_directora.php"><i class="fas fa-tachometer-alt"></i> Panel Principal</a></li>
            <li><a href="panel_directora.php"><i class="fas fa-clipboard-list"></i> Solicitudes Pendientes-Permiso</a></li>
            <li><a href="panel_directora_vacaciones.php"><i class="fas fa-umbrella-beach"></i> Solicitudes Pendientes-Vacaciones</a></li>
            <li><a href="solicitudes_aprobadas_directora.php"><i class="fas fa-check"></i> Solicitudes Aprobadas</a></li>
            <li><a href="solicitudes_rechazadas_directora.php"><i class="fas fa-times"></i> Solicitudes Rechazadas</a></li>
            <li><a href="vacaciones_jefe.php"><i class="fas fa-users"></i> Vacaciones</a></li>
            <li><a href="panel_user_directora.php"><i class="fas fa-eye"></i> Perfil</a></li>
            <li>
                <a href="https://sistemas.proasol.gob.hn/denuncias_proasol/index.html?src=jefe_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>
    </aside>

    <!-- CONTENIDO PRINCIPAL -->
    <main class="main-content">
        <header class="topbar">
            <div class="topbar-left">
                <div class="topbar-title">
                    <i class="fas fa-clipboard-check"></i>
                    <span>Solicitudes Pendientes</span>
                </div>
                <div class="topbar-subtitle">
                    Revisa, aprueba o rechaza las solicitudes de tu equipo.
                </div>
            </div>
            <div class="topbar-user">
                <div class="topbar-user-avatar">
                    <?php
                        $nombre = isset($_SESSION['Nom']) ? trim($_SESSION['Nom']) : '';
                        echo strtoupper(substr($nombre,0,1));
                    ?>
                </div>
                <div class="topbar-user-name">
                    Bienvenido, <?= htmlspecialchars($_SESSION['Nom']) ?>
                </div>
            </div>
        </header>

        <h1>Solicitudes de Permiso - Pendientes</h1>

        <section class="dashboard-grid">
            <?php if ($result && $result->num_rows > 0): ?>
                <?php while ($row = $result->fetch_assoc()): ?>
                    <?php
                        $idSolicitud = (int)$row['id'];
                        $urlDetalle  = "detalle_solicitud_jefe.php?id=" . $idSolicitud;
                        $nombreFunc  = ucwords(mb_strtolower($row['nombre_funcionario'] ?? '', 'UTF-8'));
                    ?>
                    <article class="solicitud-card">
                        <div class="card-header">
                            <div class="title">
                                <i class="fas fa-user-circle"></i>
                                <span><?= htmlspecialchars($nombreFunc) ?></span>
                            </div>
                            <div class="badges">
                                <span class="badge"><?= htmlspecialchars($row['tipo_permiso']) ?></span>
                                <span class="badge badge-warning"><?= htmlspecialchars($row['estado']) ?></span>
                            </div>
                        </div>

                        <div class="card-body">
                            <div class="row">
                                <div class="label">Fecha solicitud:</div>
                                <div class="value"><?= htmlspecialchars($row['fecha_solicitud']) ?></div>
                            </div>
                            <div class="row">
                                <div class="label">Motivo:</div>
                                <div class="value"><?= htmlspecialchars($row['descripcion_motivo'] ?? '') ?></div>
                            </div>
                            <div class="row">
                                <div class="label">Fecha salida:</div>
                                <div class="value"><?= htmlspecialchars($row['fecha_salida'] ?? '') ?></div>
                            </div>
                            <div class="row">
                                <div class="label">Horario:</div>
                                <div class="value"><?= htmlspecialchars($row['horario_permiso'] ?? '') ?></div>
                            </div>
                        </div>

                        <div class="actions">
                            <div class="actions-top">
                                <button type="button"
                                        class="btn-preview"
                                        data-url="<?= htmlspecialchars($urlDetalle) ?>">
                                    <i class="fas fa-eye"></i> Ver detalle
                                </button>
                            </div>

                            <form action="procesar_revision_jefe.php" method="POST">
                                <input type="hidden" name="id_solicitud" value="<?= $idSolicitud ?>">
                                <textarea name="comentario" placeholder="Comentario (opcional)"></textarea>
                                <div class="button-group">
                                    <button type="submit" name="accion" value="Aprobar" class="btn btn-approve">
                                        ✅ Aprobar
                                    </button>
                                    <button type="submit" name="accion" value="Rechazar" class="btn btn-reject">
                                        ❌ Rechazar
                                    </button>
                                </div>
                            </form>
                        </div>
                    </article>
                <?php endwhile; ?>
            <?php else: ?>
                <article class="solicitud-card card-empty">
                    <p>No hay solicitudes pendientes por el momento.</p>
                </article>
            <?php endif; ?>
        </section>
    </main>
</div>

<!-- Modal Vista Previa -->
<div class="modal" id="previewModal">
  <div class="modal-card">
    <div class="modal-header">
      <div class="modal-title">
        <i class="fas fa-eye"></i>
        <span>Vista previa de solicitud</span>
      </div>
      <button class="modal-close" id="closePreview">Cerrar</button>
    </div>
    <iframe id="previewFrame" class="modal-iframe" src="about:blank"></iframe>
  </div>
</div>

<script>
function toggleSidebar(){
    const sidebar = document.getElementById('sidebar');
    sidebar.classList.toggle('open');
}

// Modal de vista previa
(function(){
    const modal  = document.getElementById('previewModal');
    const iframe = document.getElementById('previewFrame');
    const closeBtn = document.getElementById('closePreview');

    document.querySelectorAll('.btn-preview').forEach(btn => {
        btn.addEventListener('click', () => {
            const url = btn.dataset.url;
            iframe.src = url || 'about:blank';
            modal.classList.add('open');
            document.body.style.overflow = 'hidden';
        });
    });

    closeBtn.addEventListener('click', () => {
        modal.classList.remove('open');
        iframe.src = 'about:blank';
        document.body.style.overflow = '';
    });

    modal.addEventListener('click', e => {
        if (e.target === modal) {
            closeBtn.click();
        }
    });
})();
</script>

<?php $conn->close(); ?>
</body>
</html>
