<?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'];

// === Obtener cod_unidad del usuario (para fallback) ===
$sqlDatos = "SELECT cod_unidad FROM accounts WHERE ID = ?";
$stmtDatos = $conn->prepare($sqlDatos);
$stmtDatos->bind_param("i", $userId);
$stmtDatos->execute();
$resDatos = $stmtDatos->get_result();
$rowDatos = $resDatos->fetch_assoc();

if (!$rowDatos) {
    $_SESSION['error'] = 'No fue posible determinar datos del usuario.';
    header("Location: login.php");
    exit;
}

$codUnidadViewer = $rowDatos['cod_unidad'] ?? null;

/**
 * =========================
 *   🔁 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
// =========================
$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)
      AND u.ID <> ?
  )
  UNION
  (
    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 u.cod_unidad = ?
      AND u.cod_rol IN (7, 8)
      AND u.ID <> ?
  )
  ORDER BY fecha_salida DESC, id DESC
";

$stmt = $conn->prepare($sql);
$types = str_repeat('i', count($ids)) . 'i' . 's' . 'i'; // cambia 's' por 'i' si cod_unidad es INT
$params = [...$ids, $userId, $codUnidadViewer, $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>
*{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;}
.sidebar{width:260px;background:linear-gradient(135deg,#2c3e50,#34495e);color:white;padding:20px 15px;position:fixed;height:100%;transition:transform .3s ease;z-index:1000;}
.sidebar.collapsed{transform:translateX(-260px);}
.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 .3s,color .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{flex-grow:1;padding:30px;margin-left:260px;transition:margin-left .3s ease;width:calc(100% - 260px);}
.welcome-message{font-size:28px;margin-bottom:25px;text-align:center;font-weight:500;}
.main-content h1{font-size:32px;margin-bottom:30px;text-align:center;border-bottom:3px solid #68c8d8;padding-bottom:10px;font-weight:700;}
.dashboard-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:20px;}
.solicitud-card{background:white;border-radius:12px;box-shadow:0 8px 18px rgba(0,0,0,0.08);transition:.2s;border:1px solid #e8eef4;display:flex;flex-direction:column;}
.solicitud-card:hover{transform:translateY(-4px);box-shadow:0 12px 24px rgba(0,0,0,0.1);}
.card-header{display:flex;justify-content:space-between;align-items:center;padding:14px 16px;border-bottom:1px solid #eef2f6;background:linear-gradient(180deg,#fff 0%,#f7fbff 100%);}
.title{font-weight:600;display:flex;align-items:center;gap:8px;font-size:15px;}
.badges{display:flex;gap:6px;}
.badge{font-size:11px;padding:4px 8px;border-radius:999px;background:#eef7ff;color:#1f6fb2;}
.card-body{padding:16px;display:grid;gap:8px;}
.row{display:grid;grid-template-columns:120px 1fr;gap:6px;}
.row .label{color:#6b7c93;font-weight:500;font-size:13px;}
.row .value{font-size:14px;color:#2b3a4a;}
.actions{margin-top:auto;padding:14px;border-top:1px solid #eef2f6;}
textarea{width:100%;padding:10px;border:1px solid #ddd;border-radius:8px;resize:vertical;font-size:14px;}
.button-group{display:flex;gap:8px;flex-wrap:wrap;margin-top:8px;}
.btn{flex:1;padding:10px;border:none;border-radius:6px;cursor:pointer;font-size:14px;font-weight:600;}
.btn-approve{background:linear-gradient(135deg,#27ae60,#219653);color:#fff;}
.btn-reject{background:linear-gradient(135deg,#c0392b,#a93226);color:#fff;}
.btn-preview{background:#e9f3ff;color:#0b5cab;border:1px solid #cfe6ff;font-size:12px;padding:6px 10px;flex:0 0 auto;}
.btn-preview:hover{background:#f3f9ff;}
.modal{display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:2000;align-items:center;justify-content:center;padding:20px;}
.modal.open{display:flex;}
.modal-card{width:min(1200px,96vw);height:min(85vh,900px);background:#fff;border-radius:12px;overflow:hidden;box-shadow:0 20px 60px rgba(0,0,0,.25);display:flex;flex-direction:column;}
.modal-header{display:flex;justify-content:space-between;align-items:center;padding:10px 14px;border-bottom:1px solid #eef2f6;background:#f8fbff;}
.modal-title{font-weight:600;}
.modal-iframe{width:100%;height:100%;border:0;}
</style>
</head>
<body>
<button class="toggle-btn" onclick="toggleSidebar()"><i class="fas fa-bars"></i></button>
<div class="container">
    <div class="sidebar" id="sidebar">
        <h2>Panel Jefe</h2>
        <ul>
            <li><a href="dashboard_jefe.php"><i class="fas fa-tachometer-alt"></i> Panel Principal</a></li>
            <li><a href="panel_jefe.php"><i class="fas fa-clipboard-list"></i> Solicitudes Pendientes-Permiso</a></li>
            <li><a href="panel_jefe_vacaciones.php"><i class="fas fa-umbrella-beach"></i> Solicitudes Pendientes-Vacaciones</a></li>
            <li><a href="solicitudes_aprobadas.php"><i class="fas fa-check"></i> Solicitudes Aprobadas</a></li>
            <li><a href="solicitudes_rechazadas.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_jefe_user.php"><i class="fas fa-eye"></i> Perfil</a></li>
            <li><a href="logout.php"><i class="fas fa-sign-out-alt"></i> Cerrar Sesión</a></li>
        </ul>
    </div>

    <div class="main-content">
        <div class="welcome-message">Bienvenido, <?= htmlspecialchars($_SESSION['Nom']) ?></div>
        <h1>Solicitudes Pendientes - Panel Jefe</h1>

        <div 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;
                    $nombre = ucwords(mb_strtolower($row['nombre_funcionario'] ?? '', 'UTF-8'));
                ?>
                <div class="solicitud-card">
                    <div class="card-header">
                        <div class="title"><i class="fas fa-user-circle"></i> <?= htmlspecialchars($nombre) ?></div>
                        <div class="badges">
                            <span class="badge"><?= htmlspecialchars($row['tipo_permiso']) ?></span>
                            <span class="badge"><?= 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="button-group">
                            <button type="button" class="btn 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>
                </div>
            <?php endwhile; ?>
        <?php else: ?>
            <div class="solicitud-card" style="text-align:center;justify-content:center;padding:20px;">
                <p style="color:#777;">No hay solicitudes pendientes.</p>
            </div>
        <?php endif; ?>
        </div>
    </div>
</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> Vista previa</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');
}
(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',()=>{
            iframe.src=btn.dataset.url;
            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>
