<?php
declare(strict_types=1);

require_once '../../common/app_guard.php';
checkAppAccess();

require_once __DIR__ . '/../../common/catalogo_db.php';
require_once __DIR__ . '/../../common/mailsignatures_db.php';

if (!catalogo_is_admin()) {
    if (function_exists('renderErrorPage')) {
        renderErrorPage('Solo administradores pueden gestionar las firmas de correo.');
        exit;
    }
    http_response_code(403);
    die('Acceso restringido');
}

$pdo = db();
mail_signatures_ensure_schema($pdo);

function h($s): string { return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }

$msg = '';
$err = '';

if (isset($_GET['ok'])) {
    $ok = (int)$_GET['ok'];
    if ($ok === 1) $msg = 'Firma guardada correctamente.';
    if ($ok === 2) $msg = 'Firmas actualizadas correctamente.';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        catalogo_csrf_validate($_POST['csrf'] ?? null, 'mail_sigs_admin_csrf');
        $action = isset($_POST['action']) && is_string($_POST['action']) ? trim($_POST['action']) : '';

        if ($action === 'add') {
            $title = trim((string)($_POST['title'] ?? ''));
            $validFrom = trim((string)($_POST['valid_from'] ?? ''));
            $html = trim((string)($_POST['html_signature'] ?? ''));
            $text = trim((string)($_POST['text_signature'] ?? ''));
            $enabled = isset($_POST['is_enabled']) && (string)$_POST['is_enabled'] === '1' ? 1 : 0;

            if ($title === '') throw new RuntimeException('El título es obligatorio.');
            if ($validFrom === '' || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $validFrom)) throw new RuntimeException('Fecha "Válida desde" inválida (formato AAAA-MM-DD).');
            if ($html === '') throw new RuntimeException('La firma HTML es obligatoria.');

            $st = $pdo->prepare('INSERT INTO mail_signatures (title, valid_from, html_signature, text_signature, is_enabled) VALUES (:t, :vf, :h, :x, :en)');
            $st->execute([
                ':t' => $title,
                ':vf' => $validFrom,
                ':h' => $html,
                ':x' => ($text !== '' ? $text : null),
                ':en' => $enabled,
            ]);

            header('Location: index.php?ok=1');
            exit;
        }

        if ($action === 'bulk_save') {
            $rows = $_POST['rows'] ?? [];
            if (!is_array($rows)) $rows = [];

            foreach ($rows as $r) {
                if (!is_array($r)) continue;
                $id = isset($r['id']) ? (int)$r['id'] : 0;
                if ($id <= 0) continue;

                $doDelete = !empty($r['_delete']);
                if ($doDelete) {
                    $st = $pdo->prepare('DELETE FROM mail_signatures WHERE id = :id');
                    $st->execute([':id' => $id]);
                    continue;
                }

                $doUpdate = !empty($r['_update']);
                if (!$doUpdate) continue;

                $title = trim((string)($r['title'] ?? ''));
                $validFrom = trim((string)($r['valid_from'] ?? ''));
                $html = trim((string)($r['html_signature'] ?? ''));
                $text = trim((string)($r['text_signature'] ?? ''));
                $enabled = isset($r['is_enabled']) && (string)$r['is_enabled'] === '1' ? 1 : 0;

                if ($title === '') throw new RuntimeException("Título vacío en ID {$id}.");
                if ($validFrom === '' || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $validFrom)) throw new RuntimeException("Fecha inválida en ID {$id} (AAAA-MM-DD).");
                if ($html === '') throw new RuntimeException("Firma HTML vacía en ID {$id}.");

                $st = $pdo->prepare('UPDATE mail_signatures SET title=:t, valid_from=:vf, html_signature=:h, text_signature=:x, is_enabled=:en WHERE id=:id');
                $st->execute([
                    ':t' => $title,
                    ':vf' => $validFrom,
                    ':h' => $html,
                    ':x' => ($text !== '' ? $text : null),
                    ':en' => $enabled,
                    ':id' => $id,
                ]);
            }

            header('Location: index.php?ok=2');
            exit;
        }

        throw new RuntimeException('Acción inválida.');

    } catch (Throwable $e) {
        $err = $e->getMessage();
    }
}

$csrf = catalogo_csrf_token('mail_sigs_admin_csrf');
$rows = $pdo->query('SELECT * FROM mail_signatures ORDER BY valid_from DESC, id DESC')->fetchAll(PDO::FETCH_ASSOC);
$current = mail_signatures_get_current($pdo);
$themeFile = dirname(__DIR__, 2) . '/styles/css/theme-vars.css';
$themeVersion = is_file($themeFile) ? (string) filemtime($themeFile) : (string) time();

?><!doctype html>
<html lang="es" class="app-html" <?= intranet_theme_html_attr(); ?>>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Firmas de correo</title>
    <?= intranet_theme_bootstrap_script_tag(); ?>
    <link rel="stylesheet" href="../../styles/css/style.css" />
    <link rel="stylesheet" href="../../styles/css/theme-vars.css?v=<?= urlencode($themeVersion) ?>" />
    <style>
        .sig-grid{display:grid;grid-template-columns:2fr 1fr;gap:18px;align-items:start}
        @media (max-width:980px){.sig-grid{grid-template-columns:1fr}}
        .sig-row{display:grid;grid-template-columns:1fr 1fr;gap:12px}
        @media (max-width:720px){.sig-row{grid-template-columns:1fr}}
        .sig-field label{display:block;font-size:.85rem;font-weight:800;margin-bottom:8px;color:var(--text-main)}
        .sig-help{margin-top:6px;font-size:.85rem;color:var(--text-muted)}
        .sig-ta{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;min-height:180px;resize:vertical}
        .sig-ta--small{min-height:120px}
        .sig-actions{display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin-top:14px}
        .sig-badges{display:flex;gap:10px;flex-wrap:wrap;align-items:center}
        .sig-badge{display:inline-flex;align-items:center;gap:8px;padding:6px 10px;border-radius:999px;font-size:.8rem;font-weight:800;border:1px solid var(--border-light);background:var(--bg-input);color:var(--text-main)}
        .sig-badge--ok{background:color-mix(in srgb, var(--success-bg) 88%, var(--bg-card) 12%);color:var(--success-text);border-color:var(--success-border)}
        .sig-badge--warn{background:color-mix(in srgb, var(--primary-light) 72%, var(--bg-card) 28%);color:var(--primary-dark);border-color:color-mix(in srgb, var(--primary) 24%, var(--border-light) 76%)}
        .sig-table textarea{min-width:360px}
        .sig-table td{vertical-align:top}
        .sig-check{display:flex;gap:10px;align-items:center;white-space:nowrap}
        .sig-soft-card{padding:16px;margin:0;background:color-mix(in srgb, var(--bg-input) 82%, var(--bg-card) 18%);border:1px solid var(--border-light);border-radius:12px}
        .sig-soft-card .form-control{background:var(--bg-card);color:var(--text-main);border-color:var(--border-light)}
        .sig-soft-card input[type="date"],
        .sig-soft-card select{appearance:auto}
        .sig-empty{color:var(--text-muted)}
        .sig-inline-note{color:var(--text-muted);font-size:.9rem}
        .sig-delete-text{font-weight:800;color:var(--error-text)}
        .sig-actions > span{color:var(--text-muted)!important;font-size:.9rem!important}
        html[data-theme="dark"] .sig-soft-card,
        html[data-theme-variant="contrast"] .sig-soft-card{
            background:color-mix(in srgb, var(--bg-input) 88%, var(--bg-card) 12%);
        }
        html[data-theme="dark"] .sig-soft-card .form-control,
        html[data-theme-variant="contrast"] .sig-soft-card .form-control{
            background:var(--bg-input);
            color:var(--text-main);
            border-color:var(--border-light);
            box-shadow:inset 0 1px 0 rgba(255,255,255,0.03);
        }
        html[data-theme="dark"] .sig-soft-card input[type="date"],
        html[data-theme="dark"] .sig-soft-card select,
        html[data-theme-variant="contrast"] .sig-soft-card input[type="date"],
        html[data-theme-variant="contrast"] .sig-soft-card select{
            color-scheme:dark;
        }
    </style>
</head>
<body class="app-body">
<div class="app-container">

    <!-- CABECERA ESTILO INTRANET -->
    <header class="header-top">
        <div class="header-info">
            <h2>Firmas de correo</h2>
            <p>Gestión de firmas con vigencia por fecha (se usa la última válida).</p>

            <?php if ($current): ?>
                <div class="sig-badges" style="margin-top:10px;">
                    <span class="sig-badge sig-badge--ok">Vigente: <strong><?php echo h((string)$current['title']); ?></strong></span>
                    <span class="sig-badge">Desde: <strong><?php echo h((string)$current['valid_from']); ?></strong></span>
                </div>
            <?php else: ?>
                <div class="sig-badges" style="margin-top:10px;">
                    <span class="sig-badge sig-badge--warn">Vigente: <strong>No hay ninguna firma válida/activa</strong></span>
                </div>
            <?php endif; ?>
        </div>
        <div class="header-actions">
            <a href="../../dashboard.php" target="_top" class="btn-back-dashboard">Volver al inicio</a>
        </div>
    </header>

    <?php if ($msg): ?>
        <div class="admin-notice" style="margin:18px 0;">
            <?php echo h($msg); ?>
        </div>
    <?php endif; ?>
    <?php if ($err): ?>
        <div class="alert alert-error" style="margin:18px 0;">
            <?php echo h($err); ?>
        </div>
    <?php endif; ?>

    <main>
        <div class="card" style="margin-top:18px;">
            <div class="card-title"><span>Añadir firma</span></div>

            <form method="post">
                <input type="hidden" name="csrf" value="<?php echo h($csrf); ?>" />
                <input type="hidden" name="action" value="add" />

                <div class="sig-grid">
                    <!-- Columna principal -->
                    <div>
                        <div class="sig-field" style="margin-bottom:12px;">
                            <label for="title">Título</label>
                            <input id="title" class="form-control" name="title" type="text" placeholder="Ej: Firma temporada Primavera 2026" required />
                        </div>

                        <div class="sig-field" style="margin-bottom:12px;">
                            <label for="html_signature">Firma HTML</label>
                            <textarea id="html_signature" class="form-control sig-ta" name="html_signature" placeholder="Pega aquí la firma en HTML" required></textarea>
                            <div class="sig-help">Se insertará al final del correo, separada por una línea horizontal.</div>
                        </div>

                        <div class="sig-field" style="margin-bottom:12px;">
                            <label for="text_signature">Firma texto (opcional)</label>
                            <textarea id="text_signature" class="form-control sig-ta sig-ta--small" name="text_signature" placeholder="Versión en texto plano (si no se indica, se genera a partir del HTML)"></textarea>
                        </div>

                        <div class="sig-actions">
                            <button class="btn-intranet" type="submit">Guardar firma</button>
                        </div>
                    </div>

                    <!-- Columna lateral -->
                    <div>
                        <div class="sig-soft-card">
                            <div class="sig-row">
                                <div class="sig-field">
                                    <label for="valid_from">Válida desde</label>
                                    <input id="valid_from" class="form-control" name="valid_from" type="date" required />
                                    <div class="sig-help">Formato: AAAA-MM-DD</div>
                                </div>
                                <div class="sig-field">
                                    <label for="is_enabled">Activa</label>
                                    <select id="is_enabled" class="form-control" name="is_enabled">
                                        <option value="1" selected>Sí</option>
                                        <option value="0">No</option>
                                    </select>
                                    <div class="sig-help">Solo se usan firmas activas y vigentes.</div>
                                </div>
                            </div>
                            <div class="sig-help" style="margin-top:10px;">
                                Consejo: si publicas una nueva firma, deja las antiguas en <strong>No</strong> para evitar confusiones.
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>

        <div class="card" style="margin-top:18px;">
            <div class="card-title"><span>Firmas existentes</span></div>

            <?php if (!$rows): ?>
                <div class="sig-empty">No hay firmas registradas.</div>
            <?php else: ?>
                <form method="post">
                    <input type="hidden" name="csrf" value="<?php echo h($csrf); ?>" />
                    <input type="hidden" name="action" value="bulk_save" />

                    <div class="table-responsive sig-table">
                        <table style="min-width:1100px;">
                            <thead>
                            <tr>
                                <th style="width:70px;">ID</th>
                                <th style="width:260px;">Título</th>
                                <th style="width:160px;">Válida desde</th>
                                <th style="width:120px;">Activa</th>
                                <th>Firma HTML</th>
                                <th>Firma texto</th>
                                <th style="width:120px;">Acciones</th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php foreach ($rows as $i => $r): ?>
                                <?php
                                $id = (int)($r['id'] ?? 0);
                                $isEnabled = (int)($r['is_enabled'] ?? 0);
                                ?>
                                <tr>
                                    <td>
                                        <?php echo h((string)$id); ?>
                                        <input type="hidden" name="rows[<?php echo $i; ?>][id]" value="<?php echo h((string)$id); ?>" />
                                    </td>
                                    <td>
                                        <input class="form-control" name="rows[<?php echo $i; ?>][title]" type="text" value="<?php echo h((string)($r['title'] ?? '')); ?>" />
                                    </td>
                                    <td>
                                        <input class="form-control" name="rows[<?php echo $i; ?>][valid_from]" type="date" value="<?php echo h((string)($r['valid_from'] ?? '')); ?>" />
                                    </td>
                                    <td>
                                        <select class="form-control" name="rows[<?php echo $i; ?>][is_enabled]">
                                            <option value="1" <?php echo $isEnabled === 1 ? 'selected' : ''; ?>>Sí</option>
                                            <option value="0" <?php echo $isEnabled === 0 ? 'selected' : ''; ?>>No</option>
                                        </select>
                                    </td>
                                    <td>
                                        <textarea class="form-control sig-ta sig-ta--small" name="rows[<?php echo $i; ?>][html_signature]" rows="6"><?php echo h((string)($r['html_signature'] ?? '')); ?></textarea>
                                    </td>
                                    <td>
                                        <textarea class="form-control sig-ta sig-ta--small" name="rows[<?php echo $i; ?>][text_signature]" rows="6"><?php echo h((string)($r['text_signature'] ?? '')); ?></textarea>
                                    </td>
                                    <td>
                                        <div class="sig-check" style="margin-bottom:10px;">
                                            <input type="checkbox" name="rows[<?php echo $i; ?>][_update]" value="1" />
                                            <span style="font-weight:800;">Actualizar</span>
                                        </div>
                                        <div class="sig-check">
                                            <input type="checkbox" name="rows[<?php echo $i; ?>][_delete]" value="1" />
                                            <span class="sig-delete-text">Eliminar</span>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>

                    <div class="sig-actions">
                        <button class="btn-intranet" type="submit">Aplicar cambios</button>
                        <span style="color:#64748b; font-size:0.9rem;">Marca “Actualizar” o “Eliminar” por fila.</span>
                    </div>
                </form>
            <?php endif; ?>
        </div>

        <div style="height:32px"></div>
    </main>

</div>
</body>
</html>
