<?php

use dokuwiki\Extension\AdminPlugin;

/**
 * Task Semaphore Manager - Configuracion de semaforizacion de tareas
 *
 * Plugin para configurar los niveles de prioridad visual de tareas
 * segun los dias restantes para su vencimiento.
 */
class admin_plugin_tasksemaphore extends AdminPlugin
{
    /** @var helper_plugin_sqlite */
    protected $sqlite = null;

    /** @var bool Flag para saber si ya intentamos conectar */
    protected $db_initialized = false;

    /** @var string Mensaje de estado */
    protected $message = '';

    /** @var string Tipo de mensaje (success/error/info) */
    protected $message_type = '';

    /** @var array Configuracion de prioridades */
    protected $priorities = [];

    /**
     * Inicializa la conexion a la base de datos
     */
    protected function getDatabase()
    {
        if ($this->db_initialized) {
            return $this->sqlite;
        }

        $this->db_initialized = true;

        /** @var helper_plugin_bez_db $db_helper */
        $db_helper = plugin_load('helper', 'bez_db');
        if ($db_helper) {
            try {
                $this->sqlite = $db_helper->getDB();
            } catch (Exception $e) {
                $this->sqlite = null;
            }
        }

        return $this->sqlite;
    }

    /**
     * Retorna el texto del menu de administracion
     */
    public function getMenuText($language)
    {
        return $this->getLang('menu');
    }

    /**
     * Orden en el menu de administracion (despues de dbcleanup=4)
     */
    public function getMenuSort()
    {
        return 5;
    }

    /**
     * Accesible para managers, no solo admins
     */
    public function forAdminOnly()
    {
        return false;
    }

    /**
     * Verifica si el usuario tiene permisos de manager, admin o director
     */
    protected function isManager()
    {
        global $INFO;

        // 1. Verificar permisos nativos de DokuWiki
        if (auth_isadmin() || auth_ismanager()) {
            return true;
        }

        // 2. Verificar si el usuario pertenece al grupo "director"
        $grps = isset($INFO['userinfo']['grps']) ? $INFO['userinfo']['grps'] : [];
        if (in_array('director', $grps)) {
            return true;
        }

        return false;
    }

    /**
     * Icono del menu
     */
    public function getMenuIcon()
    {
        return DOKU_INC . 'lib/images/menu/settings.svg';
    }

    /**
     * Maneja las peticiones del usuario
     */
    public function handle()
    {
        global $INPUT;

        // Verificar permisos
        if (!$this->isManager()) {
            $this->message = $this->getLang('error_no_permission');
            $this->message_type = 'error';
            return;
        }

        // Cargar configuracion actual
        $this->loadPriorities();

        // Guardar configuracion
        if ($INPUT->post->has('save_config') && checkSecurityToken()) {
            $this->saveConfiguration($INPUT);
        }

        // Restaurar valores por defecto
        if ($INPUT->post->has('reset_config') && checkSecurityToken()) {
            $this->resetToDefaults();
        }

        // Enviar correo de prueba
        if ($INPUT->post->has('test_email') && checkSecurityToken()) {
            $this->sendTestEmail();
        }
    }

    /**
     * Carga la configuracion de prioridades desde la base de datos
     */
    protected function loadPriorities()
    {
        $db = $this->getDatabase();
        if (!$db) {
            return;
        }

        // Verificar si la tabla existe
        if (!$this->tableExists()) {
            $this->createTable();
        }

        $sql = "SELECT * FROM task_priority_config ORDER BY sort_order DESC, priority_level ASC";
        $result = $db->query($sql);

        if ($result) {
            $this->priorities = $db->res2arr($result);
        }
    }

    /**
     * Verifica si la tabla de configuracion existe
     */
    protected function tableExists()
    {
        $db = $this->getDatabase();
        if (!$db) {
            return false;
        }

        $sql = "SELECT name FROM sqlite_master WHERE type='table' AND name='task_priority_config'";
        $result = $db->query($sql);
        $row = $db->res2row($result);

        return !empty($row);
    }

    /**
     * Crea la tabla de configuracion si no existe
     */
    protected function createTable()
    {
        $db = $this->getDatabase();
        if (!$db) {
            return false;
        }

        $sql = "CREATE TABLE IF NOT EXISTS task_priority_config (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            priority_level INTEGER NOT NULL UNIQUE,
            days_from INTEGER,
            days_to INTEGER,
            background_color TEXT NOT NULL DEFAULT '#FFFFFF',
            border_color TEXT NOT NULL DEFAULT '#CCCCCC',
            label TEXT NOT NULL,
            notify_superuser INTEGER DEFAULT 0,
            notify_assignee INTEGER DEFAULT 1,
            notify_creator INTEGER DEFAULT 0,
            is_active INTEGER DEFAULT 1,
            sort_order INTEGER DEFAULT 0
        )";

        $db->query($sql);

        // Insertar valores por defecto
        $this->insertDefaults();

        return true;
    }

    /**
     * Inserta los valores por defecto (6 niveles)
     * Debe coincidir con update0017.sql para mantener consistencia
     */
    protected function insertDefaults()
    {
        $db = $this->getDatabase();
        if (!$db) {
            return;
        }

        // 6 niveles: Lejana, Normal, Proxima, Urgente, Hoy vence, Vencida
        // Estos valores deben coincidir con lib/plugins/bez/db/update0017.sql
        $defaults = [
            // [priority_level, days_from, days_to, background_color, border_color, label, notify_superuser, notify_assignee, notify_creator, is_active, sort_order]
            [0, 31, null, '#EEF6F0', '#B0D2B6', 'Lejana', 0, 0, 0, 1, 6],        // >= 31 dias
            [1, 15, 30, '#E8F5E9', '#81C784', 'Normal', 0, 0, 0, 1, 5],          // 15-30 dias
            [2, 7, 14, '#FFF9C4', '#FFF176', 'Proxima', 0, 0, 0, 1, 4],          // 7-14 dias
            [3, 1, 6, '#FFECB3', '#FFD54F', 'Urgente', 0, 1, 0, 1, 3],           // 1-6 dias
            [4, 0, 0, '#FFCDD2', '#EF5350', 'Hoy vence', 0, 1, 0, 1, 2],         // 0 dias (hoy)
            [5, null, -1, '#F8E8E8', '#F0AFAD', 'Vencida', 0, 1, 0, 1, 1],       // < 0 dias (vencida)
        ];

        foreach ($defaults as $row) {
            $sql = "INSERT OR IGNORE INTO task_priority_config
                    (priority_level, days_from, days_to, background_color, border_color, label, notify_superuser, notify_assignee, notify_creator, is_active, sort_order)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $db->query($sql, $row[0], $row[1], $row[2], $row[3], $row[4], $row[5], $row[6], $row[7], $row[8], $row[9], $row[10]);
        }
    }

    /**
     * Guarda la configuracion
     */
    protected function saveConfiguration($INPUT)
    {
        $db = $this->getDatabase();
        if (!$db) {
            $this->message = $this->getLang('msg_error_db');
            $this->message_type = 'error';
            return;
        }

        try {
            $priorities = $INPUT->post->arr('priority');

            // Validar solapamiento de rangos entre niveles activos
            $ranges = [];
            foreach ($priorities as $level => $data) {
                if (!isset($data['is_active'])) continue;
                $from = ($data['days_from'] !== '' && $data['days_from'] !== null) ? (int)$data['days_from'] : null;
                $to = ($data['days_to'] !== '' && $data['days_to'] !== null) ? (int)$data['days_to'] : null;
                $ranges[$level] = ['from' => $from, 'to' => $to, 'label' => $data['label']];
            }

            $warnings = $this->detectOverlaps($ranges);

            foreach ($priorities as $level => $data) {
                $sql = "UPDATE task_priority_config SET
                        days_from = ?,
                        days_to = ?,
                        background_color = ?,
                        border_color = ?,
                        label = ?,
                        notify_superuser = ?,
                        notify_assignee = ?,
                        notify_creator = ?,
                        is_active = ?
                        WHERE priority_level = ?";

                $days_from = ($data['days_from'] !== '' && $data['days_from'] !== null) ? (int)$data['days_from'] : null;
                $days_to = ($data['days_to'] !== '' && $data['days_to'] !== null) ? (int)$data['days_to'] : null;

                // Validar formato de colores hex (#RRGGBB)
                $bgColor = (isset($data['background_color']) && preg_match('/^#[0-9A-Fa-f]{6}$/', $data['background_color']))
                    ? $data['background_color'] : '#FFFFFF';
                $bdColor = (isset($data['border_color']) && preg_match('/^#[0-9A-Fa-f]{6}$/', $data['border_color']))
                    ? $data['border_color'] : '#CCCCCC';

                $db->query(
                    $sql,
                    $days_from,
                    $days_to,
                    $bgColor,
                    $bdColor,
                    $data['label'],
                    isset($data['notify_superuser']) ? 1 : 0,
                    isset($data['notify_assignee']) ? 1 : 0,
                    isset($data['notify_creator']) ? 1 : 0,
                    isset($data['is_active']) ? 1 : 0,
                    (int)$level
                );
            }

            $msg = $this->getLang('msg_saved');
            if (!empty($warnings)) {
                $msg .= ' Advertencia: ' . implode(' | ', $warnings);
                $this->message_type = 'info';
            } else {
                $this->message_type = 'success';
            }
            $this->message = $msg;

            // Recargar prioridades
            $this->loadPriorities();

        } catch (Exception $e) {
            $this->message = $this->getLang('msg_error') . ': ' . $e->getMessage();
            $this->message_type = 'error';
        }
    }

    /**
     * Detecta solapamientos entre rangos de dias de niveles activos
     */
    protected function detectOverlaps($ranges)
    {
        $warnings = [];
        $keys = array_keys($ranges);

        for ($i = 0; $i < count($keys); $i++) {
            for ($j = $i + 1; $j < count($keys); $j++) {
                $a = $ranges[$keys[$i]];
                $b = $ranges[$keys[$j]];

                // Expandir NULLs a limites amplios para comparacion
                $a_from = ($a['from'] !== null) ? $a['from'] : -9999;
                $a_to = ($a['to'] !== null) ? $a['to'] : 9999;
                $b_from = ($b['from'] !== null) ? $b['from'] : -9999;
                $b_to = ($b['to'] !== null) ? $b['to'] : 9999;

                // Dos rangos se solapan si a_from <= b_to AND b_from <= a_to
                if ($a_from <= $b_to && $b_from <= $a_to) {
                    $warnings[] = '"' . $a['label'] . '" y "' . $b['label'] . '" tienen rangos solapados';
                }
            }
        }

        return $warnings;
    }

    /**
     * Restaura los valores por defecto
     */
    protected function resetToDefaults()
    {
        $db = $this->getDatabase();
        if (!$db) {
            $this->message = $this->getLang('msg_error_db');
            $this->message_type = 'error';
            return;
        }

        try {
            // Transaccion para evitar tabla vacia si insertDefaults() falla
            $db->query("BEGIN TRANSACTION");

            // Eliminar configuracion actual
            $db->query("DELETE FROM task_priority_config");

            // Insertar valores por defecto
            $this->insertDefaults();

            $db->query("COMMIT");

            $this->message = $this->getLang('msg_reset');
            $this->message_type = 'success';

            // Recargar prioridades
            $this->loadPriorities();

        } catch (Exception $e) {
            // Revertir si algo fallo — la config anterior se restaura
            try { $db->query("ROLLBACK"); } catch (Exception $ignore) {}
            $this->message = $this->getLang('msg_error') . ': ' . $e->getMessage();
            $this->message_type = 'error';
        }
    }

    /**
     * Envia un correo de prueba
     */
    protected function sendTestEmail()
    {
        global $INFO, $conf;

        try {
            $mailer = new \Mailer();
            $mailer->to($INFO['userinfo']['mail']);
            $mailer->subject($conf['title'] . ' - Prueba de Semaforizacion de Tareas');

            $body = $this->buildTestEmailBody();
            $mailer->setBody('', null, null, $body);

            if ($mailer->send()) {
                $this->message = $this->getLang('msg_test_sent');
                $this->message_type = 'success';
            } else {
                $this->message = $this->getLang('msg_test_error');
                $this->message_type = 'error';
            }

        } catch (Exception $e) {
            $this->message = $this->getLang('msg_test_error') . ': ' . $e->getMessage();
            $this->message_type = 'error';
        }
    }

    /**
     * Construye el cuerpo del correo de prueba con estilo NICC
     */
    protected function buildTestEmailBody()
    {
        global $conf;

        $title = hsc($conf['title']);
        $date = date('d/m/Y H:i');

        // --- Construir filas de la tabla de prioridades ---
        $priorityRows = '';
        foreach ($this->priorities as $p) {
            $days = hsc($this->formatDaysRange($p['days_from'], $p['days_to']));
            $label = hsc($p['label']);
            $bgColor = preg_match('/^#[0-9A-Fa-f]{3,6}$/', $p['background_color']) ? $p['background_color'] : '#FFFFFF';
            $bdColor = preg_match('/^#[0-9A-Fa-f]{3,6}$/', $p['border_color']) ? $p['border_color'] : '#CCCCCC';
            $level = hsc($p['priority_level']);
            $notifyList = [];
            if ($p['notify_assignee']) $notifyList[] = 'Responsable';
            if ($p['notify_creator']) $notifyList[] = 'Creador';
            if ($p['notify_superuser']) $notifyList[] = 'Superusuario';
            $notify = !empty($notifyList) ? implode(', ', $notifyList) : 'Ninguno';

            $priorityRows .= '<tr>';
            $priorityRows .= '<td style="padding:10px 12px;border-bottom:1px solid #e8e6e1;text-align:center;font-weight:bold;color:#555;">' . $level . '</td>';
            $priorityRows .= '<td style="padding:10px 12px;border-bottom:1px solid #e8e6e1;">';
            $priorityRows .= '<span style="display:inline-block;padding:4px 12px;border-radius:4px;font-weight:bold;font-size:13px;background-color:' . $bgColor . ';border-left:4px solid ' . $bdColor . ';color:#333;">' . $label . '</span>';
            $priorityRows .= '</td>';
            $priorityRows .= '<td style="padding:10px 12px;border-bottom:1px solid #e8e6e1;color:#555;font-size:13px;">' . $days . '</td>';
            $priorityRows .= '<td style="padding:10px 12px;border-bottom:1px solid #e8e6e1;font-size:13px;">';
            $priorityRows .= '<span style="display:inline-block;width:14px;height:14px;border-radius:3px;background-color:' . $bgColor . ';border:1px solid ' . $bdColor . ';vertical-align:middle;margin-right:5px;"></span>';
            $priorityRows .= '<code style="font-size:11px;color:#777;">' . $bgColor . '</code>';
            $priorityRows .= '</td>';
            $priorityRows .= '<td style="padding:10px 12px;border-bottom:1px solid #e8e6e1;color:#555;font-size:13px;">' . hsc($notify) . '</td>';
            $priorityRows .= '<td style="padding:10px 12px;border-bottom:1px solid #e8e6e1;text-align:center;">';
            $priorityRows .= $p['is_active']
                ? '<span style="color:#27ae60;font-weight:bold;">&#10003;</span>'
                : '<span style="color:#c0392b;font-weight:bold;">&#10007;</span>';
            $priorityRows .= '</td>';
            $priorityRows .= '</tr>';
        }

        // --- Email HTML completo con estilo NICC ---
        $html = '<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>' . $title . ' - Prueba de Semaforizacion</title>
</head>
<body style="margin:0;padding:0;font-family:Arial,Helvetica,sans-serif;background-color:#f0eeea;">

<!-- Outer wrapper -->
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#f0eeea;">
<tr><td align="center" style="padding:30px 10px;">

<!-- Inner container 600px -->
<table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0" style="max-width:600px;width:100%;background-color:#ffffff;border-radius:0;">

<!-- Red accent top line -->
<tr><td style="height:4px;background-color:#e94560;font-size:0;line-height:0;">&nbsp;</td></tr>

<!-- Dark header -->
<tr><td style="background-color:#1a1a2e;padding:20px 30px;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<!-- Logo + title -->
<td style="vertical-align:middle;">
<table role="presentation" cellpadding="0" cellspacing="0" border="0">
<tr>
<td style="vertical-align:middle;padding-right:12px;">
<div style="width:38px;height:38px;background-color:#e94560;border-radius:6px;text-align:center;line-height:38px;font-size:20px;font-weight:bold;color:#ffffff;">N</div>
</td>
<td style="vertical-align:middle;">
<div style="font-size:18px;font-weight:bold;color:#ffffff;letter-spacing:1px;">NICC</div>
<div style="font-size:11px;color:#8a8a9a;margin-top:2px;">' . $title . '</div>
</td>
</tr>
</table>
</td>
<!-- Badge -->
<td style="vertical-align:middle;text-align:right;">
<span style="display:inline-block;background-color:#e94560;color:#ffffff;font-size:11px;font-weight:bold;padding:5px 14px;border-radius:12px;letter-spacing:0.5px;">Prueba</span>
</td>
</tr>
</table>
</td></tr>

<!-- Body area -->
<tr><td style="background-color:#f8f7f4;padding:28px 30px;">

<!-- Success info band -->
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:24px;">
<tr>
<td style="background-color:#ffffff;border-left:4px solid #27ae60;border-radius:4px;padding:16px 20px;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td style="vertical-align:middle;padding-right:12px;width:24px;">
<div style="width:24px;height:24px;background-color:#27ae60;border-radius:50%;text-align:center;line-height:24px;color:#fff;font-size:14px;font-weight:bold;">&#10003;</div>
</td>
<td style="vertical-align:middle;">
<div style="font-size:15px;font-weight:bold;color:#27ae60;">Correo de prueba enviado exitosamente</div>
<div style="font-size:12px;color:#888;margin-top:3px;">Enviado el ' . $date . '</div>
</td>
</tr>
</table>
</td>
</tr>
</table>

<!-- Intro text -->
<p style="font-size:14px;color:#555;line-height:1.6;margin:0 0 20px 0;">
Este correo confirma que el sistema de notificaciones por correo esta funcionando correctamente.
A continuacion se muestra la configuracion actual de semaforizacion de tareas.
</p>

<!-- Section title -->
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:14px;">
<tr>
<td style="font-size:16px;font-weight:bold;color:#1a1a2e;padding-bottom:8px;border-bottom:2px solid #e94560;">
Configuracion de Prioridades
</td>
</tr>
</table>

<!-- Priority config table -->
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#ffffff;border-radius:4px;overflow:hidden;">
<!-- Table header -->
<tr style="background-color:#1a1a2e;">
<th style="padding:10px 12px;color:#ffffff;font-size:12px;font-weight:bold;text-align:center;text-transform:uppercase;letter-spacing:0.5px;">Nivel</th>
<th style="padding:10px 12px;color:#ffffff;font-size:12px;font-weight:bold;text-align:left;text-transform:uppercase;letter-spacing:0.5px;">Etiqueta</th>
<th style="padding:10px 12px;color:#ffffff;font-size:12px;font-weight:bold;text-align:left;text-transform:uppercase;letter-spacing:0.5px;">Dias</th>
<th style="padding:10px 12px;color:#ffffff;font-size:12px;font-weight:bold;text-align:left;text-transform:uppercase;letter-spacing:0.5px;">Color</th>
<th style="padding:10px 12px;color:#ffffff;font-size:12px;font-weight:bold;text-align:left;text-transform:uppercase;letter-spacing:0.5px;">Notificar</th>
<th style="padding:10px 12px;color:#ffffff;font-size:12px;font-weight:bold;text-align:center;text-transform:uppercase;letter-spacing:0.5px;">Activo</th>
</tr>
<!-- Data rows -->
' . $priorityRows . '
</table>

</td></tr>

<!-- Footer -->
<tr><td style="background-color:#1a1a2e;padding:24px 30px;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<!-- SIE Asesorias column -->
<td style="vertical-align:top;width:50%;">
<div style="font-size:14px;font-weight:bold;color:#ffffff;margin-bottom:6px;">SIE Asesorias</div>
<div style="font-size:12px;color:#8a8a9a;line-height:1.5;">Sistema Integral Empresarial<br>Soluciones de gestion documental</div>
</td>
<!-- Contact column -->
<td style="vertical-align:top;width:50%;text-align:right;">
<div style="font-size:14px;font-weight:bold;color:#ffffff;margin-bottom:6px;">Contacto</div>
<div style="font-size:12px;color:#8a8a9a;line-height:1.5;">proyect@sieasesorias.com<br>www.sieasesorias.com</div>
</td>
</tr>
</table>

<!-- Copyright line -->
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-top:16px;border-top:1px solid #2a2a4e;padding-top:12px;">
<tr><td style="text-align:center;font-size:11px;color:#666;">
&copy; ' . date('Y') . ' ' . $title . '. Todos los derechos reservados.
</td></tr>
</table>
</td></tr>

<!-- Red accent bottom line -->
<tr><td style="height:4px;background-color:#e94560;font-size:0;line-height:0;">&nbsp;</td></tr>

</table>
<!-- /Inner container -->

</td></tr>
</table>
<!-- /Outer wrapper -->

</body>
</html>';

        return $html;
    }

    /**
     * Formatea el rango de dias para mostrar
     */
    protected function formatDaysRange($from, $to)
    {
        // Normalizar valores NULL de SQLite (pueden venir como null, '', o 'NULL')
        $from_is_null = ($from === null || $from === '' || $from === 'NULL');
        $to_is_null = ($to === null || $to === '' || $to === 'NULL');

        if ($from_is_null && $to_is_null) {
            return 'Sin limite';
        }
        if ($from_is_null) {
            return '<= ' . (int)$to . ' dias';
        }
        if ($to_is_null) {
            return '>= ' . (int)$from . ' dias';
        }
        if ((int)$from == (int)$to) {
            return (int)$from . ' dias';
        }
        return (int)$from . ' a ' . (int)$to . ' dias';
    }

    /**
     * Genera la salida HTML
     */
    public function html()
    {
        global $ID;

        echo '<div id="tasksemaphore_manager">';

        // Verificar permisos
        if (!$this->isManager()) {
            echo '<div class="notify error">';
            echo '<p>' . hsc($this->getLang('error_no_permission')) . '</p>';
            echo '</div>';
            $this->printStyles();
            echo '</div>';
            return;
        }

        // Titulo
        echo '<h1>' . hsc($this->getLang('title')) . '</h1>';
        echo '<p class="description">' . hsc($this->getLang('description')) . '</p>';

        // Mostrar mensaje si hay
        if ($this->message) {
            $class = $this->message_type === 'success' ? 'notify' : ($this->message_type === 'info' ? 'info' : 'error');
            echo '<div class="' . $class . '">';
            echo '<p>' . hsc($this->message) . '</p>';
            echo '</div>';
        }

        // Verificar conexion a BD
        $db = $this->getDatabase();
        if (!$db) {
            echo '<div class="error"><p>' . hsc($this->getLang('msg_error_db')) . '</p></div>';
            $this->printStyles();
            echo '</div>';
            return;
        }

        // Formulario de configuracion
        $this->printConfigForm();

        // Vista previa
        $this->printPreview();

        $this->printStyles();
        echo '</div>';
    }

    /**
     * Imprime el formulario de configuracion
     */
    protected function printConfigForm()
    {
        global $ID;

        echo '<form method="post" action="' . wl($ID, ['do' => 'admin', 'page' => 'tasksemaphore']) . '">';
        echo '<input type="hidden" name="sectok" value="' . getSecurityToken() . '" />';

        echo '<h2>' . hsc($this->getLang('subtitle_config')) . '</h2>';

        echo '<div class="table-wrapper">';
        echo '<table class="inline config-table">';
        echo '<thead>';
        // Fila superior con agrupadores
        echo '<tr class="header-group">';
        echo '<th rowspan="2">' . hsc($this->getLang('col_level')) . '</th>';
        echo '<th rowspan="2">' . hsc($this->getLang('col_label')) . '</th>';
        echo '<th colspan="2" class="group-header">' . hsc($this->getLang('col_days')) . '</th>';
        echo '<th colspan="2" class="group-header">' . hsc($this->getLang('col_colors')) . '</th>';
        echo '<th colspan="3" class="group-header">' . hsc($this->getLang('col_notify')) . '</th>';
        echo '<th rowspan="2">' . hsc($this->getLang('col_active')) . '</th>';
        echo '</tr>';
        // Fila inferior con subcolumnas
        echo '<tr class="header-sub">';
        echo '<th>' . hsc($this->getLang('col_days_from')) . '</th>';
        echo '<th>' . hsc($this->getLang('col_days_to')) . '</th>';
        echo '<th>' . hsc($this->getLang('col_background')) . '</th>';
        echo '<th>' . hsc($this->getLang('col_border')) . '</th>';
        echo '<th>' . hsc($this->getLang('col_notify_superuser')) . '</th>';
        echo '<th>' . hsc($this->getLang('col_notify_assignee')) . '</th>';
        echo '<th>' . hsc($this->getLang('col_notify_creator')) . '</th>';
        echo '</tr>';
        echo '</thead>';
        echo '<tbody>';

        foreach ($this->priorities as $p) {
            $level = $p['priority_level'];
            $bgColor = hsc($p['background_color']);
            $borderColor = hsc($p['border_color']);

            echo '<tr style="background-color: ' . $bgColor . '; border-left: 4px solid ' . $borderColor . ';">';

            // Estado descriptivo (sin numero)
            echo '<td class="level-col">';
            echo '<small>' . hsc($this->getLang('level_desc_' . $level)) . '</small>';
            echo '</td>';

            // Etiqueta
            echo '<td>';
            echo '<input type="text" name="priority[' . $level . '][label]" value="' . hsc($p['label']) . '" class="input-text" required />';
            echo '</td>';

            // Dias desde
            echo '<td class="days-col">';
            echo '<input type="number" name="priority[' . $level . '][days_from]" value="' . ($p['days_from'] !== null ? hsc($p['days_from']) : '') . '" class="input-number" />';
            echo '</td>';

            // Dias hasta
            echo '<td class="days-col">';
            echo '<input type="number" name="priority[' . $level . '][days_to]" value="' . ($p['days_to'] !== null ? hsc($p['days_to']) : '') . '" class="input-number" />';
            echo '</td>';

            // Color de fondo
            echo '<td class="color-col">';
            echo '<input type="color" name="priority[' . $level . '][background_color]" value="' . $bgColor . '" class="input-color" title="' . $bgColor . '" />';
            echo '</td>';

            // Color de borde
            echo '<td class="color-col">';
            echo '<input type="color" name="priority[' . $level . '][border_color]" value="' . $borderColor . '" class="input-color" title="' . $borderColor . '" />';
            echo '</td>';

            // Notificar superusuarios
            echo '<td class="check-col">';
            echo '<input type="checkbox" name="priority[' . $level . '][notify_superuser]" ' . ($p['notify_superuser'] ? 'checked' : '') . ' />';
            echo '</td>';

            // Notificar responsable
            echo '<td class="check-col">';
            echo '<input type="checkbox" name="priority[' . $level . '][notify_assignee]" ' . ($p['notify_assignee'] ? 'checked' : '') . ' />';
            echo '</td>';

            // Notificar creador
            echo '<td class="check-col">';
            echo '<input type="checkbox" name="priority[' . $level . '][notify_creator]" ' . ($p['notify_creator'] ? 'checked' : '') . ' />';
            echo '</td>';

            // Activo
            echo '<td class="check-col">';
            echo '<input type="checkbox" name="priority[' . $level . '][is_active]" ' . ($p['is_active'] ? 'checked' : '') . ' />';
            echo '</td>';

            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
        echo '</div>';

        // Ayuda
        echo '<div class="help-box">';
        echo '<p><strong>' . hsc($this->getLang('col_days')) . ':</strong> ' . hsc($this->getLang('help_days_from')) . '</p>';
        echo '<p><strong>' . hsc($this->getLang('col_notify')) . ':</strong> ' . hsc($this->getLang('help_notify')) . '</p>';
        echo '</div>';

        // Botones
        echo '<div class="button-group">';
        echo '<button type="submit" name="save_config" class="btn btn-primary">' . hsc($this->getLang('btn_save')) . '</button>';
        echo ' ';
        echo '<button type="submit" name="reset_config" class="btn btn-warning" onclick="return confirm(\'Restaurar valores por defecto?\');">' . hsc($this->getLang('btn_reset')) . '</button>';
        echo ' ';
        echo '<button type="submit" name="test_email" class="btn btn-info">' . hsc($this->getLang('btn_test_email')) . '</button>';
        echo '</div>';

        echo '</form>';

    }

    /**
     * Imprime la vista previa de los colores
     */
    protected function printPreview()
    {
        echo '<h2>' . hsc($this->getLang('subtitle_preview')) . '</h2>';

        echo '<div class="preview-container">';
        echo '<table class="inline preview-table">';
        echo '<thead><tr><th colspan="2">' . hsc($this->getLang('preview_title')) . '</th></tr></thead>';
        echo '<tbody>';

        foreach ($this->priorities as $p) {
            if (!$p['is_active']) continue;

            $bgColor = hsc($p['background_color']);
            $borderColor = hsc($p['border_color']);
            $days = $this->formatDaysRange($p['days_from'], $p['days_to']);

            echo '<tr class="preview-row" style="background-color: ' . $bgColor . '; border-left: 5px solid ' . $borderColor . ';">';
            echo '<td class="preview-label"><strong>' . hsc($p['label']) . '</strong></td>';
            echo '<td class="preview-days">' . hsc($days) . '</td>';
            echo '</tr>';
        }

        echo '</tbody>';
        echo '</table>';
        echo '</div>';
    }

    /**
     * Imprime los estilos CSS
     */
    protected function printStyles()
    {
        echo '<style>
            #tasksemaphore_manager {
                max-width: 1200px;
                margin: 0 auto;
                padding: 20px;
            }

            #tasksemaphore_manager h1 {
                color: #2c3e50;
                border-bottom: 3px solid #3498db;
                padding-bottom: 10px;
                margin-bottom: 10px;
            }

            #tasksemaphore_manager h2 {
                color: #34495e;
                margin-top: 30px;
                margin-bottom: 15px;
            }

            #tasksemaphore_manager .description {
                color: #7f8c8d;
                font-size: 1.1em;
                margin-bottom: 20px;
            }

            #tasksemaphore_manager .notify {
                background: #d4edda;
                border: 1px solid #c3e6cb;
                color: #155724;
                padding: 15px;
                border-radius: 5px;
                margin-bottom: 20px;
            }

            #tasksemaphore_manager .error {
                background: #f8d7da;
                border: 1px solid #f5c6cb;
                color: #721c24;
                padding: 15px;
                border-radius: 5px;
                margin-bottom: 20px;
            }

            #tasksemaphore_manager .info {
                background: #d1ecf1;
                border: 1px solid #bee5eb;
                color: #0c5460;
                padding: 15px;
                border-radius: 5px;
                margin-bottom: 20px;
            }

            #tasksemaphore_manager .table-wrapper {
                overflow-x: auto;
                margin-bottom: 20px;
            }

            #tasksemaphore_manager .config-table {
                width: 100%;
                border-collapse: collapse;
            }

            #tasksemaphore_manager .config-table th {
                background: #34495e;
                color: white;
                padding: 8px 6px;
                text-align: center;
                font-size: 0.85em;
                white-space: nowrap;
                border: 1px solid #2c3e50;
            }

            #tasksemaphore_manager .config-table .header-group th {
                border-bottom: none;
            }

            #tasksemaphore_manager .config-table .header-sub th {
                background: #4a6785;
                font-weight: normal;
                font-size: 0.8em;
                padding: 5px 4px;
            }

            #tasksemaphore_manager .config-table .group-header {
                background: #2c3e50;
                font-weight: bold;
            }

            #tasksemaphore_manager .config-table td {
                padding: 8px 5px;
                border-bottom: 1px solid #ddd;
                vertical-align: middle;
            }

            #tasksemaphore_manager .config-table tr:hover {
                filter: brightness(0.98);
            }

            #tasksemaphore_manager .level-col {
                min-width: 100px;
                max-width: 120px;
            }

            #tasksemaphore_manager .level-col small {
                color: #333;
                font-size: 0.85em;
                font-weight: 500;
            }

            #tasksemaphore_manager .days-col {
                width: 60px;
            }

            #tasksemaphore_manager .color-col {
                width: 80px;
            }

            #tasksemaphore_manager .check-col {
                width: 45px;
                text-align: center;
            }

            #tasksemaphore_manager .input-text {
                width: 130px;
                padding: 5px 6px;
                border: 1px solid #ccc;
                border-radius: 4px;
                font-size: 0.9em;
            }

            #tasksemaphore_manager .input-number {
                width: 55px;
                padding: 5px 4px;
                border: 1px solid #ccc;
                border-radius: 4px;
                text-align: center;
                font-size: 0.9em;
            }

            #tasksemaphore_manager .input-color {
                width: 35px;
                height: 28px;
                padding: 0;
                border: 1px solid #ccc;
                border-radius: 4px;
                cursor: pointer;
                vertical-align: middle;
            }

            #tasksemaphore_manager input[type="checkbox"] {
                width: 16px;
                height: 16px;
                cursor: pointer;
            }

            #tasksemaphore_manager .help-box {
                background: #f8f9fa;
                border: 1px solid #e9ecef;
                border-radius: 5px;
                padding: 15px;
                margin: 20px 0;
            }

            #tasksemaphore_manager .help-box p {
                margin: 8px 0;
                font-size: 0.9em;
                color: #555;
            }

            #tasksemaphore_manager .button-group {
                margin-top: 25px;
                padding-top: 20px;
                border-top: 1px solid #eee;
            }

            #tasksemaphore_manager .btn {
                display: inline-block;
                padding: 12px 24px;
                font-size: 1em;
                font-weight: bold;
                text-decoration: none;
                border: none;
                border-radius: 5px;
                cursor: pointer;
                transition: all 0.3s ease;
            }

            #tasksemaphore_manager .btn-primary {
                background: #3498db;
                color: white;
            }

            #tasksemaphore_manager .btn-primary:hover {
                background: #2980b9;
            }

            #tasksemaphore_manager .btn-warning {
                background: #f39c12;
                color: white;
            }

            #tasksemaphore_manager .btn-warning:hover {
                background: #d68910;
            }

            #tasksemaphore_manager .btn-info {
                background: #17a2b8;
                color: white;
            }

            #tasksemaphore_manager .btn-info:hover {
                background: #138496;
            }

            #tasksemaphore_manager .preview-container {
                margin-top: 20px;
            }

            #tasksemaphore_manager .preview-table {
                width: 100%;
                max-width: 600px;
                border-collapse: collapse;
            }

            #tasksemaphore_manager .preview-table th {
                background: #34495e;
                color: white;
                padding: 12px;
                text-align: left;
            }

            #tasksemaphore_manager .preview-row td {
                padding: 15px;
            }

            #tasksemaphore_manager .preview-label {
                width: 30%;
            }

            #tasksemaphore_manager .preview-days {
                width: 30%;
                color: #555;
            }

            #tasksemaphore_manager .preview-sample {
                color: #777;
                font-style: italic;
            }
        </style>';
    }
}
