<?php

declare(strict_types=1);

require_once __DIR__ . '/init.php';
require_once dirname(__DIR__) . '/lib/ImapProviderCatalog.php';

restringir_modulo_superadmin('Dominios');
exigir_permiso('gestionar_propios_dominios', 'No tienes permiso para gestionar dominios.');

$id_admin_actual = (int) ($_SESSION['admin']['uid'] ?? 0);

if (isset($_GET['fetch_data'])) {
    Security::headers(true);
    $id = filter_input(INPUT_GET, 'fetch_data', FILTER_VALIDATE_INT);
    if (!$id) {
        Security::json(['success' => false, 'message' => 'ID de dominio inválido.'], 422);
    }

    $stmt = $pdo->prepare('SELECT * FROM dominios WHERE id = ? AND id_admin_propietario = ? LIMIT 1');
    $stmt->execute([$id, $id_admin_actual]);
    $data = $stmt->fetch(PDO::FETCH_ASSOC);
    if (!$data) {
        Security::json(['success' => false, 'message' => 'El dominio no existe o no te pertenece.'], 404);
    }

    $subjects = $pdo->prepare('SELECT id_asunto, es_publico FROM dominio_asunto WHERE id_dominio = ?');
    $subjects->execute([$id]);
    Security::json([
        'success' => true,
        'data' => $data,
        'asuntos' => $subjects->fetchAll(PDO::FETCH_ASSOC),
    ]);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    Security::headers(true);
    Security::requireCsrf();
    $action = (string) ($_POST['action'] ?? '');

    if ($action === 'delete_dominio') {
        $id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
        if (!$id) {
            Security::json(['success' => false, 'message' => 'ID de dominio inválido.'], 422);
        }

        $usage = $pdo->prepare(
            'SELECT COUNT(*) FROM correos_servicios WHERE id_dominio = ? AND id_admin_propietario = ?'
        );
        $usage->execute([$id, $id_admin_actual]);
        if ((int) $usage->fetchColumn() > 0) {
            Security::json([
                'success' => false,
                'message' => 'No se puede eliminar: el dominio todavía tiene cuentas de servicio asociadas.',
            ], 409);
        }

        $pdo->beginTransaction();
        try {
            $pdo->prepare('DELETE FROM dominio_asunto WHERE id_dominio = ?')->execute([$id]);
            $delete = $pdo->prepare('DELETE FROM dominios WHERE id = ? AND id_admin_propietario = ?');
            $delete->execute([$id, $id_admin_actual]);
            if ($delete->rowCount() !== 1) {
                throw new RuntimeException('El dominio no fue encontrado.');
            }
            $pdo->commit();
            Security::json(['success' => true, 'message' => 'Dominio eliminado correctamente.']);
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            error_log('Error eliminando dominio: ' . $e->getMessage());
            Security::json(['success' => false, 'message' => $e instanceof RuntimeException ? $e->getMessage() : 'No se pudo eliminar el dominio.'], 400);
        }
    }

    if ($action !== 'guardar_dominio') {
        Security::json(['success' => false, 'message' => 'Acción no reconocida.'], 400);
    }

    try {
        $id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT) ?: null;
        $domain = strtolower(rtrim(trim((string) ($_POST['nombre_dominio'] ?? '')), '.'));
        $mailboxId = filter_input(INPUT_POST, 'id_buzon_entrada', FILTER_VALIDATE_INT);
        $clientId = filter_input(INPUT_POST, 'id_cliente', FILTER_VALIDATE_INT) ?: null;
        $selected = array_values(array_unique(array_filter(array_map(
            static fn($value): int => (int) $value,
            is_array($_POST['asuntos'] ?? null) ? $_POST['asuntos'] : []
        ))));
        $public = array_values(array_unique(array_filter(array_map(
            static fn($value): int => (int) $value,
            is_array($_POST['asuntos_publicos'] ?? null) ? $_POST['asuntos_publicos'] : []
        ))));

        if ($domain === '' || !filter_var($domain, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME)) {
            throw new InvalidArgumentException('Ingresa un dominio válido, por ejemplo: correo.tudominio.com.');
        }
        if (!$mailboxId) {
            throw new InvalidArgumentException('Selecciona un buzón de entrada.');
        }

        $mailbox = $pdo->prepare(
            'SELECT id, plataforma, nombre_proveedor, imap_host
             FROM configuraciones_imap WHERE id = ? AND id_admin = ? LIMIT 1'
        );
        $mailbox->execute([$mailboxId, $id_admin_actual]);
        $mailboxData = $mailbox->fetch(PDO::FETCH_ASSOC);
        if (!$mailboxData) {
            throw new RuntimeException('El buzón seleccionado no existe o no te pertenece.');
        }
        if (ImapProviderCatalog::isMicrosoftProvider(
            (string) ($mailboxData['plataforma'] ?? $mailboxData['nombre_proveedor'] ?? ''),
            (string) ($mailboxData['imap_host'] ?? '')
        )) {
            throw new RuntimeException('El buzón seleccionado usa Outlook u Office 365 y debe migrarse antes de asociarlo.');
        }

        if ($clientId !== null) {
            $client = $pdo->prepare(
                "SELECT COUNT(*) FROM usuarios
                 WHERE id = ? AND id_admin_propietario = ?
                   AND id_rol IN (SELECT id FROM roles WHERE nombre_rol IN ('Revendedor', 'Cliente Final'))"
            );
            $client->execute([$clientId, $id_admin_actual]);
            if ((int) $client->fetchColumn() !== 1) {
                throw new RuntimeException('El cliente seleccionado no es válido.');
            }
        }

        $allowedSubjectIds = [];
        $allowed = $pdo->prepare(
            'SELECT id FROM asuntos
             WHERE id_admin_propietario = ? OR id_propietario_admin = ?
                OR id_admin_propietario = 1 OR id_propietario_admin = 1
                OR id_admin_propietario IS NULL OR id_propietario_admin IS NULL'
        );
        $allowed->execute([$id_admin_actual, $id_admin_actual]);
        $allowedSubjectIds = array_map('intval', $allowed->fetchAll(PDO::FETCH_COLUMN));
        $selected = array_values(array_intersect($selected, $allowedSubjectIds));
        $public = array_values(array_intersect($public, $selected));

        if ($id !== null) {
            $ownerCheck = $pdo->prepare('SELECT COUNT(*) FROM dominios WHERE id = ? AND id_admin_propietario = ?');
            $ownerCheck->execute([$id, $id_admin_actual]);
            if ((int) $ownerCheck->fetchColumn() !== 1) {
                throw new RuntimeException('El dominio no existe o no te pertenece.');
            }
        } else {
            $limitStmt = $pdo->prepare(
                "SELECT p.limite_dominios FROM suscripciones s
                 JOIN planes p ON p.id = s.id_plan
                 WHERE s.id_admin = ? AND s.estado IN ('activa','prueba')
                 ORDER BY s.fecha_fin DESC, s.id DESC LIMIT 1"
            );
            $limitStmt->execute([$id_admin_actual]);
            $limitValue = $limitStmt->fetchColumn();
            if ($limitValue !== false && $limitValue !== null) {
                $countStmt = $pdo->prepare('SELECT COUNT(*) FROM dominios WHERE id_admin_propietario = ?');
                $countStmt->execute([$id_admin_actual]);
                if ((int) $countStmt->fetchColumn() >= (int) $limitValue) {
                    throw new RuntimeException('Alcanzaste el límite de dominios permitido por tu plan.');
                }
            }
        }

        $duplicateSql = 'SELECT COUNT(*) FROM dominios WHERE nombre_dominio = ? AND id_admin_propietario = ?';
        $duplicateParams = [$domain, $id_admin_actual];
        if ($id !== null) {
            $duplicateSql .= ' AND id <> ?';
            $duplicateParams[] = $id;
        }
        $duplicate = $pdo->prepare($duplicateSql);
        $duplicate->execute($duplicateParams);
        if ((int) $duplicate->fetchColumn() > 0) {
            throw new RuntimeException('Ya existe un dominio con ese nombre.');
        }

        $pdo->beginTransaction();
        if ($id !== null) {
            $stmt = $pdo->prepare(
                'UPDATE dominios SET nombre_dominio = ?, id_buzon_entrada = ?, id_cliente = ?
                 WHERE id = ? AND id_admin_propietario = ?'
            );
            $stmt->execute([$domain, $mailboxId, $clientId, $id, $id_admin_actual]);
            $domainId = $id;
            $message = 'Dominio actualizado correctamente.';
        } else {
            $stmt = $pdo->prepare(
                'INSERT INTO dominios
                 (nombre_dominio, id_buzon_entrada, id_cliente, id_admin_propietario, fecha_creacion)
                 VALUES (?, ?, ?, ?, NOW())'
            );
            $stmt->execute([$domain, $mailboxId, $clientId, $id_admin_actual]);
            $domainId = (int) $pdo->lastInsertId();
            $message = 'Dominio creado correctamente.';
        }

        $pdo->prepare('DELETE FROM dominio_asunto WHERE id_dominio = ?')->execute([$domainId]);
        if ($selected) {
            $insert = $pdo->prepare(
                'INSERT INTO dominio_asunto (id_dominio, id_asunto, es_publico) VALUES (?, ?, ?)'
            );
            foreach ($selected as $subjectId) {
                $insert->execute([$domainId, $subjectId, in_array($subjectId, $public, true) ? 1 : 0]);
            }
        }
        $pdo->commit();
        Security::json(['success' => true, 'message' => $message]);
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        error_log('Error gestionando dominio: ' . $e->getMessage());
        Security::json(['success' => false, 'message' => ($e instanceof InvalidArgumentException || $e instanceof RuntimeException) ? $e->getMessage() : 'No se pudo guardar el dominio.'], 422);
    }
}

ob_start();
$titulo_pagina = 'Gestionar Dominios';
require_once 'init.php';
restringir_modulo_superadmin('Dominios');

$rol_actual = $_SESSION['admin']['rol'] ?? '';
$id_usuario_logueado = (int) ($_SESSION['admin']['uid'] ?? 0);

if (!tiene_permiso('gestionar_propios_dominios')) {
    header("Location: index.php?status=error&msg=" . urlencode("No tienes permiso para ver esta página."));
    exit;
}

$flash = ''; $flash_status = '';
if (isset($_GET['status']) && isset($_GET['msg'])) { $flash = urldecode($_GET['msg']); $flash_status = $_GET['status']; }

$limite_dominios = 'ilimitado'; $dominios_actuales = 0; $limite_alcanzado = false;
if (in_array($rol_actual, ['Admin', 'Ayudante de Superadmin'], true)) {
    $stmt_plan = $pdo->prepare("SELECT p.limite_dominios FROM suscripciones s JOIN planes p ON s.id_plan = p.id WHERE s.id_admin = ? AND s.estado IN ('activa', 'prueba')");
    $stmt_plan->execute([$id_usuario_logueado]);
    $limites = $stmt_plan->fetch(PDO::FETCH_ASSOC);
    if ($limites && $limites['limite_dominios'] !== null) { $limite_dominios = (int) $limites['limite_dominios']; }
}

$stmt_count = $pdo->prepare("SELECT COUNT(*) FROM dominios WHERE id_admin_propietario = ?");
$stmt_count->execute([$id_usuario_logueado]);
$dominios_actuales = $stmt_count->fetchColumn();
if (is_numeric($limite_dominios) && $dominios_actuales >= $limite_dominios) { $limite_alcanzado = true; }

$sql_dominios = "SELECT d.id, d.nombre_dominio, d.fecha_creacion, ci.imap_usuario AS nombre_buzon, u_cliente.nombre_usuario AS nombre_cliente FROM dominios d LEFT JOIN configuraciones_imap ci ON d.id_buzon_entrada = ci.id LEFT JOIN usuarios u_cliente ON d.id_cliente = u_cliente.id WHERE d.id_admin_propietario = ? ORDER BY d.fecha_creacion DESC";
$stmt_dominios = $pdo->prepare($sql_dominios);
$stmt_dominios->execute([$id_usuario_logueado]);
$dominios = $stmt_dominios->fetchAll(PDO::FETCH_ASSOC);

$stmt_buzones = $pdo->prepare("SELECT id, imap_usuario, plataforma, nombre_proveedor, imap_host FROM configuraciones_imap WHERE id_admin = ? ORDER BY imap_usuario");
$stmt_buzones->execute([$id_usuario_logueado]);
$buzones_disponibles = array_values(array_filter(
    $stmt_buzones->fetchAll(PDO::FETCH_ASSOC),
    static fn(array $buzon): bool => !ImapProviderCatalog::isMicrosoftProvider(
        (string)($buzon['plataforma'] ?? $buzon['nombre_proveedor'] ?? ''),
        (string)($buzon['imap_host'] ?? '')
    )
));

$stmt_clientes = $pdo->prepare("SELECT id, nombre_usuario FROM usuarios WHERE id_rol IN (SELECT id FROM roles WHERE nombre_rol IN ('Revendedor', 'Cliente Final')) AND id_admin_propietario = ?");
$stmt_clientes->execute([$id_usuario_logueado]);
$clientes_disponibles = $stmt_clientes->fetchAll(PDO::FETCH_ASSOC);

$stmt_asuntos_disponibles = $pdo->prepare("SELECT a.id, a.nombre, p.nombre AS plataforma_nombre
    FROM asuntos a JOIN plataformas p ON p.id = a.id_plataforma
    WHERE a.id_admin_propietario = ? OR a.id_propietario_admin = ?
       OR a.id_admin_propietario = 1 OR a.id_propietario_admin = 1
       OR a.id_admin_propietario IS NULL OR a.id_propietario_admin IS NULL
    ORDER BY p.nombre, a.nombre");
$stmt_asuntos_disponibles->execute([$id_usuario_logueado, $id_usuario_logueado]);
$asuntos_disponibles = $stmt_asuntos_disponibles->fetchAll(PDO::FETCH_ASSOC);
$asuntos_por_plataforma = [];
foreach ($asuntos_disponibles as $asuntoDisponible) {
    $plataformaAsunto = trim((string) ($asuntoDisponible['plataforma_nombre'] ?? 'Sin plataforma')) ?: 'Sin plataforma';
    $asuntos_por_plataforma[$plataformaAsunto][] = $asuntoDisponible;
}

$domainsWithClient = count(array_filter($dominios, static fn(array $row): bool => !empty($row['nombre_cliente'])));
$availableMailboxCount = count($buzones_disponibles);
$availableClientCount = count($clientes_disponibles);

$platformsForSubjectRequest = $pdo->query(
    'SELECT id, nombre FROM plataformas ORDER BY nombre'
)->fetchAll(PDO::FETCH_ASSOC);

$superadminWhatsapp = '';
try {
    $superadminStmt = $pdo->query(
        "SELECT u.telefono
         FROM usuarios u
         JOIN roles r ON r.id = u.id_rol
         WHERE r.nombre_rol = 'Superadmin'
           AND TRIM(COALESCE(u.telefono, '')) <> ''
         ORDER BY u.id ASC
         LIMIT 1"
    );
    $superadminWhatsapp = preg_replace(
        '/\D+/',
        '',
        (string) ($superadminStmt->fetchColumn() ?: '')
    );
} catch (Throwable $e) {
    error_log('No se pudo cargar el WhatsApp del Superadmin: ' . $e->getMessage());
}
$adminRequestName = trim((string) ($_SESSION['admin']['nombre_usuario'] ?? 'Administrador'));
$adminRequestEmail = trim((string) ($_SESSION['admin']['correo'] ?? ''));

require_once 'admin_header.php';
?>
<div class="af-page">
    <header class="af-heading">
        <div class="af-heading-main"><span class="af-heading-icon"><i class="fas fa-at"></i></span><div><p class="af-eyebrow">Privacidad y enrutamiento</p><h1>Dominios</h1><p>Relaciona cada dominio con su buzón, cliente y asuntos permitidos. Tú decides qué asuntos se muestran públicamente y cuáles requieren acceso privado.</p></div></div>
        <div class="af-heading-actions"><button type="button" id="requestNewSubject" class="af-btn af-btn-success"><i class="fab fa-whatsapp"></i> Solicitar nuevo asunto</button><button type="button" id="openDomainModal" class="af-btn af-btn-primary" <?= $limite_alcanzado ? 'disabled' : '' ?>><i class="fas fa-plus"></i> Nuevo dominio</button></div>
    </header>

    <?php if ($limite_alcanzado): ?><div class="af-alert af-alert-warning"><i class="fas fa-triangle-exclamation"></i><div>Alcanzaste el límite de <strong><?= number_format((int) $dominios_actuales) ?>/<?= number_format((int) $limite_dominios) ?></strong> dominios de tu plan.</div></div><?php endif; ?>
    <?php if ($availableMailboxCount === 0): ?><div class="af-alert af-alert-danger"><i class="fas fa-inbox"></i><div>Necesitas al menos un buzón compatible antes de registrar un dominio.</div></div><?php endif; ?>

    <section class="af-stats">
        <article class="af-stat"><span class="af-stat-icon"><i class="fas fa-globe"></i></span><div><p class="af-stat-label">Dominios</p><p class="af-stat-value"><?= number_format((int) $dominios_actuales) ?></p><div class="af-stat-note">Límite: <?= is_numeric($limite_dominios) ? number_format((int) $limite_dominios) : 'Ilimitado' ?></div></div></article>
        <article class="af-stat"><span class="af-stat-icon"><i class="fas fa-inbox"></i></span><div><p class="af-stat-label">Buzones disponibles</p><p class="af-stat-value"><?= number_format($availableMailboxCount) ?></p><div class="af-stat-note">Microsoft excluido</div></div></article>
        <article class="af-stat"><span class="af-stat-icon"><i class="fas fa-user-check"></i></span><div><p class="af-stat-label">Con cliente</p><p class="af-stat-value"><?= number_format($domainsWithClient) ?></p><div class="af-stat-note">Asignación directa</div></div></article>
        <article class="af-stat"><span class="af-stat-icon"><i class="fas fa-tags"></i></span><div><p class="af-stat-label">Asuntos disponibles</p><p class="af-stat-value"><?= number_format(count($asuntos_disponibles)) ?></p><div class="af-stat-note">Públicos o privados</div></div></article>
    </section>

    <section class="af-panel">
        <div class="af-panel-head"><div class="af-panel-title"><span class="af-panel-title-icon"><i class="fas fa-list"></i></span><div><h2>Registros de dominios</h2><p>Filtra por buzón o cliente y administra la privacidad de cada dominio.</p></div></div></div>
        <div class="af-toolbar">
            <div class="af-field"><label class="af-label" for="domainSearch"><i class="fas fa-search"></i> Buscar</label><input id="domainSearch" type="search" class="af-control" placeholder="Dominio, buzón o cliente"></div>
            <div class="af-field"><label class="af-label" for="domainMailboxFilter"><i class="fas fa-inbox"></i> Buzón</label><select id="domainMailboxFilter" class="af-control"><option value="">Todos</option><?php foreach ($buzones_disponibles as $mailbox): ?><option value="<?= htmlspecialchars((string) $mailbox['imap_usuario']) ?>"><?= htmlspecialchars((string) $mailbox['imap_usuario']) ?></option><?php endforeach; ?></select></div>
            <div class="af-field"><label class="af-label" for="domainClientFilter"><i class="fas fa-user"></i> Cliente</label><select id="domainClientFilter" class="af-control"><option value="">Todos</option><option value="none">Sin cliente</option><?php foreach ($clientes_disponibles as $client): ?><option value="<?= htmlspecialchars((string) $client['nombre_usuario']) ?>"><?= htmlspecialchars((string) $client['nombre_usuario']) ?></option><?php endforeach; ?></select></div>
            <div class="af-field"><label class="af-label" for="domainPerPage"><i class="fas fa-list-ol"></i> Mostrar</label><select id="domainPerPage" class="af-control"><option value="100">100 registros</option><option value="200">200 registros</option><option value="400">400 registros</option><option value="all">Todos</option></select></div>
            <div class="af-toolbar-actions"><button type="button" id="clearDomainFilters" class="af-btn af-btn-secondary"><i class="fas fa-eraser"></i> Limpiar</button></div>
        </div>
        <div class="af-list-meta"><span><?= number_format(count($dominios)) ?> dominios registrados</span><span id="domainPageSummary"></span></div>
        <div class="af-table-wrap"><table id="domainTable" class="af-table"><thead><tr><th>Dominio</th><th>Buzón</th><th>Cliente</th><th>Creación</th><th>Acciones</th></tr></thead><tbody>
        <?php foreach ($dominios as $domain): $clientKey = !empty($domain['nombre_cliente']) ? (string) $domain['nombre_cliente'] : 'none'; ?>
            <tr data-af-row data-mailbox="<?= htmlspecialchars((string) ($domain['nombre_buzon'] ?? ''), ENT_QUOTES, 'UTF-8') ?>" data-client="<?= htmlspecialchars($clientKey, ENT_QUOTES, 'UTF-8') ?>" data-search="<?= htmlspecialchars(($domain['nombre_dominio'] ?? '') . ' ' . ($domain['nombre_buzon'] ?? '') . ' ' . ($domain['nombre_cliente'] ?? ''), ENT_QUOTES, 'UTF-8') ?>">
                <td><span class="af-row-title"><?= htmlspecialchars((string) $domain['nombre_dominio']) ?></span><span class="af-row-sub">Correo corporativo gestionado</span></td>
                <td><?= htmlspecialchars((string) ($domain['nombre_buzon'] ?? 'Sin buzón')) ?></td>
                <td><?php if (!empty($domain['nombre_cliente'])): ?><span class="af-badge af-badge-success"><i class="fas fa-user"></i><?= htmlspecialchars((string) $domain['nombre_cliente']) ?></span><?php else: ?><span class="af-badge af-badge-neutral">Sin asignar</span><?php endif; ?></td>
                <td><?= !empty($domain['fecha_creacion']) ? date('d/m/Y', strtotime((string) $domain['fecha_creacion'])) : '—' ?></td>
                <td><div class="af-actions"><button type="button" class="af-btn af-btn-icon af-action-edit js-edit-domain" data-id="<?= (int) $domain['id'] ?>" title="Editar"><i class="fas fa-pen"></i></button><button type="button" class="af-btn af-btn-icon af-action-delete js-delete-domain" data-id="<?= (int) $domain['id'] ?>" data-name="<?= htmlspecialchars((string) $domain['nombre_dominio'], ENT_QUOTES, 'UTF-8') ?>" title="Eliminar"><i class="fas fa-trash"></i></button></div></td>
            </tr>
        <?php endforeach; ?>
        </tbody></table><div id="domainEmpty" class="af-empty" hidden><i class="fas fa-globe"></i><strong>No se encontraron dominios</strong><div>Modifica los filtros o registra un dominio nuevo.</div></div></div>
        <div class="af-pagination-bar"><span class="af-pagination-summary">Los asuntos públicos pueden consultarse sin login; los privados respetan el acceso configurado.</span><div id="domainPagination" class="af-pagination"></div></div>
    </section>
</div>

<div id="domainModal" class="af-modal-backdrop" aria-hidden="true">
    <section class="af-modal af-modal-lg" role="dialog" aria-modal="true" aria-labelledby="domainModalTitle">
        <header class="af-modal-head"><div class="af-modal-title"><span class="af-modal-icon"><i class="fas fa-at"></i></span><div><h2 id="domainModalTitle">Nuevo dominio</h2><p id="domainModalDescription">Configura el buzón y la privacidad de los asuntos.</p></div></div><button type="button" class="af-modal-close" data-af-close><i class="fas fa-xmark"></i></button></header>
        <form id="domainForm">
            <?= Security::csrfField() ?><input type="hidden" name="action" value="guardar_dominio"><input type="hidden" name="id" id="domainId">
            <div class="af-modal-body">
                <div class="af-guide"><i class="fas fa-shield-halved"></i><div>Selecciona únicamente los asuntos que utilizará este dominio. Marca “Público” solo cuando cualquier persona pueda consultar ese mensaje sin iniciar sesión.</div></div>
                <div class="af-form-grid">
                    <div class="full"><label class="af-label" for="domainName"><i class="fas fa-globe"></i> Dominio *</label><input id="domainName" name="nombre_dominio" class="af-control" required placeholder="correo.tudominio.com"><span class="af-help">Escribe solo el dominio, sin “https://”, rutas ni direcciones completas.</span></div>
                    <div><label class="af-label" for="domainMailbox"><i class="fas fa-inbox"></i> Buzón de entrada *</label><select id="domainMailbox" name="id_buzon_entrada" class="af-control" required><option value="">Seleccionar buzón</option><?php foreach ($buzones_disponibles as $mailbox): ?><option value="<?= (int) $mailbox['id'] ?>"><?= htmlspecialchars((string) $mailbox['imap_usuario']) ?></option><?php endforeach; ?></select><span class="af-help">Buzón que recibe los mensajes de este dominio.</span></div>
                    <div><label class="af-label" for="domainClient"><i class="fas fa-user"></i> Cliente asignado</label><select id="domainClient" name="id_cliente" class="af-control"><option value="">Sin cliente</option><?php foreach ($clientes_disponibles as $client): ?><option value="<?= (int) $client['id'] ?>"><?= htmlspecialchars((string) $client['nombre_usuario']) ?></option><?php endforeach; ?></select><span class="af-help">Opcional. Permite relacionar el dominio con un cliente específico.</span></div>
                </div>
                <div class="af-form-section af-domain-subjects">
                    <div class="af-domain-subjects-head"><div><h3 class="af-form-section-title mb-0">Asuntos permitidos</h3><p class="af-help mt-1">Activa el asunto y elige su privacidad con el selector rojo o verde.</p></div><label class="af-badge af-badge-neutral"><input type="checkbox" id="selectAllSubjects"> Seleccionar todos</label></div>
                    <div class="af-subject-groups" id="domainSubjects">
                    <?php foreach ($asuntos_por_plataforma as $platformName => $platformSubjects): ?>
                        <section class="af-subject-group">
                            <div class="af-subject-group-title"><span><i class="fas fa-tv mr-2"></i><?= htmlspecialchars($platformName) ?></span><span><?= number_format(count($platformSubjects)) ?> asunto(s)</span></div>
                            <div class="af-subject-group-grid">
                            <?php foreach ($platformSubjects as $subject): ?>
                                <div class="af-check-item af-subject-compact" data-subject-item>
                                    <label class="af-check-main">
                                        <input type="checkbox" class="subject-check" name="asuntos[]" value="<?= (int) $subject['id'] ?>">
                                        <span class="af-subject-name"><strong><?= htmlspecialchars((string) $subject['nombre']) ?></strong></span>
                                    </label>
                                    <label class="af-visibility-switch is-private is-disabled" data-visibility-switch title="Rojo: privado. Verde: público.">
                                        <input type="checkbox" class="public-check" name="asuntos_publicos[]" value="<?= (int) $subject['id'] ?>" disabled>
                                        <span class="af-visibility-switch__status">
                                            <span class="af-visibility-switch__dot"></span>
                                            <i class="fas fa-lock"></i>
                                            <span class="af-visibility-switch__label">Privado</span>
                                        </span>
                                    </label>
                                </div>
                            <?php endforeach; ?>
                            </div>
                        </section>
                    <?php endforeach; ?>
                    </div>
                </div>
            </div>
            <footer class="af-modal-footer"><button type="button" class="af-btn af-btn-secondary" data-af-close>Cancelar</button><button type="submit" class="af-btn af-btn-primary"><i class="fas fa-floppy-disk"></i> Guardar dominio</button></footer>
        </form>
    </section>
</div>


<style>
.af-request-popup {
    padding: 0 0 20px !important;
    border-radius: 20px !important;
    overflow: hidden;
}
.af-request-popup .swal2-title {
    margin: 0 !important;
    padding: 22px 24px 15px !important;
    border-bottom: 1px solid #e8edf4;
    color: #172033;
    font-size: 20px !important;
    text-align: left;
}
.af-request-title {
    display: flex;
    align-items: center;
    gap: 10px;
}
.af-request-title i { color: #6758e8; }
.af-request-html { margin: 0 !important; padding: 18px 24px 4px !important; }
.af-request-form { display: grid; gap: 15px; text-align: left; }
.af-request-guide {
    display: grid;
    grid-template-columns: 32px 1fr;
    gap: 10px;
    padding: 12px 14px;
    border: 1px solid #dfe4ff;
    border-radius: 12px;
    background: #f6f7ff;
    color: #3d4563;
}
.af-request-guide > i {
    display: grid;
    width: 30px;
    height: 30px;
    place-items: center;
    border-radius: 9px;
    background: #6758e8;
    color: #fff;
}
.af-request-guide strong { display: block; margin-bottom: 3px; color: #252b45; font-size: 13px; }
.af-request-guide p { margin: 0; font-size: 12px; line-height: 1.5; }
.af-request-field label {
    display: flex;
    align-items: center;
    gap: 7px;
    margin-bottom: 6px;
    color: #263247;
    font-size: 13px;
    font-weight: 800;
}
.af-request-field label i { width: 16px; color: #6758e8; text-align: center; }
.af-request-field label span { color: #dc2626; }
.af-request-field label em {
    margin-left: auto;
    color: #8792a5;
    font-size: 10px;
    font-style: normal;
    font-weight: 700;
    text-transform: uppercase;
}
.af-request-control {
    width: 100%;
    min-height: 44px;
    padding: 10px 12px;
    border: 1px solid #d7deea;
    border-radius: 10px;
    background: #fff;
    color: #172033;
    font: inherit;
    outline: none;
}
.af-request-control:focus {
    border-color: #6758e8;
    box-shadow: 0 0 0 3px rgba(103, 88, 232, .12);
}
.af-request-textarea { min-height: 92px; resize: vertical; }
.af-request-field small { display: block; margin-top: 5px; color: #718096; font-size: 11px; line-height: 1.4; }
.af-request-reminder {
    display: grid;
    grid-template-columns: 32px 1fr;
    gap: 10px;
    padding: 12px 14px;
    border: 1px solid #f4c97a;
    border-radius: 12px;
    background: #fff8e8;
    color: #6f4b08;
}
.af-request-reminder > i {
    display: grid;
    width: 30px;
    height: 30px;
    place-items: center;
    border-radius: 9px;
    background: #f59e0b;
    color: #fff;
}
.af-request-reminder strong { display: block; margin-bottom: 3px; color: #5b3d06; font-size: 13px; }
.af-request-reminder p { margin: 0; font-size: 12px; line-height: 1.5; }
.af-request-popup .swal2-actions { width: calc(100% - 48px); margin: 17px 24px 0 !important; gap: 9px; justify-content: flex-end; }
.af-request-confirm,
.af-request-cancel {
    min-height: 42px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    padding: 9px 15px;
    border: 0;
    border-radius: 10px;
    font-size: 13px;
    font-weight: 800;
    cursor: pointer;
}
.af-request-confirm { background: #6758e8; color: #fff; }
.af-request-confirm:hover { background: #5849d8; }
.af-request-cancel { background: #eef1f5; color: #475569; }
.af-request-cancel:hover { background: #e2e7ee; }
@media (max-width: 640px) {
    .af-request-popup .swal2-title { padding: 18px 18px 13px !important; font-size: 18px !important; }
    .af-request-html { padding: 15px 18px 2px !important; }
    .af-request-popup .swal2-actions { width: calc(100% - 36px); margin: 15px 18px 0 !important; }
    .af-request-confirm, .af-request-cancel { flex: 1; }
}
</style>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const list = new AfenixAdmin.UnifiedList({table:'#domainTable',search:'#domainSearch',perPage:'#domainPerPage',filters:[{selector:'#domainMailboxFilter',data:'mailbox'},{selector:'#domainClientFilter',data:'client'}],summary:'#domainPageSummary',pagination:'#domainPagination',empty:'#domainEmpty'});
    document.getElementById('clearDomainFilters').addEventListener('click',()=>{['domainSearch','domainMailboxFilter','domainClientFilter'].forEach(id=>document.getElementById(id).value='');document.getElementById('domainPerPage').value='100';list.currentPage=1;list.render();});
    const modal = new AfenixAdmin.ModalController('#domainModal');
    const form = document.getElementById('domainForm');
    const csrf = <?= json_encode(Security::csrfToken()) ?>;
    const subjectChecks = [...document.querySelectorAll('.subject-check')];
    const publicChecks = [...document.querySelectorAll('.public-check')];
    const superadminWhatsapp = <?= json_encode($superadminWhatsapp, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>;
    const adminRequestName = <?= json_encode($adminRequestName, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
    const adminRequestEmail = <?= json_encode($adminRequestEmail, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
    const requestPlatforms = <?= json_encode(array_map(
        static fn(array $platform): array => [
            'id' => (int) $platform['id'],
            'name' => (string) $platform['nombre'],
        ],
        $platformsForSubjectRequest
    ), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;

    const escapePreviewHtml = (value) => String(value ?? '')
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');

    const formatWhatsAppPreview = (message) => escapePreviewHtml(message)
        .replace(/\*([^*\n]+)\*/g, '<strong>$1</strong>')
        .replace(/\n/g, '<br>');

    const copySubjectRequest = async (message) => {
        if (navigator.clipboard?.writeText) {
            await navigator.clipboard.writeText(message);
            return;
        }
        const area = document.createElement('textarea');
        area.value = message;
        area.style.position = 'fixed';
        area.style.opacity = '0';
        document.body.appendChild(area);
        area.select();
        document.execCommand('copy');
        area.remove();
    };

    document.getElementById('requestNewSubject').addEventListener('click', async () => {
        const platformOptions = requestPlatforms.map((platform) =>
            `<option value="${escapePreviewHtml(platform.name)}">${escapePreviewHtml(platform.name)}</option>`
        ).join('');

        const request = await Swal.fire({
            title: '<span class="af-request-title"><i class="fas fa-envelope-open-text"></i> Solicitar nuevo asunto</span>',
            html: `<div class="af-request-form">
                <div class="af-request-guide">
                    <i class="fas fa-circle-info"></i>
                    <div>
                        <strong>Solo estás solicitando el registro.</strong>
                        <p>Cuando el Superadmin agregue el asunto, vuelve a <b>Dominios</b>, edita el dominio correspondiente, selecciónalo y define si será <b>Público</b> o <b>Privado</b>.</p>
                    </div>
                </div>
                <div class="af-request-field">
                    <label for="subjectRequestPlatform"><i class="fas fa-layer-group"></i> Plataforma <span>*</span></label>
                    <select id="subjectRequestPlatform" class="af-request-control">
                        <option value="">Seleccionar plataforma</option>${platformOptions}
                    </select>
                    <small>Indica a qué plataforma pertenece el correo que deseas detectar.</small>
                </div>
                <div class="af-request-field">
                    <label for="subjectRequestName"><i class="fas fa-tag"></i> Nombre del asunto <span>*</span></label>
                    <input id="subjectRequestName" class="af-request-control" maxlength="180" placeholder="Ejemplo: Código para actualizar el hogar">
                    <small>Escribe una descripción corta y reconocible.</small>
                </div>
                <div class="af-request-field">
                    <label for="subjectRequestDetail"><i class="fas fa-align-left"></i> Detalle o ejemplo <em>Opcional</em></label>
                    <textarea id="subjectRequestDetail" class="af-request-control af-request-textarea" maxlength="700" placeholder="Ejemplo: el correo contiene la frase “actualiza tu hogar” y un código temporal."></textarea>
                    <small>Agrega palabras frecuentes o explica qué información debe encontrarse.</small>
                </div>
                <div class="af-request-reminder" role="note" aria-label="Recordatorio después del registro">
                    <i class="fas fa-triangle-exclamation"></i>
                    <div>
                        <strong>Recuerda el paso final</strong>
                        <p>Cuando el Superadmin registre el nuevo asunto, deberás volver a <b>Dominios</b>, editar cada dominio donde quieras utilizarlo, seleccionarlo y definirlo como <b>Público</b> o <b>Privado</b>.</p>
                    </div>
                </div>
            </div>`,
            customClass: {
                popup: 'af-request-popup',
                htmlContainer: 'af-request-html',
                confirmButton: 'af-request-confirm',
                cancelButton: 'af-request-cancel'
            },
            buttonsStyling: false,
            showCancelButton: true,
            confirmButtonText: '<i class="fas fa-wand-magic-sparkles"></i> Preparar solicitud',
            cancelButtonText: 'Cancelar',
            width: 570,
            focusConfirm: false,
            didOpen: () => document.getElementById('subjectRequestPlatform')?.focus(),
            preConfirm: () => {
                const platform = document.getElementById('subjectRequestPlatform').value.trim();
                const subject = document.getElementById('subjectRequestName').value.trim();
                const detail = document.getElementById('subjectRequestDetail').value.trim();

                if (!platform) {
                    Swal.showValidationMessage('Selecciona la plataforma del nuevo asunto.');
                    return false;
                }
                if (!subject) {
                    Swal.showValidationMessage('Escribe el nombre del asunto que necesitas.');
                    return false;
                }

                return {platform, subject, detail};
            }
        });

        if (!request.isConfirmed || !request.value) return;

        const data = request.value;
        const message = `📝 *SOLICITUD DE NUEVO ASUNTO*\n\n`
            + `Hola, solicito registrar un nuevo asunto para utilizarlo en mis dominios.\n\n`
            + `👤 *Administrador:* ${adminRequestName || 'Administrador'}\n`
            + (adminRequestEmail ? `📧 *Correo:* ${adminRequestEmail}\n` : '')
            + `📺 *Plataforma:* ${data.platform}\n`
            + `🏷️ *Asunto solicitado:* ${data.subject}\n`
            + (data.detail ? `🧩 *Detalle:* ${data.detail}\n` : '')
            + `\n✅ *Siguiente paso:* cuando el asunto sea registrado, lo asociaré desde el módulo Dominios y definiré allí si será público o privado.\n\n`
            + `Gracias por la revisión y el apoyo.`;

        const preview = await Swal.fire({
            title: 'Solicitud lista para enviar',
            html: `<div style="text-align:left">
                <p style="margin:0 0 12px;color:#64748b;font-size:13px">
                    Revisa el mensaje. No se asociará ningún dominio durante esta solicitud.
                </p>
                ${superadminWhatsapp === '' ? '<div style="margin-bottom:12px;padding:10px 12px;border-radius:10px;background:#fff7e3;color:#9a6700">El Superadmin no tiene un teléfono registrado. Puedes copiar la solicitud.</div>' : ''}
                <div style="max-height:340px;overflow:auto;background:#f8fafc;border:1px solid #e2e8f0;border-radius:12px;padding:16px;line-height:1.65;color:#1e293b">
                    ${formatWhatsAppPreview(message)}
                </div>
            </div>`,
            icon: 'info',
            showCancelButton: true,
            showDenyButton: true,
            showConfirmButton: superadminWhatsapp !== '',
            confirmButtonText: '<i class="fab fa-whatsapp"></i> Enviar al Superadmin',
            denyButtonText: '<i class="fas fa-copy"></i> Copiar solicitud',
            cancelButtonText: 'Cancelar',
            confirmButtonColor: '#16a34a',
            denyButtonColor: '#475569',
            reverseButtons: true,
            width: 590
        });

        if (preview.isConfirmed && superadminWhatsapp !== '') {
            window.open(
                `https://wa.me/${superadminWhatsapp}?text=${encodeURIComponent(message)}`,
                '_blank',
                'noopener'
            );
        } else if (preview.isDenied) {
            try {
                await copySubjectRequest(message);
                await Swal.fire({
                    icon: 'success',
                    title: 'Solicitud copiada',
                    text: 'El mensaje está listo para pegarse en WhatsApp.',
                    timer: 1800,
                    showConfirmButton: false
                });
            } catch (error) {
                await Swal.fire(
                    'No se pudo copiar',
                    'Selecciona el mensaje y cópialo manualmente.',
                    'error'
                );
            }
        }
    });
    const domainModalBody = document.querySelector('#domainModal .af-modal-body');
    const domainSubjectScroller = document.getElementById('domainSubjects');
    let visibilityScrollState = null;

    function rememberVisibilityScroll() {
        visibilityScrollState = {
            modal: domainModalBody ? domainModalBody.scrollTop : 0,
            subjects: domainSubjectScroller ? domainSubjectScroller.scrollTop : 0
        };
    }

    function restoreVisibilityScroll() {
        if (!visibilityScrollState) return;
        const state = visibilityScrollState;
        const restore = () => {
            if (domainModalBody) domainModalBody.scrollTop = state.modal;
            if (domainSubjectScroller) domainSubjectScroller.scrollTop = state.subjects;
        };
        restore();
        requestAnimationFrame(restore);
        window.setTimeout(restore, 40);
    }

    function updateVisibility(publicCheck) { const switchLabel=publicCheck.closest('[data-visibility-switch]'); if(!switchLabel)return; const enabled=!publicCheck.disabled; const isPublic=enabled&&publicCheck.checked; switchLabel.classList.toggle('is-disabled',!enabled); switchLabel.classList.toggle('is-public',isPublic); switchLabel.classList.toggle('is-private',!isPublic); switchLabel.setAttribute('aria-checked', isPublic ? 'true' : 'false'); switchLabel.setAttribute('aria-disabled', enabled ? 'false' : 'true'); const label=switchLabel.querySelector('.af-visibility-switch__label'); const icon=switchLabel.querySelector('i'); if(label)label.textContent=isPublic?'Público':'Privado'; if(icon)icon.className=isPublic?'fas fa-globe':'fas fa-lock'; }
    function syncPublic(check) { const publicCheck=check.closest('[data-subject-item]').querySelector('.public-check'); publicCheck.disabled=!check.checked; if(!check.checked)publicCheck.checked=false; updateVisibility(publicCheck); }
    subjectChecks.forEach(check=>check.addEventListener('change',()=>syncPublic(check)));
    publicChecks.forEach(check=>{
        const switchLabel = check.closest('[data-visibility-switch]');
        if (switchLabel) {
            switchLabel.setAttribute('role', 'switch');
            switchLabel.addEventListener('pointerdown', rememberVisibilityScroll, {passive:true});
            switchLabel.addEventListener('mousedown', rememberVisibilityScroll, {passive:true});
        }
        check.addEventListener('change',()=>{
            updateVisibility(check);
            restoreVisibilityScroll();
        });
    });
    publicChecks.forEach(updateVisibility);
    document.getElementById('selectAllSubjects').addEventListener('change',function(){subjectChecks.forEach(check=>{check.checked=this.checked;syncPublic(check);});});
    function resetForm(data=null,subjects=[]) { form.reset(); document.getElementById('domainId').value=''; subjectChecks.forEach(syncPublic); document.getElementById('domainModalTitle').textContent=data?'Editar dominio':'Nuevo dominio'; document.getElementById('domainModalDescription').textContent=data?'Actualiza la asignación o privacidad del dominio.':'Configura el buzón y la privacidad de los asuntos.'; if(!data)return; document.getElementById('domainId').value=data.id;document.getElementById('domainName').value=data.nombre_dominio||'';document.getElementById('domainMailbox').value=data.id_buzon_entrada||'';document.getElementById('domainClient').value=data.id_cliente||'';subjects.forEach(row=>{const check=document.querySelector(`.subject-check[value="${row.id_asunto}"]`);if(!check)return;check.checked=true;syncPublic(check);const pub=check.closest('[data-subject-item]').querySelector('.public-check');pub.checked=String(row.es_publico)==='1';updateVisibility(pub);}); }
    function resetDomainModalScroll() {
        requestAnimationFrame(() => {
            if (domainModalBody) domainModalBody.scrollTop = 0;
            if (domainSubjectScroller) domainSubjectScroller.scrollTop = 0;
        });
    }
    document.getElementById('openDomainModal').addEventListener('click',function(){resetForm();modal.open(this);resetDomainModalScroll();});
    document.getElementById('domainTable').addEventListener('click',async(event)=>{const edit=event.target.closest('.js-edit-domain');const del=event.target.closest('.js-delete-domain');if(edit){try{const result=await AfenixAdmin.request(`gestionar_dominios.php?fetch_data=${encodeURIComponent(edit.dataset.id)}`);resetForm(result.data,result.asuntos||[]);modal.open(edit);resetDomainModalScroll();}catch(e){Swal.fire('Error',e.message,'error');}}if(del){const confirm=await Swal.fire({title:'¿Eliminar dominio?',html:`Se eliminará <strong>${del.dataset.name}</strong>.`,text:'No podrá eliminarse si todavía tiene cuentas asociadas.',icon:'warning',showCancelButton:true,confirmButtonText:'Sí, eliminar',cancelButtonText:'Cancelar',confirmButtonColor:'#dc2626'});if(!confirm.isConfirmed)return;try{const body=new URLSearchParams({action:'delete_dominio',id:del.dataset.id,_csrf:csrf});const result=await AfenixAdmin.request('gestionar_dominios.php',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body});await Swal.fire('Eliminado',result.message,'success');location.reload();}catch(e){Swal.fire('Error',e.message,'error');}}});
    form.addEventListener('submit',async(event)=>{event.preventDefault();const submit=form.querySelector('[type=submit]');submit.disabled=true;try{const result=await AfenixAdmin.request('gestionar_dominios.php',{method:'POST',body:new FormData(form)});modal.clean();await Swal.fire('Guardado',result.message,'success');location.reload();}catch(e){Swal.fire('Error',e.message,'error');}finally{submit.disabled=false;}});
});
</script>
<?php require_once __DIR__ . '/admin_footer.php'; ob_end_flush(); ?>
