<?php
/**
 * @intranet-file base/preferences/index.php
 * @intranet-file-version 2026.05.05.1
 * @intranet-file-date 2026-05-05
 * @intranet-file-owner CSIF Intranet
 */
declare(strict_types=1);

require_once dirname(__DIR__, 2) . '/common/app_guard.php';
require_once dirname(__DIR__, 2) . '/common/url.php';
require_once dirname(__DIR__, 2) . '/common/catalogo_db.php';
require_once dirname(__DIR__, 2) . '/common/user_preferences.php';
checkAppAccess();

$pdo = db();
intranet_preferences_ensure_app_registered($pdo);
$currentMode = intranet_load_session_theme_mode($pdo);
$currentMenuLayout = intranet_load_session_menu_layout($pdo);
$currentSessionTimeout = intranet_load_session_timeout_minutes($pdo);
$currentHomeFrequentLimit = intranet_load_session_home_frequent_limit($pdo);
$currentHomeFrequentAppBg = intranet_load_session_home_frequent_app_bg($pdo);
$currentHomeFrequentLinkBg = intranet_load_session_home_frequent_link_bg($pdo);
$currentHomeFrequentAppText = intranet_hex_contrast_text($currentHomeFrequentAppBg);
$currentHomeFrequentLinkText = intranet_hex_contrast_text($currentHomeFrequentLinkBg);
$csrf = catalogo_csrf_token('user_preferences_csrf');

$error = '';
$notice = '';
$justSavedMode = null;
$justSavedMenuLayout = null;
$themeModes = [
    'light' => [
        'label' => 'Modo claro',
        'description' => 'Mantiene la apariencia clara corporativa de la intranet.',
        'surface' => 'Tarjetas, formularios y tablas usaran superficies claras.',
    ],
    'medium' => [
        'label' => 'Modo medio',
        'description' => 'Reduce mas el brillo del modo claro y deja una interfaz neutra, mas templada.',
        'surface' => 'Las superficies se veran mas apagadas y ligeramente mas oscuras que en el claro.',
    ],
    'dark' => [
        'label' => 'Modo oscuro',
        'description' => 'Reduce brillo con un fondo oscuro equilibrado para uso prolongado.',
        'surface' => 'Tarjetas, formularios y tablas usaran superficies oscuras con contraste moderado.',
    ],
    'contrast' => [
        'label' => 'Modo alto contraste',
        'description' => 'Maximiza contraste y legibilidad con fondos muy oscuros y textos mas definidos.',
        'surface' => 'La interfaz priorizara lectura, separacion visual y nitidez en todos los bloques.',
    ],
];
$menuLayouts = [
    'top' => [
        'label' => 'Menu superior compacto',
        'description' => 'Cuatro iconos arriba, con paneles desplegables por grupo. Recomendado para escritorio.',
        'preview' => 'Cabecera fija, mas ancho util para tablas y formularios.',
    ],
    'dock' => [
        'label' => 'Dock inferior',
        'description' => 'Cuatro iconos abajo, con paneles que se abren hacia arriba.',
        'preview' => 'Comodo en pantallas tactiles o navegacion frecuente.',
    ],
    'sidebar' => [
        'label' => 'Menu lateral clasico',
        'description' => 'Mantiene el menu actual en la parte izquierda.',
        'preview' => 'Familiar para usuarios que prefieren ver todas las opciones en columna.',
    ],
];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        catalogo_csrf_validate($_POST['csrf'] ?? null, 'user_preferences_csrf');
        $selectedMode = intranet_theme_mode_normalize((string) ($_POST['theme_mode'] ?? INTRANET_THEME_MODE_DEFAULT));
        $selectedMenuLayout = intranet_menu_layout_normalize((string) ($_POST['menu_layout'] ?? INTRANET_MENU_LAYOUT_DEFAULT));
        $selectedSessionTimeout = intranet_session_timeout_normalize($_POST['session_timeout_minutes'] ?? INTRANET_SESSION_TIMEOUT_DEFAULT_MINUTES);
        $selectedHomeFrequentLimit = intranet_home_frequent_limit_normalize($_POST['home_frequent_limit'] ?? INTRANET_HOME_FREQUENT_LIMIT_DEFAULT);
        $selectedHomeFrequentAppBg = intranet_home_frequent_app_bg_normalize($_POST['home_frequent_app_bg'] ?? INTRANET_HOME_FREQUENT_APP_BG_DEFAULT);
        $selectedHomeFrequentLinkBg = intranet_home_frequent_link_bg_normalize($_POST['home_frequent_link_bg'] ?? INTRANET_HOME_FREQUENT_LINK_BG_DEFAULT);
        $username = (string) ($_SESSION['username'] ?? '');
        if ($username === '') {
            throw new RuntimeException('No se ha detectado el usuario actual.');
        }

        $previousMenuLayout = $currentMenuLayout;
        $savedMode = intranet_set_user_theme_mode($pdo, $username, $selectedMode);
        $savedMenuLayout = intranet_set_user_menu_layout($pdo, $username, $selectedMenuLayout);
        $savedSessionTimeout = intranet_set_user_session_timeout_minutes($pdo, $username, $selectedSessionTimeout);
        $savedHomeFrequentLimit = intranet_set_user_home_frequent_limit($pdo, $username, $selectedHomeFrequentLimit);
        $savedHomeFrequentAppBg = intranet_set_user_home_frequent_app_bg($pdo, $username, $selectedHomeFrequentAppBg);
        $savedHomeFrequentLinkBg = intranet_set_user_home_frequent_link_bg($pdo, $username, $selectedHomeFrequentLinkBg);
        intranet_set_session_theme_mode($savedMode);
        intranet_set_session_menu_layout($savedMenuLayout);
        intranet_set_session_timeout_minutes($savedSessionTimeout);
        intranet_set_session_home_frequent_limit($savedHomeFrequentLimit);
        intranet_set_session_home_frequent_app_bg($savedHomeFrequentAppBg);
        intranet_set_session_home_frequent_link_bg($savedHomeFrequentLinkBg);
        intranet_touch_session_activity();
        $currentMode = $savedMode;
        $currentMenuLayout = $savedMenuLayout;
        $currentSessionTimeout = $savedSessionTimeout;
        $currentHomeFrequentLimit = $savedHomeFrequentLimit;
        $currentHomeFrequentAppBg = $savedHomeFrequentAppBg;
        $currentHomeFrequentLinkBg = $savedHomeFrequentLinkBg;
        $currentHomeFrequentAppText = intranet_hex_contrast_text($currentHomeFrequentAppBg);
        $currentHomeFrequentLinkText = intranet_hex_contrast_text($currentHomeFrequentLinkBg);
        $justSavedMode = $savedMode;
        if ($savedMenuLayout !== $previousMenuLayout) {
            $justSavedMenuLayout = $savedMenuLayout;
        }
        $notice = 'Tus preferencias se han guardado correctamente.';
    } catch (Throwable $e) {
        $error = $e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html lang="es" class="app-html" <?= intranet_theme_html_attr($currentMode); ?>>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Preferencias</title>
    <?= intranet_theme_bootstrap_script_tag($currentMode); ?>
    <link rel="stylesheet" href="<?= h(asset_url('styles/css/style.css')) ?>">
    <link rel="stylesheet" href="<?= h(asset_url('styles/css/theme-vars.css')) ?>">
    <style>
        .prefs-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:18px}
        .prefs-option{position:relative;border:1px solid var(--border-light);border-radius:16px;background:var(--bg-card);padding:18px;cursor:pointer;transition:transform .15s ease,border-color .15s ease,box-shadow .15s ease}
        .prefs-option:hover{transform:translateY(-2px);border-color:var(--primary);box-shadow:0 10px 24px rgba(15,23,42,.08)}
        .prefs-option input{position:absolute;inset:14px auto auto 14px}
        .prefs-option.is-active{border-color:var(--primary);box-shadow:0 0 0 3px var(--border-focus)}
        .prefs-title{display:flex;align-items:center;gap:10px;margin-bottom:8px;padding-left:28px}
        .prefs-preview{--preview-body:#f1f5f9;--preview-card:#ffffff;--preview-input:#f8fafc;--preview-border:#dbe4ef;--preview-text:#334155;--preview-muted:#64748b;border:1px solid var(--preview-border);border-radius:14px;overflow:hidden;background:var(--preview-body);margin-top:14px}
        .prefs-preview-top{padding:12px 14px;background:linear-gradient(135deg,var(--bg-sidebar),var(--primary));color:#fff;font-weight:800}
        .prefs-preview-body{padding:14px;display:grid;gap:10px;background:var(--preview-body)}
        .prefs-chip{display:inline-flex;align-items:center;gap:8px;padding:8px 10px;border-radius:999px;background:var(--preview-input);border:1px solid var(--preview-border);font-size:.85rem;color:var(--preview-text)}
        .prefs-surface{padding:12px;border-radius:12px;background:var(--preview-card);border:1px solid var(--preview-border);color:var(--preview-text)}
        .prefs-actions{display:flex;gap:10px;flex-wrap:wrap;align-items:center}
        .prefs-section{margin-top:24px;padding-top:22px;border-top:1px solid var(--border-light)}
        .prefs-field{display:grid;gap:8px;max-width:260px}
        .prefs-field-row{display:flex;flex-wrap:wrap;gap:14px;align-items:end}
        .prefs-select{width:100%;border:1px solid var(--border-light);border-radius:12px;background:var(--bg-card);color:var(--text-main);padding:12px 14px;font:inherit}
        .prefs-color-input{width:72px;min-height:48px;padding:4px;border:1px solid var(--border-light);border-radius:12px;background:var(--bg-card);cursor:pointer}
        .prefs-frequent-samples{display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:12px;margin-top:14px;max-width:620px}
        .prefs-frequent-sample{border:1px solid color-mix(in srgb,var(--sample-color) 42%,var(--border-light) 58%);border-radius:14px;padding:14px;color:var(--text-main);background:color-mix(in srgb,var(--sample-color) 18%,var(--bg-card) 82%);box-shadow:inset 4px 0 0 color-mix(in srgb,var(--sample-color) 76%,var(--primary) 24%),0 10px 22px rgba(15,23,42,.06)}
        .prefs-frequent-sample small{display:block;margin-top:5px;color:var(--text-muted)}
        html[data-theme="dark"] .prefs-frequent-sample{background:color-mix(in srgb,var(--sample-color) 12%,var(--bg-card) 88%);border-color:color-mix(in srgb,var(--sample-color) 36%,var(--border-light) 64%)}
        .prefs-help{margin:10px 0 0 0;color:var(--text-muted);line-height:1.6}
        .prefs-menu-preview{margin-top:14px;border:1px solid var(--preview-border);border-radius:14px;background:var(--preview-body);padding:12px;display:grid;gap:8px}
        .prefs-menu-bar{height:12px;border-radius:999px;background:linear-gradient(135deg,var(--bg-sidebar),var(--primary));}
        .prefs-menu-row{display:flex;gap:8px;align-items:center}
        .prefs-menu-dot{width:30px;height:30px;border-radius:10px;background:var(--preview-card);border:1px solid var(--preview-border)}
        .prefs-menu-copy{flex:1;border-radius:10px;background:var(--preview-input);border:1px solid var(--preview-border);padding:9px 10px;color:var(--preview-text);font-size:.82rem;line-height:1.35}
        .prefs-menu-preview[data-layout="dock"]{padding-top:44px}
        .prefs-menu-preview[data-layout="dock"] .prefs-menu-bar{order:3}
        .prefs-menu-preview[data-layout="sidebar"]{grid-template-columns:54px 1fr;min-height:92px}
        .prefs-menu-preview[data-layout="sidebar"] .prefs-menu-bar{height:100%;border-radius:12px}
        .prefs-menu-preview[data-layout="sidebar"] .prefs-menu-row{flex-direction:column;align-items:stretch}
        .prefs-preview[data-theme="light"]{--preview-body:#f1f5f9;--preview-card:#ffffff;--preview-input:#f8fafc;--preview-border:#dbe4ef;--preview-text:#334155;--preview-muted:#64748b}
        .prefs-preview[data-theme="medium"]{--preview-body:#8a939d;--preview-card:#959ca6;--preview-input:#8e95a0;--preview-border:#909bab;--preview-text:#243447;--preview-muted:#4f6276}
        .prefs-preview[data-theme="dark"]{--preview-body:#223041;--preview-card:#2a394d;--preview-input:#233144;--preview-border:#3d4e66;--preview-text:#e2e8f0;--preview-muted:#a9b6c8}
        .prefs-preview[data-theme="contrast"]{--preview-body:#0a0f18;--preview-card:#0d1522;--preview-input:#08101b;--preview-border:#314056;--preview-text:#f8fafc;--preview-muted:#c4d0df}
    </style>
</head>
<body class="app-body">
<div class="app-container">
    <header class="header-top">
        <div class="header-titles">
            <h2 style="margin:0;">Preferencias</h2>
            <p style="margin:5px 0 0 0; opacity:0.9;">Personaliza como ves la intranet y guarda tu eleccion.</p>
        </div>
        <div class="header-actions">
            <a href="<?= h(asset_url('dashboard.php')) ?>" target="_top" class="btn-back-dashboard">Volver al inicio</a>
        </div>
    </header>

    <?php if ($error !== ''): ?>
        <div class="alert alert-error" style="margin-bottom:12px;"><?= h($error) ?></div>
    <?php endif; ?>
    <?php if ($notice !== ''): ?>
        <div class="alert admin-notice" style="margin-bottom:12px;"><?= h($notice) ?></div>
    <?php endif; ?>

    <section class="card">
        <div class="card-title">Apariencia</div>
        <p style="margin:0 0 18px 0; color:var(--text-muted);">La preferencia se guarda por usuario y se aplica al dashboard y a las pantallas de la intranet compatibles con el tema global.</p>

        <form method="post" class="prefs-form">
            <input type="hidden" name="csrf" value="<?= h($csrf) ?>">

            <div class="prefs-grid">
                <?php foreach ($themeModes as $value => $meta): ?>
                    <?php $active = $currentMode === $value; ?>
                    <label class="prefs-option<?= $active ? ' is-active' : '' ?>">
                        <input type="radio" name="theme_mode" value="<?= h($value) ?>" <?= $active ? 'checked' : '' ?>>
                        <div class="prefs-title">
                            <strong><?= h($meta['label']) ?></strong>
                        </div>
                        <p style="padding-left:28px; color:var(--text-muted); margin:0;">
                            <?= h($meta['description']) ?>
                        </p>

                        <div class="prefs-preview" data-theme="<?= h($value) ?>">
                            <div class="prefs-preview-top"><?= h($meta['label']) ?></div>
                            <div class="prefs-preview-body">
                                <div class="prefs-chip">Color corporativo activo</div>
                                <div class="prefs-surface"><?= h($meta['surface']) ?></div>
                            </div>
                        </div>
                    </label>
                <?php endforeach; ?>
            </div>

            <div class="prefs-section">
                <div class="card-title" style="margin-bottom:8px;">Disposicion del menu principal</div>
                <p style="margin:0 0 18px 0; color:var(--text-muted);">Elige como quieres navegar por los grupos Inicio, Portal, Herramientas y Administración.</p>

                <div class="prefs-grid">
                    <?php foreach ($menuLayouts as $value => $meta): ?>
                        <?php $active = $currentMenuLayout === $value; ?>
                        <label class="prefs-option<?= $active ? ' is-active' : '' ?>">
                            <input type="radio" name="menu_layout" value="<?= h($value) ?>" <?= $active ? 'checked' : '' ?>>
                            <div class="prefs-title">
                                <strong><?= h($meta['label']) ?></strong>
                            </div>
                            <p style="padding-left:28px; color:var(--text-muted); margin:0;">
                                <?= h($meta['description']) ?>
                            </p>

                            <div class="prefs-menu-preview prefs-preview" data-layout="<?= h($value) ?>" data-theme="<?= h($currentMode) ?>">
                                <div class="prefs-menu-bar"></div>
                                <div class="prefs-menu-row">
                                    <span class="prefs-menu-dot"></span>
                                    <span class="prefs-menu-dot"></span>
                                    <span class="prefs-menu-dot"></span>
                                    <span class="prefs-menu-dot"></span>
                                </div>
                                <div class="prefs-menu-copy"><?= h($meta['preview']) ?></div>
                            </div>
                        </label>
                    <?php endforeach; ?>
                </div>

                <p class="prefs-help">Preferencia actual: <strong><?= h(intranet_menu_layout_label($currentMenuLayout)) ?></strong>.</p>
            </div>

            <div class="prefs-section">
                <div class="card-title" style="margin-bottom:8px;">Cierre automatico por inactividad</div>
                <p style="margin:0 0 18px 0; color:var(--text-muted);">Elige cuanto tiempo puede pasar sin actividad antes de que la intranet cierre tu sesion. El valor por defecto es 30 minutos.</p>

                <div class="prefs-field">
                    <label for="session_timeout_minutes"><strong>Tiempo de inactividad permitido</strong></label>
                    <input
                        id="session_timeout_minutes"
                        name="session_timeout_minutes"
                        type="number"
                        min="<?= h((string) INTRANET_SESSION_TIMEOUT_MIN_MINUTES) ?>"
                        max="<?= h((string) INTRANET_SESSION_TIMEOUT_MAX_MINUTES) ?>"
                        step="1"
                        value="<?= h((string) $currentSessionTimeout) ?>"
                        class="prefs-select"
                    >
                </div>

                <p class="prefs-help">Preferencia actual: <strong><?= h(intranet_session_timeout_label($currentSessionTimeout)) ?></strong>.</p>
            </div>

            <div class="prefs-section">
                <div class="card-title" style="margin-bottom:8px;">Accesos frecuentes del inicio</div>
                <p style="margin:0 0 18px 0; color:var(--text-muted);">Elige cuantos accesos se muestran en la pagina de inicio y el color de fondo de las tarjetas segun sean aplicaciones o enlaces.</p>

                <div class="prefs-field-row">
                    <div class="prefs-field">
                        <label for="home_frequent_limit"><strong>Numero de accesos</strong></label>
                        <input
                            id="home_frequent_limit"
                            name="home_frequent_limit"
                            type="number"
                            min="<?= h((string) INTRANET_HOME_FREQUENT_LIMIT_MIN) ?>"
                            max="<?= h((string) INTRANET_HOME_FREQUENT_LIMIT_MAX) ?>"
                            step="1"
                            value="<?= h((string) $currentHomeFrequentLimit) ?>"
                            class="prefs-select"
                        >
                    </div>
                    <div class="prefs-field">
                        <label for="home_frequent_app_bg"><strong>Fondo de aplicaciones</strong></label>
                        <input
                            id="home_frequent_app_bg"
                            name="home_frequent_app_bg"
                            type="color"
                            value="<?= h($currentHomeFrequentAppBg) ?>"
                            class="prefs-color-input"
                        >
                    </div>
                    <div class="prefs-field">
                        <label for="home_frequent_link_bg"><strong>Fondo de enlaces</strong></label>
                        <input
                            id="home_frequent_link_bg"
                            name="home_frequent_link_bg"
                            type="color"
                            value="<?= h($currentHomeFrequentLinkBg) ?>"
                            class="prefs-color-input"
                        >
                    </div>
                </div>

                <div class="prefs-frequent-samples">
                    <div class="prefs-frequent-sample" style="--sample-color:<?= h($currentHomeFrequentAppBg) ?>;">
                        <strong>Aplicacion</strong>
                        <small>Tarjeta de ejemplo para apps del portal.</small>
                    </div>
                    <div class="prefs-frequent-sample" style="--sample-color:<?= h($currentHomeFrequentLinkBg) ?>;">
                        <strong>Enlace</strong>
                        <small>Tarjeta de ejemplo para enlaces, NNTT o novedades.</small>
                    </div>
                </div>

                <p class="prefs-help">Preferencia actual: <strong><?= h(intranet_home_frequent_limit_label($currentHomeFrequentLimit)) ?></strong>.</p>
            </div>

            <div class="prefs-actions" style="margin-top:20px;">
                <button type="submit" class="btn-primary-intranet">Guardar preferencias</button>
                <span style="color:var(--text-muted); font-size:.92rem;">Tema actual: <strong><?= h(intranet_theme_mode_label($currentMode)) ?></strong></span>
            </div>
        </form>
    </section>
    <section class="card">
        <div class="card-title">Como funciona</div>
        <ul style="margin:0; padding-left:18px; color:var(--text-main); line-height:1.7;">
            <li>La preferencia se guarda en la base de datos asociada a tu usuario.</li>
            <li>Tambien se sincroniza con el navegador para aplicar el cambio de forma inmediata.</li>
            <li>La disposicion del menu se aplicara al volver al dashboard o recargar la intranet.</li>
            <li>El cierre automatico por inactividad puede ajustarse entre 15 y 60 minutos.</li>
            <li>Los accesos frecuentes se calculan con las aplicaciones y enlaces que abres desde la intranet.</li>
            <li>El color corporativo general del sitio se conserva; lo que cambia es la intensidad de fondos, tarjetas, formularios y tablas.</li>
        </ul>
    </section>
</div>
<?php if ($justSavedMode !== null): ?>
<script>
window.intranetApplyThemeMode && window.intranetApplyThemeMode(<?= json_encode($justSavedMode, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>);
</script>
<?php endif; ?>
<?php if ($justSavedMenuLayout !== null): ?>
<script>
(function () {
    var dashboardUrl = <?= json_encode(asset_url('dashboard.php?open=' . rawurlencode('base/preferences/index.php')), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
    try {
        if (window.top && window.top !== window) {
            window.top.location.href = dashboardUrl;
        } else {
            window.location.href = dashboardUrl;
        }
    } catch (e) {
        window.location.href = dashboardUrl;
    }
})();
</script>
<?php endif; ?>
</body>
</html>
