<?php
// admin/gestionar_asuntos.php - v4 visual PRO registros/modal estilo Plataforma/Asuntos, sin perder lógica
require_once __DIR__ . '/init.php';

function asunto_json_response(array $response): void {
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($response, JSON_UNESCAPED_UNICODE);
    exit;
}

function asunto_limpiar_aliases(string $raw): array {
    $out = [];
    $partes = preg_split('/[\r\n,]+/u', $raw) ?: [];

    foreach ($partes as $alias) {
        $alias = trim($alias);
        if ($alias === '') continue;

        $normalizado = preg_replace('/\s+/u', ' ', $alias) ?? $alias;
        $key = mb_strtolower($normalizado, 'UTF-8');
        $out[$key] = $normalizado;
    }

    return array_values($out);
}

function asunto_admin_id_actual(): int {
    return (int)($_SESSION['admin']['uid'] ?? $_SESSION['admin_info']['id'] ?? 0);
}

function asunto_admin_rol_actual(): string {
    return (string)($_SESSION['admin']['rol'] ?? $_SESSION['admin_info']['rol'] ?? '');
}

function asunto_es_superadmin(): bool {
    return asunto_admin_rol_actual() === 'Superadmin';
}

function asunto_owner_id(array $row): int {
    if (isset($row['id_admin_propietario']) && (int)$row['id_admin_propietario'] > 0) {
        return (int)$row['id_admin_propietario'];
    }
    if (isset($row['id_propietario_admin']) && (int)$row['id_propietario_admin'] > 0) {
        return (int)$row['id_propietario_admin'];
    }
    return 0;
}

function asunto_usuario_puede_editar(array $row): bool {
    if (asunto_es_superadmin()) return true;

    $uid = asunto_admin_id_actual();
    $owner = asunto_owner_id($row);

    return $owner === $uid || $owner === 1 || $owner === 0;
}

function asunto_verificar_permiso_registro(PDO $pdo, int $id): array {
    $stmt = $pdo->prepare('SELECT id, id_admin_propietario, id_propietario_admin FROM asuntos WHERE id = ? LIMIT 1');
    $stmt->execute([$id]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$row || !asunto_usuario_puede_editar($row)) {
        throw new Exception('No tienes permiso para modificar este asunto.');
    }

    return $row;
}

if (isset($_REQUEST['action']) || isset($_GET['fetch_data']) || isset($_GET['delete'])) {
    if (!tiene_permiso('gestionar_asuntos')) {
        asunto_json_response(['success' => false, 'message' => 'Acceso denegado.']);
    }

    try {
        if (isset($_GET['fetch_data'])) {
            $id = filter_input(INPUT_GET, 'fetch_data', FILTER_VALIDATE_INT);
            if (!$id) throw new Exception('No se recibió un asunto válido.');

            $stmt = $pdo->prepare("
                SELECT a.*, GROUP_CONCAT(al.nombre ORDER BY al.nombre SEPARATOR ', ') AS aliases
                FROM asuntos a
                LEFT JOIN asuntos_alias al ON al.id_asunto = a.id
                WHERE a.id = ?
                GROUP BY a.id
                LIMIT 1
            ");
            $stmt->execute([$id]);
            $data = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$data || !asunto_usuario_puede_editar($data)) {
                throw new Exception('No tienes permiso o el asunto no existe.');
            }

            asunto_json_response(['success' => true, 'data' => $data]);
        }

        $action = $_POST['action'] ?? $_GET['action'] ?? '';

        if ($action === 'guardar_asunto') {
            $id            = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
            $nombre        = trim($_POST['nombre'] ?? '');
            $id_plataforma = filter_input(INPUT_POST, 'id_plataforma', FILTER_VALIDATE_INT);
            $es_flexible   = isset($_POST['es_flexible']) ? 1 : 0;
            $aliasCadena   = trim($_POST['aliases'] ?? '');
            $aliases       = asunto_limpiar_aliases($aliasCadena);

            if ($nombre === '') throw new Exception('Ingresa el nombre del asunto que llega al correo.');
            if (!$id_plataforma) throw new Exception('Selecciona la plataforma del asunto.');

            if ($id) {
                asunto_verificar_permiso_registro($pdo, (int)$id);
            }

            $pdo->beginTransaction();

            if ($id) {
                $sql = 'UPDATE asuntos
                        SET nombre = ?, id_plataforma = ?, es_flexible = ?, modo_coincidencia = ?
                        WHERE id = ?';
                $params = [$nombre, $id_plataforma, $es_flexible, $es_flexible ? 'flexible' : 'exacto', $id];

                if (!asunto_es_superadmin()) {
                    $sql .= ' AND (id_admin_propietario = ? OR id_propietario_admin = ? OR id_admin_propietario = 1 OR id_propietario_admin = 1)';
                    $params[] = asunto_admin_id_actual();
                    $params[] = asunto_admin_id_actual();
                }

                $stmt = $pdo->prepare($sql);
                $stmt->execute($params);

                $asunto_id = (int)$id;
                $message = 'Asunto actualizado correctamente.';
            } else {
                $id_propietario = asunto_admin_id_actual();

                $stmt = $pdo->prepare('
                    INSERT INTO asuntos(nombre, id_plataforma, es_flexible, modo_coincidencia, visible_publico, id_propietario_admin, id_admin_propietario, fecha_creacion)
                    VALUES (?, ?, ?, ?, 0, ?, ?, NOW())
                ');
                $stmt->execute([$nombre, $id_plataforma, $es_flexible, $es_flexible ? 'flexible' : 'exacto', $id_propietario, $id_propietario]);

                $asunto_id = (int)$pdo->lastInsertId();
                $message = 'Asunto creado correctamente.';
            }

            $pdo->prepare('DELETE FROM asuntos_alias WHERE id_asunto = ?')->execute([$asunto_id]);

            if ($aliases) {
                $ins = $pdo->prepare('INSERT INTO asuntos_alias(id_asunto, nombre) VALUES (?, ?)');
                foreach ($aliases as $al) {
                    $ins->execute([$asunto_id, $al]);
                }
            }

            $pdo->commit();
            asunto_json_response(['success' => true, 'message' => $message]);
        }

        if ($action === 'delete_asunto' || isset($_GET['delete'])) {
            $id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT) ?: filter_input(INPUT_GET, 'delete', FILTER_VALIDATE_INT);
            if (!$id) throw new Exception('No se recibió un asunto válido.');

            asunto_verificar_permiso_registro($pdo, (int)$id);

            $bloqueos = [
                'dominio_asunto' => 'dominios',
                'asociacion_asunto' => 'permisos de asociaciones',
                'asociaciones' => 'asociaciones de clientes',
            ];

            foreach ($bloqueos as $tabla => $nombre) {
                try {
                    $stmt_check = $pdo->prepare("SELECT COUNT(*) FROM {$tabla} WHERE id_asunto = ?");
                    $stmt_check->execute([$id]);
                    if ((int)$stmt_check->fetchColumn() > 0) {
                        throw new Exception("No se puede eliminar porque este asunto está asociado a {$nombre}. Primero quita esa relación.");
                    }
                } catch (PDOException $e) {
                    // Si la tabla no existe en alguna instalación, no se detiene el módulo.
                }
            }

            $pdo->beginTransaction();
            $pdo->prepare('DELETE FROM asuntos_alias WHERE id_asunto = ?')->execute([$id]);
            $pdo->prepare('DELETE FROM asuntos WHERE id = ?')->execute([$id]);
            $pdo->commit();

            if (isset($_GET['delete'])) {
                $_SESSION['flash_message'] = ['type' => 'success', 'text' => 'Asunto eliminado correctamente.'];
                header('Location: gestionar_asuntos.php');
                exit;
            }

            asunto_json_response(['success' => true, 'message' => 'Asunto eliminado correctamente.']);
        }

        asunto_json_response(['success' => false, 'message' => 'Acción no reconocida.']);
    } catch (PDOException $e) {
        if (isset($pdo) && $pdo->inTransaction()) $pdo->rollBack();

        $msg = $e->getMessage();
        if (stripos($msg, 'Duplicate') !== false || stripos($msg, '1062') !== false) {
            $msg = 'No se pudo guardar porque existe un alias duplicado para este asunto. Revisa las variantes ingresadas.';
        } else {
            $msg = 'No se pudo completar la acción. Revisa los datos e inténtalo nuevamente.';
        }

        if (isset($_GET['delete'])) {
            $_SESSION['flash_message'] = ['type' => 'error', 'text' => $msg];
            header('Location: gestionar_asuntos.php');
            exit;
        }

        asunto_json_response(['success' => false, 'message' => $msg]);
    } catch (Exception $e) {
        if (isset($pdo) && $pdo->inTransaction()) $pdo->rollBack();

        if (isset($_GET['delete'])) {
            $_SESSION['flash_message'] = ['type' => 'error', 'text' => $e->getMessage()];
            header('Location: gestionar_asuntos.php');
            exit;
        }

        asunto_json_response(['success' => false, 'message' => $e->getMessage()]);
    }
}

// === Página ===
$titulo_pagina = 'Gestionar Asuntos y Alias';
require_once 'admin_header.php';

$current_page = basename($_SERVER['PHP_SELF']);
$nombre_usuario_logueado = $_SESSION['admin']['nombre_usuario'] ?? 'Usuario';
$ui_primary_hex = (isset($ui_chatbot_color) && preg_match('/^#[0-9A-Fa-f]{6}$/', $ui_chatbot_color)) ? $ui_chatbot_color : '#dc2626';

// Carga de plataformas sin filtro agresivo para evitar que el modal quede vacío.
// Este módulo necesita poder seleccionar plataformas existentes del catálogo.
try {
    $plataformas = $pdo->query('SELECT id, nombre FROM plataformas ORDER BY nombre ASC')->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $plataformas = [];
}

$sqlAsuntos = "
    SELECT
        a.id,
        a.nombre,
        a.es_flexible,
        a.modo_coincidencia,
        a.visible_publico,
        a.id_plataforma,
        a.id_propietario_admin,
        a.id_admin_propietario,
        COALESCE(a.id_admin_propietario, a.id_propietario_admin, 0) AS propietario_real,
        p.nombre AS plataforma,
        p.imagen_url AS plataforma_imagen,
        COALESCE(u1.nombre_usuario, u2.nombre_usuario, 'Sistema') AS admin_propietario,
        GROUP_CONCAT(DISTINCT al.nombre ORDER BY al.nombre SEPARATOR ', ') AS aliases,
        COUNT(DISTINCT al.id) AS alias_count,
        COUNT(DISTINCT da.id_dominio) AS dominios_count,
        COALESCE(SUM(CASE WHEN da.es_publico = 1 THEN 1 ELSE 0 END), 0) AS publicos_count
    FROM asuntos a
    JOIN plataformas p ON p.id = a.id_plataforma
    LEFT JOIN asuntos_alias al ON al.id_asunto = a.id
    LEFT JOIN usuarios u1 ON a.id_admin_propietario = u1.id
    LEFT JOIN usuarios u2 ON a.id_propietario_admin = u2.id
    LEFT JOIN dominio_asunto da ON da.id_asunto = a.id
";
$paramsAsuntos = [];

if (!asunto_es_superadmin()) {
    $sqlAsuntos .= " 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
    )";
    $paramsAsuntos[] = asunto_admin_id_actual();
    $paramsAsuntos[] = asunto_admin_id_actual();
}

$sqlAsuntos .= "
    GROUP BY a.id, a.nombre, a.es_flexible, a.modo_coincidencia, a.visible_publico, a.id_plataforma,
             a.id_propietario_admin, a.id_admin_propietario, p.nombre, p.imagen_url, u1.nombre_usuario, u2.nombre_usuario
    ORDER BY p.nombre ASC, a.nombre ASC
";
$stmtAsuntos = $pdo->prepare($sqlAsuntos);
$stmtAsuntos->execute($paramsAsuntos);
$asuntos = $stmtAsuntos->fetchAll(PDO::FETCH_ASSOC);

$total_asuntos = count($asuntos);
$total_alias = 0;
$total_flexibles = 0;
$total_exactos = 0;
$total_dominios = 0;
$total_publicos = 0;
$total_sin_alias = 0;
$plataformas_usadas = [];

foreach ($asuntos as $a) {
    $total_alias += (int)($a['alias_count'] ?? 0);
    $total_dominios += (int)($a['dominios_count'] ?? 0);
    $total_publicos += (int)($a['publicos_count'] ?? 0);
    if ((int)($a['alias_count'] ?? 0) === 0) $total_sin_alias++;
    if ((int)($a['es_flexible'] ?? 0) === 1 || ($a['modo_coincidencia'] ?? '') === 'flexible') $total_flexibles++; else $total_exactos++;
    if (!empty($a['plataforma'])) $plataformas_usadas[$a['plataforma']] = true;
}
$total_plataformas_usadas = count($plataformas_usadas);
?>

<style>
.super-subject-ui{--brand:#ef3b43;--brand-dark:#d9252e;--ink:#0f172a;--muted:#64748b;--line:#dbe4ef;--surface:#fff;--soft:#f7f9fc;}
.super-subject-ui *{box-sizing:border-box;}
.module-context-strip{display:none!important;}
body.af-catalog-modal-open table.fixedHeader-floating,
body.af-catalog-modal-open table.fixedHeader-locked,
body.af-catalog-modal-open .fixedHeader-floating,
body.af-catalog-modal-open .fixedHeader-locked,
body.af-catalog-modal-open .dtfh-floatingparent{display:none!important;visibility:hidden!important;}
body.af-catalog-modal-open .admin-main table thead,
body.af-catalog-modal-open .admin-main table thead th{position:static!important;z-index:auto!important;visibility:hidden!important;opacity:0!important;pointer-events:none!important;}
body.af-catalog-modal-open .dataTables_scrollHead{visibility:hidden!important;opacity:0!important;}
.super-subject-ui{padding-left:0!important;padding-right:0!important;}
.super-subject-ui .module-shell{width:100%;max-width:1480px;margin:0 auto;}
.super-subject-ui .module-card{background:#fff;border:1px solid #dfe6ef;border-radius:20px;box-shadow:0 12px 30px rgba(15,23,42,.055);}
.super-subject-ui .module-hero{margin-top:18px;padding:18px 20px;display:flex;align-items:center;justify-content:space-between;gap:18px;}
.super-subject-ui .hero-main{display:flex;align-items:flex-start;gap:14px;min-width:0;}
.super-subject-ui .hero-icon{width:42px;height:42px;border-radius:13px;background:#feecee;color:var(--brand);display:flex;align-items:center;justify-content:center;flex:0 0 auto;font-size:17px;}
.super-subject-ui .eyebrow{font-size:11px;line-height:1.2;text-transform:uppercase;letter-spacing:.08em;font-weight:900;color:#50698a;margin-bottom:4px;}
.super-subject-ui .module-title{font-size:28px;line-height:1.05;font-weight:900;color:var(--ink);letter-spacing:-.035em;margin:0;}
.super-subject-ui .module-copy{font-size:13px;line-height:1.5;color:var(--muted);margin:6px 0 0;max-width:760px;}
.super-subject-ui .btn-primary,.super-subject-ui .btn-secondary{height:42px;border-radius:12px;padding:0 16px;display:inline-flex;align-items:center;justify-content:center;gap:8px;font-size:13px;font-weight:900;white-space:nowrap;transition:.16s;border:1px solid transparent;}
.super-subject-ui .btn-primary{background:linear-gradient(180deg,#fb444c 0%,#ee333c 100%);color:#fff;box-shadow:0 8px 18px rgba(239,59,67,.22);}
.super-subject-ui .btn-primary:hover{background:linear-gradient(180deg,#ef3942 0%,#d9252e 100%);transform:translateY(-1px);}
.super-subject-ui .btn-secondary{background:#fff;border-color:#d8e1ec;color:#0f172a;}
.super-subject-ui .btn-secondary:hover{background:#f8fafc;}
.super-subject-ui .stats-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;margin-top:14px;}
.super-subject-ui .stat-card{background:#fff;border:1px solid #dfe6ef;border-radius:16px;padding:13px 15px;display:flex;align-items:center;gap:12px;min-height:78px;box-shadow:0 7px 18px rgba(15,23,42,.035);}
.super-subject-ui .stat-icon{width:38px;height:38px;border-radius:12px;background:#feecee;color:var(--brand);display:flex;align-items:center;justify-content:center;flex:0 0 auto;}
.super-subject-ui .stat-label{font-size:10px;letter-spacing:.07em;text-transform:uppercase;font-weight:900;color:#5d728f;}
.super-subject-ui .stat-value{font-size:22px;line-height:1;font-weight:900;color:var(--ink);margin-top:4px;}
.super-subject-ui .stat-note{font-size:11px;color:#708199;margin-top:4px;line-height:1.25;}
.super-subject-ui .records-card{margin-top:14px;overflow:hidden;}
.super-subject-ui .records-head{padding:14px 16px;border-bottom:1px solid #e6edf5;display:flex;align-items:center;gap:11px;}
.super-subject-ui .section-icon{width:36px;height:36px;border-radius:11px;background:#feecee;color:var(--brand);display:flex;align-items:center;justify-content:center;flex:0 0 auto;}
.super-subject-ui .records-title{font-size:18px;font-weight:900;color:var(--ink);margin:0;}
.super-subject-ui .records-copy{font-size:12px;color:var(--muted);margin:2px 0 0;}
.super-subject-ui .toolbar{padding:12px 16px;border-bottom:1px solid #e6edf5;background:#f8fafc;display:grid;grid-template-columns:minmax(260px,1fr) 210px 180px 170px auto;gap:10px;align-items:end;}
.super-subject-ui .field-label{display:block;font-size:10px;font-weight:900;letter-spacing:.05em;text-transform:uppercase;color:#334155;margin:0 0 5px;}
.super-subject-ui .field-label i{color:var(--brand);margin-right:4px;}
.super-subject-ui .field,.super-subject-ui .textarea{width:100%;border:1px solid #cfd9e6;border-radius:10px;background:#fff;color:#0f172a;font-size:13px;outline:none;transition:.15s;}
.super-subject-ui .field{height:40px;padding:0 12px;}
.super-subject-ui .textarea{min-height:100px;padding:10px 12px;resize:vertical;line-height:1.45;}
.super-subject-ui .field:focus,.super-subject-ui .textarea:focus{border-color:#ef3b43;box-shadow:0 0 0 3px rgba(239,59,67,.09);}
.super-subject-ui .summary-row{padding:9px 16px;border-bottom:1px solid #e6edf5;display:flex;align-items:center;justify-content:space-between;gap:12px;color:#60728b;font-size:11px;background:#fff;}
.super-subject-ui .table-wrap{overflow-x:auto;}
.super-subject-ui table{width:100%;border-collapse:collapse;min-width:1090px;}
.super-subject-ui thead th{background:#eaf2f9;color:#172033;text-transform:uppercase;font-size:10px;letter-spacing:.04em;font-weight:900;padding:10px 12px;border-bottom:1px solid #d5e0eb;text-align:left;}
.super-subject-ui thead th.center,.super-subject-ui tbody td.center{text-align:center;}
.super-subject-ui thead th.right,.super-subject-ui tbody td.right{text-align:right;}
.super-subject-ui tbody td{padding:10px 12px;border-bottom:1px solid #e7edf4;color:#263449;font-size:12px;vertical-align:middle;background:#fff;}
.super-subject-ui tbody tr:nth-child(even) td{background:#fbfdff;}
.super-subject-ui tbody tr:hover td{background:#fff8f8;}
.super-subject-ui .platform-cell{display:flex;align-items:center;gap:9px;min-width:0;}
.super-subject-ui .platform-symbol{width:34px;height:34px;border:1px solid #dbe5ef;border-radius:9px;background:#fff;color:#6857ea;display:flex;align-items:center;justify-content:center;flex:0 0 auto;overflow:hidden;}
.super-subject-ui .platform-symbol img{display:block;max-width:27px;max-height:27px;object-fit:contain;}
.super-subject-ui .platform-symbol i{font-size:13px;line-height:1;}
.super-subject-ui .primary-text{font-size:12px;font-weight:900;color:#0f172a;line-height:1.35;overflow-wrap:anywhere;}
.super-subject-ui .secondary-text{font-size:10px;color:#708199;line-height:1.35;margin-top:3px;overflow-wrap:anywhere;}
.super-subject-ui .alias-list{display:flex;flex-wrap:wrap;gap:4px;margin-top:5px;}
.super-subject-ui .alias-chip{display:inline-flex;align-items:center;gap:4px;border:1px solid #d8defa;background:#f4f5ff;color:#5147a9;border-radius:999px;padding:3px 7px;font-size:9px;font-weight:800;max-width:250px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
.super-subject-ui .status-pill,.super-subject-ui .owner-pill{display:inline-flex;align-items:center;justify-content:center;gap:5px;border-radius:999px;padding:5px 9px;font-size:10px;font-weight:900;border:1px solid;white-space:nowrap;}
.super-subject-ui .status-exact{background:#ecfdf3;border-color:#b7ebc8;color:#087b42;}
.super-subject-ui .status-flex{background:#eff6ff;border-color:#bfdbfe;color:#1d4ed8;}
.super-subject-ui .owner-pill{background:#f8fafc;border-color:#dce4ed;color:#475569;}
.super-subject-ui .domain-main{font-weight:900;color:#172033;font-size:12px;}
.super-subject-ui .domain-sub{font-size:10px;color:#708199;margin-top:2px;}
.super-subject-ui .action-group{display:flex;justify-content:flex-end;align-items:center;gap:6px;}
.super-subject-ui .action-btn{width:34px;height:34px;border-radius:10px;display:inline-flex;align-items:center;justify-content:center;border:1px solid;font-size:12px;transition:.15s;}
.super-subject-ui .action-edit{background:#eff6ff;border-color:#bfdbfe;color:#1d4ed8;}
.super-subject-ui .action-edit:hover{background:#dbeafe;}
.super-subject-ui .action-delete{background:#fff1f2;border-color:#fecdd3;color:#be123c;}
.super-subject-ui .action-delete:hover{background:#ffe4e6;}
.super-subject-ui .empty-state{padding:42px 18px;text-align:center;color:#64748b;}
.super-subject-ui .empty-icon{width:48px;height:48px;border-radius:15px;background:#feecee;color:var(--brand);display:flex;align-items:center;justify-content:center;margin:0 auto 10px;font-size:19px;}
.super-subject-ui .records-foot{padding:10px 16px;border-top:1px solid #e6edf5;display:flex;align-items:center;justify-content:space-between;gap:12px;background:#fff;}
.super-subject-ui .foot-note{font-size:11px;color:#60728b;line-height:1.4;}
.super-subject-ui .pagination{display:flex;align-items:center;gap:5px;}
.super-subject-ui .page-btn{min-width:30px;height:30px;border:1px solid #dce4ed;border-radius:9px;background:#fff;color:#64748b;display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:900;padding:0 9px;}
.super-subject-ui .page-btn.active{background:var(--brand);border-color:var(--brand);color:#fff;}
.super-subject-ui .page-btn:disabled{opacity:.42;cursor:not-allowed;}
.super-subject-ui .modal-backdrop{position:fixed;inset:0;z-index:2147483646!important;background:rgba(15,23,42,.62);backdrop-filter:blur(4px);-webkit-backdrop-filter:blur(4px);isolation:isolate;}
.super-subject-ui .modal-shell{width:min(94vw,900px);max-height:91vh;border-radius:18px;overflow:hidden;background:#fff;border:1px solid #dfe6ef;box-shadow:0 25px 65px rgba(15,23,42,.30);display:flex;flex-direction:column;}
.super-subject-ui .modal-head{padding:14px 16px;border-bottom:1px solid #e4eaf2;display:flex;align-items:flex-start;justify-content:space-between;gap:14px;background:#fff;}
.super-subject-ui .modal-head-main{display:flex;align-items:flex-start;gap:11px;min-width:0;}
.super-subject-ui .modal-head-icon{width:34px;height:34px;border-radius:10px;background:#feecee;color:var(--brand);display:flex;align-items:center;justify-content:center;flex:0 0 auto;}
.super-subject-ui .modal-kicker{font-size:9px;font-weight:900;text-transform:uppercase;letter-spacing:.08em;color:var(--brand);margin-bottom:3px;}
.super-subject-ui .modal-title{font-size:20px;line-height:1.1;font-weight:900;color:#0f172a;}
.super-subject-ui .modal-copy{font-size:11px;color:#64748b;line-height:1.4;margin-top:4px;}
.super-subject-ui .modal-close{width:34px;height:34px;border-radius:10px;border:1px solid #dce4ed;background:#fff;color:#64748b;display:flex;align-items:center;justify-content:center;flex:0 0 auto;}
.super-subject-ui .modal-close:hover{background:#f8fafc;color:#111827;}
.super-subject-ui .modal-body{padding:14px 16px;overflow-y:auto;display:flex;flex-direction:column;gap:12px;}
.super-subject-ui .modal-note{padding:10px 12px;border:1px solid #fecaca;background:#fff6f6;border-radius:10px;color:#8f2d34;font-size:11px;line-height:1.45;display:flex;gap:8px;align-items:flex-start;}
.super-subject-ui .modal-grid{display:grid;grid-template-columns:1fr 1fr;gap:10px;}
.super-subject-ui .form-group{min-width:0;}
.super-subject-ui .help-text{font-size:10px;line-height:1.4;color:#718199;margin-top:4px;}
.super-subject-ui .mode-grid{display:grid;grid-template-columns:1fr 1fr;gap:7px;}
.super-subject-ui .mode-option{border:1px solid #d7e0ea;border-radius:10px;padding:9px 10px;background:#fff;display:flex;align-items:center;gap:10px;cursor:pointer;transition:.15s;min-height:60px;}
.super-subject-ui .mode-option.is-active{border-color:#ef3b43;background:#fff7f7;box-shadow:0 0 0 2px rgba(239,59,67,.07);}
.super-subject-ui .mode-option input{position:absolute;opacity:0;pointer-events:none;}
.super-subject-ui .mode-option .mode-option-icon{width:36px;height:36px;border-radius:10px;background:#f1f5f9;color:#475569;display:flex;align-items:center;justify-content:center;flex:0 0 36px;margin:0;}
.super-subject-ui .mode-option .mode-option-icon i{display:block;font-size:15px;line-height:1;margin:0;}
.super-subject-ui .mode-option.is-active .mode-option-icon{background:#feecee;color:#ef3b43;}
.super-subject-ui .mode-option-copy{display:block;min-width:0;margin:0;}
.super-subject-ui .mode-option-copy strong{display:block;font-size:11px;color:#172033;line-height:1.2;}
.super-subject-ui .mode-option-copy small{display:block;font-size:9px;color:#718199;margin-top:3px;line-height:1.3;}
.super-subject-ui .alias-preview{display:flex;flex-wrap:wrap;gap:5px;margin-top:7px;}
.super-subject-ui .modal-business-note{padding:9px 11px;border:1px solid #dbeafe;background:#f4f8ff;border-radius:10px;color:#31598e;font-size:10px;line-height:1.45;}
.super-subject-ui .modal-foot{padding:11px 16px;border-top:1px solid #e5ebf2;background:#fff;display:flex;justify-content:flex-end;gap:8px;}
.swal2-container{z-index:2147483647!important;}
@media(max-width:1100px){.super-subject-ui .toolbar{grid-template-columns:1fr 1fr 1fr;}.super-subject-ui .toolbar .search-field{grid-column:1 / -1;}}
@media(max-width:900px){.super-subject-ui .stats-grid{grid-template-columns:repeat(2,minmax(0,1fr));}}
@media(max-width:680px){.super-subject-ui .module-hero{align-items:flex-start;flex-direction:column;}.super-subject-ui .module-hero .btn-primary{width:100%;}.super-subject-ui .stats-grid{grid-template-columns:1fr;}.super-subject-ui .toolbar{grid-template-columns:1fr;}.super-subject-ui .toolbar .search-field{grid-column:auto;}.super-subject-ui .summary-row,.super-subject-ui .records-foot{align-items:flex-start;flex-direction:column;}.super-subject-ui .modal-grid,.super-subject-ui .mode-grid{grid-template-columns:1fr;}.super-subject-ui .modal-shell{max-height:92vh;}}
</style>

<div class="super-subject-ui pb-10">
    <div class="module-shell">
        <section class="module-card module-hero">
            <div class="hero-main">
                <span class="hero-icon"><i class="fas fa-tags"></i></span>
                <div>
                    <div class="eyebrow">Catálogo global</div>
                    <h1 class="module-title">Asuntos y alias</h1>
                    <p class="module-copy">Define los títulos que llegan por correo y registra variantes para que el sistema localice cada mensaje sin duplicar reglas.</p>
                </div>
            </div>
            <button type="button" id="openModalBtn" class="btn-primary"><i class="fas fa-plus-circle"></i> Nuevo asunto</button>
        </section>

        <section class="stats-grid" aria-label="Resumen de asuntos">
            <article class="stat-card">
                <span class="stat-icon"><i class="fas fa-envelope"></i></span>
                <div><div class="stat-label">Asuntos</div><div class="stat-value"><?= (int)$total_asuntos ?></div><div class="stat-note">Reglas principales</div></div>
            </article>
            <article class="stat-card">
                <span class="stat-icon"><i class="fas fa-bullseye"></i></span>
                <div><div class="stat-label">Exactos</div><div class="stat-value"><?= (int)$total_exactos ?></div><div class="stat-note">Coincidencia completa</div></div>
            </article>
            <article class="stat-card">
                <span class="stat-icon"><i class="fas fa-magnifying-glass-plus"></i></span>
                <div><div class="stat-label">Flexibles</div><div class="stat-value"><?= (int)$total_flexibles ?></div><div class="stat-note">Contienen texto</div></div>
            </article>
            <article class="stat-card">
                <span class="stat-icon"><i class="fas fa-language"></i></span>
                <div><div class="stat-label">Alias</div><div class="stat-value"><?= (int)$total_alias ?></div><div class="stat-note">Variantes registradas</div></div>
            </article>
        </section>

        <section class="module-card records-card">
            <header class="records-head">
                <span class="section-icon"><i class="fas fa-list-check"></i></span>
                <div><h2 class="records-title">Registros de asuntos</h2><p class="records-copy">Busca por plataforma, asunto, alias o propietario y administra las reglas del catálogo.</p></div>
            </header>

            <div class="toolbar">
                <div class="search-field">
                    <label class="field-label" for="search-input"><i class="fas fa-magnifying-glass"></i> Buscar</label>
                    <input type="search" id="search-input" class="field" placeholder="Asunto, alias, plataforma o propietario">
                </div>
                <div>
                    <label class="field-label" for="platform-filter"><i class="fas fa-layer-group"></i> Plataforma</label>
                    <select id="platform-filter" class="field">
                        <option value="">Todas</option>
                        <?php foreach ($plataformas as $p): ?>
                            <option value="<?= htmlspecialchars($p['nombre'], ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($p['nombre'], ENT_QUOTES, 'UTF-8') ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="field-label" for="match-filter"><i class="fas fa-bullseye"></i> Coincidencia</label>
                    <select id="match-filter" class="field"><option value="">Todas</option><option value="Exacto">Exacta</option><option value="Flexible">Flexible</option></select>
                </div>
                <div>
                    <label class="field-label" for="asuntosPageLength"><i class="fas fa-list-ol"></i> Mostrar</label>
                    <select id="asuntosPageLength" class="field"><option value="100" selected>100 registros</option><option value="200">200 registros</option><option value="400">400 registros</option><option value="-1">Todos</option></select>
                </div>
                <button type="button" id="clearFiltersBtn" class="btn-secondary"><i class="fas fa-eraser"></i> Limpiar</button>
            </div>

            <div class="summary-row">
                <span id="asuntosRegisteredText"><?= (int)$total_asuntos ?> asunto<?= $total_asuntos === 1 ? '' : 's' ?> registrado<?= $total_asuntos === 1 ? '' : 's' ?></span>
                <span id="asuntosShowingText">Mostrando registros</span>
            </div>

            <div class="table-wrap">
                <table id="tablaAsuntos">
                    <thead><tr><th style="width:155px">Plataforma</th><th>Asunto / alias</th><th class="center" style="width:125px">Coincidencia</th><th class="center" style="width:125px">Dominios</th><th class="center" style="width:145px">Propietario</th><th class="right" style="width:95px">Acciones</th></tr></thead>
                    <tbody>
                    <?php foreach ($asuntos as $a):
                        $alias_full = trim((string)($a['aliases'] ?? ''));
                        $alias_items = $alias_full !== '' ? array_values(array_filter(array_map('trim', explode(',', $alias_full)))) : [];
                        $is_flexible = (int)($a['es_flexible'] ?? 0) === 1 || ($a['modo_coincidencia'] ?? '') === 'flexible';
                        $dominios_count = (int)($a['dominios_count'] ?? 0);
                        $publicos_count = (int)($a['publicos_count'] ?? 0);
                    ?>
                        <tr>
                            <td>
                                <div class="platform-cell"><span class="platform-symbol"><?php $platformImage = trim((string)($a['plataforma_imagen'] ?? '')); if ($platformImage !== ''): ?><img src="../<?= htmlspecialchars($platformImage, ENT_QUOTES, 'UTF-8') ?>" alt="<?= htmlspecialchars($a['plataforma'] ?? 'Plataforma', ENT_QUOTES, 'UTF-8') ?>"><?php else: ?><i class="fas fa-display" aria-hidden="true"></i><?php endif; ?></span><div><div class="primary-text"><?= htmlspecialchars($a['plataforma'] ?? '', ENT_QUOTES, 'UTF-8') ?></div><div class="secondary-text">ID #<?= (int)$a['id'] ?></div></div></div>
                            </td>
                            <td>
                                <div class="primary-text"><?= htmlspecialchars($a['nombre'] ?? '', ENT_QUOTES, 'UTF-8') ?></div>
                                <?php if ($alias_items): ?><div class="alias-list" title="<?= htmlspecialchars($alias_full, ENT_QUOTES, 'UTF-8') ?>"><?php foreach ($alias_items as $alias): ?><span class="alias-chip"><i class="fas fa-language"></i><?= htmlspecialchars($alias, ENT_QUOTES, 'UTF-8') ?></span><?php endforeach; ?></div><?php else: ?><div class="secondary-text">Sin alias configurados</div><?php endif; ?>
                            </td>
                            <td class="center"><?php if ($is_flexible): ?><span class="status-pill status-flex"><i class="fas fa-magnifying-glass-plus"></i> Flexible</span><?php else: ?><span class="status-pill status-exact"><i class="fas fa-bullseye"></i> Exacto</span><?php endif; ?></td>
                            <td class="center"><div class="domain-main"><?= $dominios_count ?> asignación<?= $dominios_count === 1 ? '' : 'es' ?></div><div class="domain-sub"><?= $publicos_count ?> público<?= $publicos_count === 1 ? '' : 's' ?></div></td>
                            <td class="center"><span class="owner-pill"><i class="fas fa-user-shield"></i><?= htmlspecialchars($a['admin_propietario'] ?? 'Sistema', ENT_QUOTES, 'UTF-8') ?></span></td>
                            <td class="right"><div class="action-group"><button type="button" class="action-btn action-edit edit-btn" title="Editar asunto" data-id="<?= (int)$a['id'] ?>"><i class="fas fa-pen"></i></button><button type="button" class="action-btn action-delete delete-btn" title="Eliminar asunto" data-id="<?= (int)$a['id'] ?>"><i class="fas fa-trash"></i></button></div></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <footer class="records-foot">
                <div class="foot-note">Los asuntos reconocen los correos del sistema; su condición pública o privada se define en cada dominio.</div>
                <div id="asuntosPagination" class="pagination"></div>
            </footer>
        </section>
    </div>
</div>

<div id="asuntoModal" class="super-subject-ui modal-backdrop fixed inset-0 hidden items-center justify-center z-[2147483000] px-3 py-4">
    <div class="modal-shell" role="dialog" aria-modal="true" aria-labelledby="modalTitle">
        <div class="modal-head">
            <div class="modal-head-main"><span class="modal-head-icon"><i class="fas fa-tags"></i></span><div><div class="modal-kicker">Gestionar asuntos · formulario</div><div class="modal-title" id="modalTitle">Nuevo asunto</div><p class="modal-copy">Registra el título real del correo y sus variantes para que el sistema pueda localizarlo correctamente.</p></div></div>
            <button type="button" id="closeModalBtn" class="modal-close" aria-label="Cerrar"><i class="fas fa-times"></i></button>
        </div>
        <form id="asuntoForm" class="flex min-h-0 flex-1 flex-col">
            <input type="hidden" name="action" value="guardar_asunto"><input type="hidden" name="id" id="asuntoId"><input type="checkbox" name="es_flexible" id="es_flexible" value="1" hidden>
            <div class="modal-body">
                <div class="modal-note"><i class="fas fa-shield-halved"></i><div><strong>Regla de negocio:</strong> registra un solo asunto principal por mensaje y usa alias para otros idiomas o pequeñas variantes. La visibilidad pública o privada se configura desde Dominios.</div></div>
                <div class="modal-grid">
                    <div class="form-group"><label class="field-label" for="id_plataforma"><i class="fas fa-layer-group"></i> Plataforma *</label><select name="id_plataforma" id="id_plataforma" class="field" required><option value="">Seleccionar plataforma</option><?php foreach ($plataformas as $p): ?><option value="<?= (int)$p['id'] ?>"><?= htmlspecialchars($p['nombre'], ENT_QUOTES, 'UTF-8') ?></option><?php endforeach; ?></select><div class="help-text">Servicio al que pertenece el mensaje.</div></div>
                    <div class="form-group"><label class="field-label"><i class="fas fa-bullseye"></i> Coincidencia *</label><div class="mode-grid"><label class="mode-option is-active" for="es_flexible_off"><input type="radio" name="modo_visual" id="es_flexible_off" value="exacto" checked><span class="mode-option-icon" aria-hidden="true"><i class="fas fa-bullseye"></i></span><span class="mode-option-copy"><strong>Exacta</strong><small>El título debe coincidir completo.</small></span></label><label class="mode-option" for="es_flexible_on"><input type="radio" name="modo_visual" id="es_flexible_on" value="flexible"><span class="mode-option-icon" aria-hidden="true"><i class="fas fa-magnifying-glass-plus"></i></span><span class="mode-option-copy"><strong>Flexible</strong><small>El título contiene el texto registrado.</small></span></label></div></div>
                </div>
                <div class="form-group"><label class="field-label" for="nombre"><i class="fas fa-envelope-open-text"></i> Asunto principal *</label><input type="text" name="nombre" id="nombre" class="field" placeholder="Ejemplo: Tu código de acceso único para Disney+" required><div class="help-text">Escribe el título tal como llega en el correo. No uses únicamente el nombre de la plataforma.</div></div>
                <div class="form-group"><label class="field-label" for="aliases"><i class="fas fa-language"></i> Alias o variantes <span style="color:#94a3b8">Opcional</span></label><textarea name="aliases" id="aliases" class="textarea" rows="4" placeholder="Una variante por línea o separadas por comas"></textarea><div class="help-text">Añade traducciones o variaciones del mismo mensaje; no crees otro asunto para el mismo correo.</div><div id="aliasPreview" class="alias-preview"></div></div>
                <div class="modal-business-note"><i class="fas fa-circle-info"></i> Los dominios asociados y su privacidad no se modifican desde este formulario. La eliminación se bloqueará cuando el asunto mantenga relaciones activas.</div>
            </div>
            <div class="modal-foot"><button type="button" id="cancelModalBtn" class="btn-secondary"><i class="fas fa-times"></i> Cancelar</button><button type="submit" id="btnGuardarAsunto" class="btn-primary"><i class="fas fa-floppy-disk"></i> Guardar asunto</button></div>
        </form>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
(function($){
    'use strict';
    const modal = $('#asuntoModal');
    let table = null;

    function escapeHtml(value){ return String(value ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[c])); }
    function splitAliases(raw){ return String(raw || '').split(/[\n,]+/).map(v => v.trim()).filter(Boolean).filter((v,i,a) => a.findIndex(x => x.toLowerCase() === v.toLowerCase()) === i); }
    function renderAliasPreview(){ const values = splitAliases($('#aliases').val()); $('#aliasPreview').html(values.slice(0,12).map(v => `<span class="alias-chip"><i class="fas fa-language"></i>${escapeHtml(v)}</span>`).join('') + (values.length > 12 ? `<span class="alias-chip">+${values.length-12} más</span>` : '')); }
    function syncMode(){ const flexible = $('#es_flexible_on').is(':checked'); $('#es_flexible').prop('checked', flexible); $('.mode-option').removeClass('is-active'); (flexible ? $('#es_flexible_on') : $('#es_flexible_off')).closest('.mode-option').addClass('is-active'); }

    function renderTableMeta(){
        if(!table) return;
        const info = table.page.info();
        const total = info.recordsDisplay || 0;
        const start = total ? info.start + 1 : 0;
        const end = total ? info.end : 0;
        $('#asuntosShowingText').text(total ? `Mostrando ${start}–${end} de ${total} registros` : 'No hay registros que coincidan con los filtros');
        const disabledPrev = info.page <= 0 || info.pages <= 1;
        const disabledNext = info.page >= info.pages - 1 || info.pages <= 1;
        const pageNumber = info.pages ? info.page + 1 : 1;
        $('#asuntosPagination').html(`<button type="button" class="page-btn" data-page="prev" ${disabledPrev?'disabled':''}><i class="fas fa-chevron-left"></i></button><button type="button" class="page-btn active" disabled>${pageNumber}</button><button type="button" class="page-btn" data-page="next" ${disabledNext?'disabled':''}><i class="fas fa-chevron-right"></i></button>`);
    }

    function applyFilters(){
        table.search($('#search-input').val() || '');
        const platform = $('#platform-filter').val() || '';
        const match = $('#match-filter').val() || '';
        table.column(0).search(platform, false, false);
        table.column(2).search(match, false, false);
        table.draw();
    }

    function closeModal(){ $('body').removeClass('overflow-hidden af-catalog-modal-open'); modal.addClass('hidden').removeClass('flex'); }
    function openModal(isEdit, data){
        const form = $('#asuntoForm')[0];
        form.reset();
        $('#asuntoId').val(''); $('#modalTitle').text(isEdit ? 'Editar asunto' : 'Nuevo asunto'); $('#aliases').val(''); $('#es_flexible_off').prop('checked', true); $('#es_flexible_on').prop('checked', false);
        if(isEdit){ $('#asuntoId').val(data.id || ''); $('#id_plataforma').val(data.id_plataforma || ''); $('#nombre').val(data.nombre || ''); $('#aliases').val(data.aliases || ''); if(Number(data.es_flexible) === 1 || String(data.modo_coincidencia || '') === 'flexible'){ $('#es_flexible_on').prop('checked', true); $('#es_flexible_off').prop('checked', false); } }
        syncMode(); renderAliasPreview(); $('body').addClass('overflow-hidden af-catalog-modal-open'); modal.removeClass('hidden').addClass('flex'); modal.find('.modal-body').scrollTop(0); setTimeout(() => $('#id_plataforma').trigger('focus'), 60);
    }

    $(function(){
        <?php if (!empty($_SESSION['flash_message'])): ?>
        Swal.fire({icon:<?= json_encode($_SESSION['flash_message']['type'] === 'success' ? 'success' : 'error') ?>,title:<?= json_encode($_SESSION['flash_message']['type'] === 'success' ? 'Listo' : 'Error') ?>,text:<?= json_encode($_SESSION['flash_message']['text']) ?>,confirmButtonColor:'#dc2626'});
        <?php unset($_SESSION['flash_message']); endif; ?>

        if($.fn.DataTable.isDataTable('#tablaAsuntos')) $('#tablaAsuntos').DataTable().destroy();
        table = $('#tablaAsuntos').DataTable({dom:'t',pageLength:100,lengthMenu:[[100,200,400,-1],[100,200,400,'Todos']],autoWidth:false,deferRender:true,order:[],language:{emptyTable:'No se encontraron asuntos',zeroRecords:'No hay registros que coincidan con los filtros'},columnDefs:[{orderable:false,targets:[5]}]});
        table.on('draw page.dt length.dt search.dt', renderTableMeta);
        renderTableMeta();

        $('#search-input').on('input', applyFilters);
        $('#platform-filter, #match-filter').on('change', applyFilters);
        $('#asuntosPageLength').on('change', function(){ table.page.len(parseInt(this.value,10)).draw(); });
        $('#clearFiltersBtn').on('click', function(){ $('#search-input').val(''); $('#platform-filter,#match-filter').val(''); $('#asuntosPageLength').val('100'); table.search('').columns().search('').page.len(100).draw(); });
        $('#asuntosPagination').on('click','.page-btn',function(){ const target=$(this).data('page'); if($(this).prop('disabled')) return; table.page(target === 'prev' ? 'previous' : 'next').draw('page'); });

        $('#openModalBtn').on('click', () => openModal(false, {}));
        $('#closeModalBtn, #cancelModalBtn').on('click', closeModal);
        modal.on('click', function(e){ if(e.target === this) closeModal(); });
        $(document).on('keydown.asuntoModal', function(e){ if(e.key === 'Escape' && modal.hasClass('flex')) closeModal(); });
        $('input[name="modo_visual"]').on('change', syncMode);
        $('#aliases').on('input', renderAliasPreview);

        $('#tablaAsuntos').on('click','.edit-btn',function(){
            const id=$(this).data('id');
            Swal.fire({title:'Cargando...',allowOutsideClick:false,didOpen:()=>Swal.showLoading()});
            $.get('gestionar_asuntos.php',{fetch_data:id},function(response){ Swal.close(); if(response.success) openModal(true,response.data||{}); else Swal.fire({icon:'error',title:'No se pudo cargar',text:response.message||'El asunto no está disponible.',confirmButtonColor:'#dc2626'}); },'json').fail(function(){ Swal.close(); Swal.fire({icon:'error',title:'Error de conexión',text:'No se pudo conectar con el servidor.',confirmButtonColor:'#dc2626'}); });
        });

        $('#tablaAsuntos').on('click','.delete-btn',function(){
            const id=$(this).data('id');
            Swal.fire({title:'¿Eliminar asunto?',html:'Se eliminarán también sus alias.<br><strong>El sistema bloqueará la acción si existen dominios, asociaciones o permisos relacionados.</strong>',icon:'warning',showCancelButton:true,confirmButtonColor:'#dc2626',cancelButtonColor:'#64748b',confirmButtonText:'Sí, eliminar',cancelButtonText:'Cancelar'}).then(result=>{ if(!result.isConfirmed) return; $.post('gestionar_asuntos.php',{action:'delete_asunto',id:id},function(response){ if(response.success) Swal.fire({icon:'success',title:'Asunto eliminado',text:response.message,confirmButtonColor:'#dc2626'}).then(()=>location.reload()); else Swal.fire({icon:'error',title:'No se pudo eliminar',text:response.message||'Revisa las relaciones del asunto.',confirmButtonColor:'#dc2626'}); },'json').fail(()=>Swal.fire({icon:'error',title:'Error de conexión',text:'No se pudo completar la solicitud.',confirmButtonColor:'#dc2626'})); });
        });

        $('#asuntoForm').on('submit',function(e){
            e.preventDefault(); syncMode();
            const button=$('#btnGuardarAsunto'); const original=button.html(); button.prop('disabled',true).html('<i class="fas fa-spinner fa-spin"></i> Guardando...');
            $.post('gestionar_asuntos.php',$(this).serialize(),function(response){ if(response.success){ closeModal(); Swal.fire({icon:'success',title:'Listo',text:response.message,confirmButtonColor:'#dc2626'}).then(()=>location.reload()); } else { Swal.fire({icon:'error',title:'No se pudo guardar',text:response.message||'Revisa los datos.',confirmButtonColor:'#dc2626'}); button.prop('disabled',false).html(original); } },'json').fail(function(){ Swal.fire({icon:'error',title:'Error de conexión',text:'No se pudo conectar con el servidor.',confirmButtonColor:'#dc2626'}); button.prop('disabled',false).html(original); });
        });
    });
})(jQuery);
</script>

<?php require_once 'admin_footer.php'; ?>
