<?php
// APPS/PanelIconos.php
session_start();

// =============================
// CONFIGURACIÓN
// =============================
$CARPETA_APPS = '/var/www/html/MS/librerias/Administrativas/'; // Ruta física
$RUTA_WEB_APPS = '/MS/librerias/Administrativas/';            // Ruta web (URL)

$RESTRINGIR_A_EXT = ['php'];
$EXCLUIR_FILES = ['PanelIconos.php'];

$ICON_SIZE = 64;
$POPUP_WIDTH = 1000;
$POPUP_HEIGHT = 700;

// =============================
// SEGURIDAD
// =============================
if (!isset($_SESSION['Acceso']) || $_SESSION['Acceso'] !== 'AccesoSiqueSi') {
    echo '<div class="alert alert-danger">Acceso denegado.</div>';
    return;
}

// =============================
// FUNCIONES
// =============================
function obtener_descripcion_corta($rutaArchivo) {
    if (!file_exists($rutaArchivo)) return '';
    $fp = @fopen($rutaArchivo, 'r');
    if (!$fp) return '';
    $desc = '';
    $i = 0;
    while (!feof($fp) && $i < 30) {
        $line = trim(fgets($fp));
        if (preg_match('#^(//|/\*|\#)\s*DESC\s*[:\-]\s*(.+)$#i', $line, $m)) {
            $desc = trim($m[2]);
            break;
        }
        if (preg_match('#/\*\s*DESC\s*[:\-]\s*(.+)\s*\*/#i', $line, $m2)) {
            $desc = trim($m2[1]);
            break;
        }
        $i++;
    }
    fclose($fp);
    return $desc;
}

function titulo_amigable($nombreArchivo) {
    $sinExt = preg_replace('/\.[^.]+$/', '', $nombreArchivo);
    $sinExt = preg_replace('/[-_]+/', ' ', $sinExt);
    return ucwords($sinExt);
}

// =============================
// LISTAR ARCHIVOS
// =============================
$items = [];
$dir = @opendir($CARPETA_APPS);

if ($dir) {
    while (($file = readdir($dir)) !== false) {
        if (in_array($file, ['.', '..'])) continue;
        if (in_array($file, $EXCLUIR_FILES)) continue;

        $full = $CARPETA_APPS . $file;
        if (!is_file($full)) continue;

        $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
        if (!in_array($ext, $RESTRINGIR_A_EXT)) continue;

        $items[] = [
            'file'  => $file,
            'title' => titulo_amigable($file),
            'desc'  => obtener_descripcion_corta($full)
        ];
    }
    closedir($dir);
}

usort($items, function($a, $b) {
    return strcasecmp($a['title'], $b['title']);
});
?>

<!-- =============================
      ESTILOS
============================= -->
<style>
.panel-iconos-grid { margin-top: 8px; }
.panel-icono-card { transition: transform .12s, box-shadow .12s; cursor: pointer; }
.panel-icono-card:hover { transform: translateY(-6px); box-shadow: 0 10px 20px rgba(0,0,0,0.08); }
.panel-icono-card .card-body { padding: .75rem; }
.panel-icono-icon { width: 64px; height: 64px; border-radius: .5rem; background: rgba(0,0,0,0.03); display:flex; align-items:center; justify-content:center; }
.panel-icono-title { font-size: .95rem; font-weight: 600; margin-top: .5rem; }
.panel-icono-desc { font-size: .82rem; color:#666; }
.panel-iconos-empty { padding: 2rem; text-align: center; color:#777; }
</style>

<!-- =============================
      HTML DEL PANEL
============================= -->
<div class="card">
    <div class="card-body">
        <h5 class="mb-2">Panel de Módulos</h5>
        <div class="small text-muted mb-3">Haz clic para abrir el módulo en una ventana hija minimal.</div>

        <?php if (empty($items)): ?>
            <div class="panel-iconos-empty">No hay módulos en la carpeta Administrativas.</div>
        <?php else: ?>
            <div class="row panel-iconos-grid">
                <?php foreach ($items as $it): 
                    $file = $it['file'];
                    $sinExt = preg_replace('/\.[^.]+$/', '', $file);
                    $title = htmlspecialchars($it['title']);
                    $desc  = htmlspecialchars($it['desc'] ?: "Abrir módulo $title");
                ?>
                <div class="col-6 col-md-3 col-lg-3 mb-3">
                    <div class="card panel-icono-card"
                        onclick="abrirModuloMinimal('<?php echo $sinExt; ?>','<?php echo addslashes($title); ?>')">

                        <div class="card-body d-flex align-items-center">
                            <div class="panel-icono-icon me-3">
                                <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                    <rect x="3" y="4" width="18" height="14" rx="2" stroke-width="1.5"/>
                                    <path d="M8 8h4v4H8z" stroke-width="1.5"/>
                                    <path d="M7 17h10" stroke-width="1.5"/>
                                </svg>
                            </div>
                            <div>
                                <div class="panel-icono-title"><?php echo $title; ?></div>
                                <div class="panel-icono-desc"><?php echo $desc; ?></div>
                            </div>
                        </div>

                        <div class="card-footer small text-muted">Archivo: <?php echo $file; ?></div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- =============================
      JS
============================= -->
<script>
const POPUP_WIDTH  = <?php echo $POPUP_WIDTH; ?>;
const POPUP_HEIGHT = <?php echo $POPUP_HEIGHT; ?>;

/* Ruta web directa del módulo */
function urlModulo(nombreSinExt) {
    const ruta = "<?php echo $RUTA_WEB_APPS; ?>";
    return ruta + encodeURIComponent(nombreSinExt) + ".php";
}

/* Abrir en popup minimal */
function abrirPopupMinimal(url, titulo) {
    const left = (screen.width - POPUP_WIDTH) / 2;
    const top  = (screen.height - POPUP_HEIGHT) / 2;
    const features = [
        "toolbar=no",
        "location=no",
        "status=no",
        "menubar=no",
        "scrollbars=yes",
        "resizable=yes",
        "width=" + POPUP_WIDTH,
        "height=" + POPUP_HEIGHT,
        "left=" + left,
        "top=" + top
    ].join(",");

    const win = window.open(url, "mod_" + titulo.replace(/\s+/g, "_"), features);
    if (win) win.focus();
}

/* Lógica principal */
function abrirModuloMinimal(nombreSinExt, titulo) {
    const url = urlModulo(nombreSinExt);
    abrirPopupMinimal(url, titulo);
}
</script>
