<?php

use dokuwiki\Extension\AdminPlugin;

class admin_plugin_niccstyleconfig extends AdminPlugin {

    /** @var helper_plugin_niccstyleconfig */
    protected $helper;

    private static $accessKey = 'Colores2026';

    public function __construct() {
        $this->helper = plugin_load('helper', 'niccstyleconfig');
    }

    public function getMenuSort() { return 150; }
    public function forAdminOnly() { return true; }
    public function getMenuText($language) { return $this->getLang('menu') ?: 'Configurar Estilos'; }

    public function handle() {
        // Nothing server-side here; all via AJAX
    }

    public function html() {
        global $INPUT;

        $stylekey = $INPUT->str('stylekey', '');

        // ── Password Gate ──
        if ($stylekey !== self::$accessKey) {
            $wrongKey = ($stylekey !== '' && $stylekey !== self::$accessKey);
            $this->renderPasswordGate($wrongKey);
            return;
        }

        // ── Authenticated: Main UI ──
        echo '<div id="niccstyle-app" data-stylekey="' . hsc($stylekey) . '" data-sectok="' . getSecurityToken() . '">';

        // Header
        echo '<div class="nsc-header">';
        echo '  <div class="nsc-header-left">';
        echo '    <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z"/><circle cx="7.5" cy="10" r="1.5"/><circle cx="12" cy="7" r="1.5"/><circle cx="16.5" cy="10" r="1.5"/></svg>';
        echo '    <h1>Configurador de Estilos</h1>';
        echo '  </div>';
        echo '  <div class="nsc-header-right">';
        echo '    <span class="nsc-badge nsc-badge-info" id="nsc-cache-date">Sin escaneo</span>';
        echo '  </div>';
        echo '</div>';

        // Tabs
        echo '<div class="nsc-tabs">';
        $tabs = [
            'systems'     => $this->getLang('tab_systems') ?: 'Sistemas',
            'groups'      => $this->getLang('tab_groups') ?: 'Grupos',
            'assignments' => $this->getLang('tab_assignments') ?: 'Asignaciones',
            'apply'       => $this->getLang('tab_apply') ?: 'Aplicar y Logs',
        ];
        $first = true;
        foreach ($tabs as $id => $label) {
            $active = $first ? ' active' : '';
            echo '<button class="nsc-tab' . $active . '" data-tab="' . $id . '">' . hsc($label) . '</button>';
            $first = false;
        }
        echo '</div>';

        // Tab Contents
        $this->renderTabSystems();
        $this->renderTabGroups();
        $this->renderTabAssignments();
        $this->renderTabApply();

        echo '</div>'; // #niccstyle-app
    }

    // ── Tab 1: Sistemas ────────────────────────────────────────

    protected function renderTabSystems() {
        echo '<div class="nsc-panel active" id="nsc-panel-systems">';
        echo '<div class="nsc-toolbar">';
        echo '  <button class="nsc-btn nsc-btn-primary" id="nsc-btn-scan">';
        echo '    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>';
        echo '    ' . hsc($this->getLang('btn_scan') ?: 'Escanear Servidor');
        echo '  </button>';
        echo '  <input type="text" class="nsc-input nsc-filter" id="nsc-filter-systems" placeholder="Filtrar sistemas...">';
        echo '  <span class="nsc-badge" id="nsc-systems-count">0</span>';
        echo '</div>';

        echo '<div id="nsc-systems-loading" class="nsc-loading" style="display:none;">';
        echo '  <div class="nsc-spinner"></div><span>Escaneando sistemas...</span>';
        echo '</div>';

        echo '<div class="nsc-table-wrap">';
        echo '<table class="nsc-table" id="nsc-systems-table">';
        echo '<thead><tr>';
        echo '<th>#</th>';
        echo '<th>Nombre</th>';
        echo '<th>Titulo</th>';
        echo '<th>Template</th>';
        echo '<th>style.ini 20c</th>';
        echo '<th>style.ini 21c</th>';
        echo '<th>Grupo</th>';
        echo '</tr></thead>';
        echo '<tbody id="nsc-systems-tbody">';
        echo '<tr><td colspan="7" class="nsc-empty">Cargando datos...</td></tr>';
        echo '</tbody>';
        echo '</table>';
        echo '</div>';
        echo '</div>';
    }

    // ── Tab 2: Grupos ──────────────────────────────────────────

    protected function renderTabGroups() {
        echo '<div class="nsc-panel" id="nsc-panel-groups" style="display:none;">';

        // New group form
        echo '<div class="nsc-card nsc-card-form" id="nsc-group-form-card">';
        echo '<h3 id="nsc-group-form-title">Nuevo Grupo</h3>';
        echo '<div class="nsc-form-row">';
        echo '  <div class="nsc-form-group">';
        echo '    <label>Etiqueta *</label>';
        echo '    <input type="text" id="nsc-group-label" class="nsc-input" maxlength="50" placeholder="ej: verde, azul, corporativo">';
        echo '  </div>';
        echo '  <div class="nsc-form-group nsc-form-color">';
        echo '    <label>Color</label>';
        echo '    <input type="color" id="nsc-group-color" value="#3b82f6">';
        echo '  </div>';
        echo '</div>';
        echo '<div class="nsc-form-group">';
        echo '  <label>Descripcion</label>';
        echo '  <input type="text" id="nsc-group-desc" class="nsc-input" maxlength="200" placeholder="Descripcion del grupo">';
        echo '</div>';
        echo '<div class="nsc-form-actions">';
        echo '  <button class="nsc-btn nsc-btn-primary" id="nsc-btn-save-group">Guardar Grupo</button>';
        echo '  <button class="nsc-btn nsc-btn-ghost" id="nsc-btn-cancel-group" style="display:none;">Cancelar</button>';
        echo '  <input type="hidden" id="nsc-group-edit-id" value="">';
        echo '</div>';
        echo '</div>';

        // Groups list
        echo '<div id="nsc-groups-grid" class="nsc-groups-grid">';
        echo '  <div class="nsc-empty">Cargando grupos...</div>';
        echo '</div>';
        echo '</div>';
    }

    // ── Tab 3: Asignaciones ────────────────────────────────────

    protected function renderTabAssignments() {
        echo '<div class="nsc-panel" id="nsc-panel-assignments" style="display:none;">';

        // Group selector
        echo '<div class="nsc-toolbar">';
        echo '  <label class="nsc-toolbar-label">Grupo:</label>';
        echo '  <select id="nsc-assign-group" class="nsc-select">';
        echo '    <option value="">-- Seleccionar grupo --</option>';
        echo '  </select>';
        echo '</div>';

        echo '<div class="nsc-assign-layout" id="nsc-assign-layout" style="display:none;">';

        // Left: Origin
        echo '<div class="nsc-assign-col">';
        echo '  <div class="nsc-card">';
        echo '    <h3>Sistema Origen</h3>';
        echo '    <div id="nsc-origin-current" class="nsc-origin-display">';
        echo '      <span class="nsc-text-muted">Sin origen asignado</span>';
        echo '    </div>';
        echo '    <div class="nsc-form-group">';
        echo '      <select id="nsc-origin-select" class="nsc-select">';
        echo '        <option value="">-- Seleccionar sistema --</option>';
        echo '      </select>';
        echo '    </div>';
        echo '    <button class="nsc-btn nsc-btn-primary" id="nsc-btn-set-origin">Establecer Origen</button>';
        echo '    <div id="nsc-origin-preview" class="nsc-color-preview" style="display:none;"></div>';
        echo '  </div>';
        echo '</div>';

        // Right: Destinations
        echo '<div class="nsc-assign-col">';
        echo '  <div class="nsc-card">';
        echo '    <h3>Sistemas Destino <span class="nsc-badge" id="nsc-dest-count">0</span></h3>';
        echo '    <div class="nsc-toolbar nsc-toolbar-compact">';
        echo '      <input type="text" class="nsc-input nsc-filter" id="nsc-filter-dest" placeholder="Filtrar...">';
        echo '      <button class="nsc-btn nsc-btn-sm" id="nsc-btn-select-all">Todos</button>';
        echo '      <button class="nsc-btn nsc-btn-sm" id="nsc-btn-deselect-all">Ninguno</button>';
        echo '    </div>';
        echo '    <div id="nsc-dest-list" class="nsc-check-list"></div>';
        echo '    <button class="nsc-btn nsc-btn-primary" id="nsc-btn-save-dests">Guardar Destinos</button>';
        echo '  </div>';
        echo '</div>';

        echo '</div>'; // .nsc-assign-layout
        echo '</div>'; // panel
    }

    // ── Tab 4: Aplicar y Logs ──────────────────────────────────

    protected function renderTabApply() {
        echo '<div class="nsc-panel" id="nsc-panel-apply" style="display:none;">';

        // Section 1: Apply
        echo '<div class="nsc-card">';
        echo '  <h3>Aplicar Estilos</h3>';
        echo '  <div id="nsc-apply-groups" class="nsc-apply-list">';
        echo '    <div class="nsc-empty">Cargando grupos...</div>';
        echo '  </div>';
        echo '  <div class="nsc-form-actions" style="margin-top:1rem;">';
        echo '    <button class="nsc-btn nsc-btn-danger" id="nsc-btn-apply-all">Aplicar Todos los Activos</button>';
        echo '  </div>';
        echo '  <div id="nsc-apply-progress" style="display:none;">';
        echo '    <div class="nsc-progress"><div class="nsc-progress-bar" id="nsc-progress-bar"></div></div>';
        echo '    <div id="nsc-apply-status" class="nsc-apply-status"></div>';
        echo '  </div>';
        echo '  <div id="nsc-apply-results" style="display:none;"></div>';
        echo '</div>';

        // Section 2: Rollback
        echo '<div class="nsc-card">';
        echo '  <h3>Historial y Rollback</h3>';
        echo '  <div class="nsc-toolbar">';
        echo '    <input type="text" class="nsc-input" id="nsc-backup-filter" placeholder="Filtrar por sistema...">';
        echo '    <button class="nsc-btn nsc-btn-sm" id="nsc-btn-load-backups">Buscar</button>';
        echo '  </div>';
        echo '  <div class="nsc-table-wrap">';
        echo '  <table class="nsc-table" id="nsc-backups-table">';
        echo '  <thead><tr><th>Fecha</th><th>Sistema</th><th>Template</th><th>Grupo</th><th>Version</th><th>Razon</th><th></th></tr></thead>';
        echo '  <tbody id="nsc-backups-tbody"><tr><td colspan="7" class="nsc-empty">Busque un sistema para ver sus backups</td></tr></tbody>';
        echo '  </table>';
        echo '  </div>';
        echo '</div>';

        // Section 3: Logs
        echo '<div class="nsc-card">';
        echo '  <h3>Log de Operaciones</h3>';
        echo '  <div class="nsc-table-wrap">';
        echo '  <table class="nsc-table" id="nsc-logs-table">';
        echo '  <thead><tr><th>Fecha</th><th>Accion</th><th>Grupo</th><th>Detalles</th><th>Afectados</th><th>Estado</th></tr></thead>';
        echo '  <tbody id="nsc-logs-tbody"><tr><td colspan="6" class="nsc-empty">Cargando...</td></tr></tbody>';
        echo '  </table>';
        echo '  </div>';
        echo '</div>';

        echo '</div>'; // panel
    }

    // ── Password Gate ──────────────────────────────────────────

    protected function renderPasswordGate($wrongKey = false) {
        echo '<div class="nsc-password-gate">';
        echo '<div class="nsc-card nsc-card-password">';
        echo '<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#6366f1" stroke-width="1.5"><path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z"/><circle cx="7.5" cy="10" r="1.5"/><circle cx="12" cy="7" r="1.5"/><circle cx="16.5" cy="10" r="1.5"/></svg>';
        echo '<h2>' . hsc($this->getLang('password_title') ?: 'Acceso Configurador de Estilos') . '</h2>';

        if ($wrongKey) {
            echo '<div class="nsc-alert nsc-alert-error">' . hsc($this->getLang('password_error') ?: 'Clave incorrecta') . '</div>';
        }

        echo '<form method="GET" action="">';
        echo '<input type="hidden" name="do" value="admin">';
        echo '<input type="hidden" name="page" value="niccstyleconfig">';
        echo '<div class="nsc-form-group">';
        echo '  <label>' . hsc($this->getLang('password_label') ?: 'Clave de acceso') . '</label>';
        echo '  <input type="password" name="stylekey" class="nsc-input" autofocus required>';
        echo '</div>';
        echo '<button type="submit" class="nsc-btn nsc-btn-primary nsc-btn-block">' . hsc($this->getLang('password_submit') ?: 'Ingresar') . '</button>';
        echo '</form>';
        echo '</div>';
        echo '</div>';
    }
}
