<?php
$stats = is_array($stats ?? null) ? $stats : [];
$plans = is_array($plans ?? null) ? $plans : [];
$companies = is_array($companies ?? null) ? $companies : [];
$subscriptions = is_array($subscriptions ?? null) ? $subscriptions : [];
$payments = is_array($payments ?? null) ? $payments : [];
$checkoutIntents = is_array($checkout_intents ?? null) ? $checkout_intents : [];
$supportAgents = is_array($support_agents ?? null) ? $support_agents : [];
$supportTickets = is_array($support_tickets ?? null) ? $support_tickets : [];
$supportEventsByTicket = is_array($support_events_by_ticket ?? null) ? $support_events_by_ticket : [];
$supportSlaSummary = is_array($support_sla_summary ?? null) ? $support_sla_summary : [];
$supportSlaByCompany = is_array($support_sla_by_company ?? null) ? $support_sla_by_company : [];
$supportSlaByAgent = is_array($support_sla_by_agent ?? null) ? $support_sla_by_agent : [];
$supportReportFilter = is_array($support_report_filter ?? null) ? $support_report_filter : [];
$collectionNoticeQueue = is_array($collection_notice_queue ?? null) ? $collection_notice_queue : [];
$wompi = is_array($wompi ?? null) ? $wompi : [];
$smtpConfig = is_array($smtp_config ?? null) ? $smtp_config : [];
$notificationConfig = is_array($notification_config ?? null) ? $notification_config : [];
$notificationTestPhoneDefault = trim((string) ($notification_test_phone_default ?? ''));
$whatsAppMetaTemplates = is_array($whatsapp_meta_templates ?? null) ? $whatsapp_meta_templates : [];
$whatsAppTemplateStatusStats = is_array($whatsapp_template_status_stats ?? null) ? $whatsapp_template_status_stats : [];
$aiConfig = is_array($ai_config ?? null) ? $ai_config : [];
$openAiReport = is_array($openai_report ?? null) ? $openai_report : [];
$openAiReportSettings = is_array($openAiReport['settings'] ?? null) ? $openAiReport['settings'] : [];
$openAiReportUsage = is_array($openAiReport['usage'] ?? null) ? $openAiReport['usage'] : [];
$openAiTopCompaniesToday = is_array($openAiReport['top_companies_today'] ?? null) ? $openAiReport['top_companies_today'] : [];
$superadminSections = [
    'resumen',
    'wompi',
    'correo',
    'whatsapp_meta',
    'whatsapp_meta_templates',
    'whatsapp_manychat',
    'notificaciones',
    'ai',
    'reporte_openia',
    'checkout',
    'cobranza',
    'planes',
    'empresas',
    'suscripciones',
    'sla',
    'soporte',
    'pagos',
];
$superadminSection = strtolower(trim((string) ($_GET['seccion'] ?? 'resumen')));
if (!in_array($superadminSection, $superadminSections, true)) {
    $superadminSection = 'resumen';
}
$whatsAppModalAutoOpen = strtolower(trim((string) ($_GET['wa_modal'] ?? '')));
if (!in_array($whatsAppModalAutoOpen, ['meta', 'manychat', 'template', 'template_link'], true)) {
    $whatsAppModalAutoOpen = '';
}
$paymentDateDefault = date('Y-m-d\TH:i');
$openFactusCompanyId = (int) ($_GET['factus_empresa'] ?? 0);
$selectedWhatsAppProvider = strtolower(trim((string) ($notificationConfig['whatsapp_provider'] ?? 'meta')));
if (!in_array($selectedWhatsAppProvider, ['meta', 'manychat'], true)) {
    $selectedWhatsAppProvider = 'meta';
}
$metaProviderActive = $selectedWhatsAppProvider === 'meta';
$manyChatProviderActive = $selectedWhatsAppProvider === 'manychat';
$metaTokenMasked = trim((string) ($notificationConfig['whatsapp_access_token_masked'] ?? ''));
$manyChatTokenMasked = trim((string) ($notificationConfig['manychat_access_token_masked'] ?? ''));
$metaHasToken = $metaTokenMasked !== '' && strtolower($metaTokenMasked) !== 'no configurado';
$manyChatHasToken = $manyChatTokenMasked !== '' && strtolower($manyChatTokenMasked) !== 'no configurado';
$metaConfigured = trim((string) ($notificationConfig['whatsapp_api_url'] ?? '')) !== ''
    && trim((string) ($notificationConfig['whatsapp_phone_number_id'] ?? '')) !== ''
    && $metaHasToken;
$manyChatConfigured = trim((string) ($notificationConfig['manychat_api_url'] ?? '')) !== ''
    && $manyChatHasToken;
$gmailConfigured = !empty($notificationConfig['has_email_sender']);
$wompiConfigured = !empty($wompi['checkout_configured']);
$openAiConfigured = !empty($aiConfig['is_ready']);
$metaLogo = (string) url('assets/img/integrations/logo-facebook.webp');
$gmailLogo = (string) url('assets/img/integrations/logo-gmail.jpg');
$openAiLogo = (string) url('assets/img/integrations/logo-openai.webp');
$wompiLogo = (string) url('assets/img/integrations/logo-wompi-brand.jpg');
$smtpSecure = strtolower((string) ($smtpConfig['secure'] ?? 'tls'));
$smtpHost = trim((string) ($smtpConfig['host'] ?? ''));
$smtpPort = trim((string) ($smtpConfig['port'] ?? '587'));
$smtpUsername = trim((string) ($smtpConfig['username'] ?? ''));
$smtpFromEmail = trim((string) ($smtpConfig['from_email'] ?? ''));
$smtpFromName = trim((string) ($smtpConfig['from_name'] ?? 'Veltrix POS'));
$retryBackoffValue = (string) ($notificationConfig['retry_backoff_minutes'] ?? '5,30,180');
$retryBackoffPreview = array_values(array_filter(
    array_map('trim', explode(',', $retryBackoffValue)),
    static fn (string $v): bool => $v !== '' && ctype_digit($v)
));
if ($retryBackoffPreview === []) {
    $retryBackoffPreview = ['5', '30', '180'];
}
$whatsAppQueueTotal = count($collectionNoticeQueue);
$whatsAppQueue10 = count(array_filter($collectionNoticeQueue, static fn (array $row): bool => (string) ($row['tipo'] ?? '') === 'previo_10_dias'));
$whatsAppQueue3 = count(array_filter($collectionNoticeQueue, static fn (array $row): bool => (string) ($row['tipo'] ?? '') === 'previo_3_dias'));
$whatsAppPendingTotal = count(array_filter($collectionNoticeQueue, static fn (array $row): bool => (string) ($row['estado'] ?? '') === 'pendiente'));
$whatsAppFailedTotal = count(array_filter($collectionNoticeQueue, static fn (array $row): bool => in_array((string) ($row['estado'] ?? ''), ['error', 'fallido'], true)));
$whatsAppTemplatePendingCount = (int) ($whatsAppTemplateStatusStats['pendiente'] ?? 0);
$whatsAppTemplateApprovedCount = (int) ($whatsAppTemplateStatusStats['aprobada'] ?? 0);
$whatsAppTemplateRejectedCount = (int) ($whatsAppTemplateStatusStats['rechazada'] ?? 0);
$whatsAppTemplateTotalCount = count($whatsAppMetaTemplates);
$whatsAppTemplateLinkedCount = count(array_filter(
    $whatsAppMetaTemplates,
    static function (array $row): bool {
        $usage = strtolower(trim((string) ($row['uso'] ?? 'libre')));
        return $usage !== '' && $usage !== 'libre';
    }
));
$whatsAppTemplateFreeCount = max(0, $whatsAppTemplateTotalCount - $whatsAppTemplateLinkedCount);
$resolveWhatsAppUsageLabel = static function (string $usage): string {
    $usage = strtolower(trim($usage));
    if ($usage === '' || $usage === 'libre') {
        return 'Libre';
    }
    if ($usage === 'previo_10_dias') {
        return 'Aviso 10 días';
    }
    if ($usage === 'previo_3_dias') {
        return 'Aviso 3 días';
    }
    if ($usage === 'previo_1_dia') {
        return 'Aviso 1 día';
    }
    if ($usage === 'vence_hoy') {
        return 'Vence hoy';
    }
    if ($usage === 'vencida') {
        return 'Suscripción vencida';
    }
    if ($usage === 'morosa') {
        return 'Suscripción en mora';
    }
    if (preg_match('/^previo_(\d{1,3})_dias$/', $usage, $matches) === 1) {
        return 'Aviso ' . (int) ($matches[1] ?? 0) . ' días';
    }

    return strtoupper(str_replace('_', ' ', $usage));
};
$resolveWhatsAppUsageOrder = static function (string $usage): int {
    $usage = strtolower(trim($usage));
    if ($usage === 'previo_10_dias') {
        return 10;
    }
    if ($usage === 'previo_3_dias') {
        return 20;
    }
    if ($usage === 'previo_1_dia') {
        return 30;
    }
    if ($usage === 'vence_hoy') {
        return 40;
    }
    if (preg_match('/^previo_(\d{1,3})_dias$/', $usage, $matches) === 1) {
        return 100 + (int) ($matches[1] ?? 0);
    }
    if ($usage === 'vencida') {
        return 900;
    }
    if ($usage === 'morosa') {
        return 910;
    }

    return 999;
};
$whatsAppTemplateLinks = array_values(array_filter(
    $whatsAppMetaTemplates,
    static fn (array $row): bool => strtolower(trim((string) ($row['uso'] ?? 'libre'))) !== 'libre'
));
usort($whatsAppTemplateLinks, static function (array $a, array $b) use ($resolveWhatsAppUsageOrder): int {
    $usageA = strtolower(trim((string) ($a['uso'] ?? 'libre')));
    $usageB = strtolower(trim((string) ($b['uso'] ?? 'libre')));
    $orderA = $resolveWhatsAppUsageOrder($usageA);
    $orderB = $resolveWhatsAppUsageOrder($usageB);
    if ($orderA !== $orderB) {
        return $orderA <=> $orderB;
    }

    return strcmp((string) ($a['nombre'] ?? ''), (string) ($b['nombre'] ?? ''));
});
$whatsAppDispatchTimeSettings = is_array($whatsapp_dispatch_time_settings ?? null) ? $whatsapp_dispatch_time_settings : [];
$whatsAppDispatchTimeDefault = trim((string) ($whatsAppDispatchTimeSettings['default'] ?? '10:00'));
if (preg_match('/^(?:[01]\d|2[0-3]):[0-5]\d$/', $whatsAppDispatchTimeDefault) !== 1) {
    $whatsAppDispatchTimeDefault = '10:00';
}
$resolveDispatchTimeForUsage = static function (string $usage) use ($whatsAppDispatchTimeSettings, $whatsAppDispatchTimeDefault): string {
    $usage = strtolower(trim($usage));
    if ($usage === '' || $usage === 'libre') {
        return $whatsAppDispatchTimeDefault;
    }
    $time = trim((string) ($whatsAppDispatchTimeSettings[$usage] ?? ''));
    if (preg_match('/^(?:[01]\d|2[0-3]):[0-5]\d$/', $time) !== 1) {
        return $whatsAppDispatchTimeDefault;
    }

    return $time;
};
$whatsAppTemplateCenterRows = array_slice($whatsAppMetaTemplates, 0, 8);
$whatsAppTemplateCenterHiddenCount = max(0, $whatsAppTemplateTotalCount - count($whatsAppTemplateCenterRows));
$whatsAppDispatchTypes = ['previo_10_dias', 'previo_3_dias', 'previo_1_dia', 'vence_hoy', 'vencida', 'morosa'];
foreach ($whatsAppTemplateLinks as $linkedTemplate) {
    $usage = strtolower(trim((string) ($linkedTemplate['uso'] ?? '')));
    if ($usage === '' || $usage === 'libre') {
        continue;
    }
    $whatsAppDispatchTypes[] = $usage;
}
$whatsAppDispatchTypes = array_values(array_unique($whatsAppDispatchTypes));
usort($whatsAppDispatchTypes, static function (string $a, string $b) use ($resolveWhatsAppUsageOrder): int {
    $orderA = $resolveWhatsAppUsageOrder($a);
    $orderB = $resolveWhatsAppUsageOrder($b);
    if ($orderA !== $orderB) {
        return $orderA <=> $orderB;
    }

    return strcmp($a, $b);
});
?>

<style>
    .sa-section {
        display: none;
    }
    .sa-section.is-active {
        display: block;
    }
    .sa-notify-card {
        border: 1px solid #dbe4ff;
        border-radius: 14px;
        background: #f8fbff;
        padding: 14px 16px;
        height: 100%;
    }
    .sa-notify-panel {
        border: 1px solid #dbe4ff;
        border-radius: 16px;
        padding: 16px;
        background: #ffffff;
    }
    .sa-notify-title {
        font-size: 0.92rem;
        font-weight: 700;
        letter-spacing: 0.02em;
        text-transform: uppercase;
        color: #3f5a8a;
        margin-bottom: 12px;
    }
    .sa-notify-status {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        margin-top: 8px;
    }
    .sa-brand-grid {
        display: grid;
        grid-template-columns: repeat(5, minmax(0, 1fr));
        gap: 12px;
    }
    .sa-brand-chip {
        border: 1px solid #d6def3;
        border-radius: 16px;
        background: linear-gradient(180deg, #ffffff 0%, #f6f9ff 100%);
        padding: 12px;
        min-height: 122px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        transition: transform 0.18s ease, box-shadow 0.18s ease, border-color 0.18s ease;
    }
    .sa-brand-chip:hover {
        transform: translateY(-2px);
        box-shadow: 0 14px 32px rgba(21, 43, 91, 0.10);
    }
    .sa-brand-chip.is-ready {
        border-color: #b9dfcf;
    }
    .sa-brand-chip.is-active {
        border-color: #7aa8ff;
        box-shadow: 0 0 0 2px rgba(84, 119, 255, 0.18);
    }
    .sa-brand-chip-head {
        display: flex;
        align-items: center;
        gap: 10px;
    }
    .sa-brand-chip-logo {
        width: 42px;
        height: 42px;
        border-radius: 12px;
        overflow: hidden;
        background: #fff;
        border: 1px solid #dbe5ff;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        flex-shrink: 0;
    }
    .sa-brand-chip-logo img {
        width: 100%;
        height: 100%;
        object-fit: contain;
        display: block;
    }
    .sa-brand-chip-title {
        font-size: 0.9rem;
        font-weight: 700;
        color: #283b67;
        margin: 0;
        line-height: 1.2;
    }
    .sa-brand-chip-subtitle {
        font-size: 0.76rem;
        color: #6a7695;
        margin: 0;
    }
    .sa-brand-chip-status {
        margin-top: 10px;
    }
    .sa-brand-chip-actions {
        margin-top: 10px;
    }
    .sa-brand-chip-actions .btn {
        width: 100%;
    }
    .sa-integration-form-card {
        border: 1px solid #d6def3;
        border-radius: 16px;
        padding: 14px;
        background: linear-gradient(180deg, #ffffff 0%, #f9fbff 100%);
        box-shadow: 0 10px 28px rgba(19, 34, 70, 0.05);
    }
    .sa-integration-form-card[data-provider="meta"] {
        border-color: #cfe0ff;
        background: linear-gradient(180deg, #ffffff 0%, #f4f8ff 100%);
    }
    .sa-integration-form-card[data-provider="manychat"] {
        border-color: #d8d0ff;
        background: linear-gradient(180deg, #ffffff 0%, #f8f6ff 100%);
    }
    .sa-integration-form-card[data-provider="email"] {
        border-color: #ffe3b7;
        background: linear-gradient(180deg, #ffffff 0%, #fffaf2 100%);
    }
    .sa-integration-form-card[data-provider="ops"] {
        border-color: #d5e6ff;
    }
    .sa-integration-form-card[data-provider="test"] {
        border-color: #d6e8d8;
        background: linear-gradient(180deg, #ffffff 0%, #f4fbf5 100%);
    }
    .sa-integration-head {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-bottom: 12px;
    }
    .sa-integration-logo {
        width: 46px;
        height: 46px;
        border-radius: 14px;
        border: 1px solid #d8e3ff;
        background: #fff;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        overflow: hidden;
        flex-shrink: 0;
    }
    .sa-integration-logo img {
        width: 100%;
        height: 100%;
        object-fit: contain;
        display: block;
    }
    .sa-integration-logo .bx {
        font-size: 1.6rem;
        color: #6f65d9;
    }
    .sa-integration-title {
        margin: 0;
        font-size: 0.95rem;
        font-weight: 700;
        color: #253b63;
    }
    .sa-integration-subtitle {
        margin: 0;
        font-size: 0.78rem;
        color: #66769b;
    }
    .sa-provider-toggle {
        border: 1px dashed #bfd0ff;
        border-radius: 12px;
        padding: 8px 10px;
        background: rgba(255, 255, 255, 0.72);
        margin-bottom: 10px;
    }
    .sa-provider-toggle label {
        font-weight: 600;
        color: #344e7f;
        font-size: 0.85rem;
    }
    .sa-mini-integration-list {
        display: grid;
        grid-template-columns: repeat(2, minmax(0, 1fr));
        gap: 10px;
        margin-top: 12px;
    }
    .sa-mini-integration {
        border: 1px solid #d7e3ea;
        border-radius: 12px;
        background: #fff;
        padding: 10px;
        display: flex;
        align-items: center;
        gap: 8px;
    }
    .sa-mini-integration strong {
        font-size: 0.82rem;
        color: #2f4168;
        display: block;
        line-height: 1.2;
    }
    .sa-mini-integration small {
        font-size: 0.73rem;
        color: #6f7f9f;
        display: block;
        line-height: 1.2;
    }
    .sa-ops-layout {
        display: grid;
        grid-template-columns: 1.2fr 0.8fr;
        gap: 14px;
    }
    .sa-ops-inputs {
        border: 1px solid #dce6ff;
        border-radius: 12px;
        padding: 12px;
        background: #fff;
    }
    .sa-ops-channels {
        border: 1px solid #dce6ff;
        border-radius: 12px;
        padding: 12px;
        background: #fff;
    }
    .sa-ops-channels-title {
        font-size: 0.82rem;
        text-transform: uppercase;
        letter-spacing: 0.04em;
        color: #5a6f99;
        margin-bottom: 10px;
        font-weight: 700;
    }
    .sa-ops-switch-list {
        display: grid;
        gap: 8px;
    }
    .sa-ops-switch-item {
        border: 1px solid #e0e8fb;
        border-radius: 10px;
        padding: 9px 10px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 10px;
    }
    .sa-ops-switch-item .form-check-label {
        font-weight: 600;
        color: #34486f;
    }
    .sa-ops-backoff-hints {
        margin-top: 10px;
        display: flex;
        flex-wrap: wrap;
        gap: 6px;
    }
    .sa-ops-backoff-chip {
        font-size: 0.74rem;
        border: 1px solid #d2def8;
        border-radius: 999px;
        padding: 4px 8px;
        color: #3f5f9e;
        background: #f5f8ff;
        line-height: 1;
    }
    .sa-whatsapp-modal .modal-content {
        border: 0;
        border-radius: 18px;
        max-height: calc(100dvh - 2rem);
        height: calc(100dvh - 2rem);
        overflow: hidden;
        display: flex;
        flex-direction: column;
    }
    .sa-whatsapp-modal .modal-content > form {
        display: flex;
        flex: 1 1 auto;
        flex-direction: column;
        height: 100%;
        max-height: 100%;
        min-height: 0;
    }
    .sa-whatsapp-modal .modal-body {
        flex: 1 1 auto;
        min-height: 0;
        overflow-y: auto;
        -webkit-overflow-scrolling: touch;
    }
    .sa-whatsapp-modal .modal-header {
        background: linear-gradient(135deg, #f5f9ff 0%, #eef4ff 100%);
        border-bottom: 1px solid #d8e4ff;
    }
    .sa-whatsapp-modal .modal-title {
        font-weight: 700;
        color: #2c426f;
    }
    .sa-whatsapp-modal .modal-footer {
        border-top: 1px solid #e4edff;
        background: #f9fbff;
    }
    .sa-whatsapp-modal .sa-modal-provider-badge {
        border: 1px solid #c4d9ff;
        border-radius: 999px;
        padding: 3px 10px;
        font-size: 0.72rem;
        font-weight: 700;
        letter-spacing: 0.03em;
        color: #4063a8;
        text-transform: uppercase;
        background: #ffffff;
    }
    .sa-market-hero {
        border: 1px solid #d8e3f6;
        border-radius: 16px;
        padding: 14px 16px;
        background: linear-gradient(180deg, #ffffff 0%, #f5f8ff 100%);
        box-shadow: 0 10px 24px rgba(22, 40, 76, 0.06);
    }
    .sa-market-title {
        margin: 0;
        font-size: 1.15rem;
        font-weight: 700;
        color: #243a63;
    }
    .sa-market-subtitle {
        margin: 2px 0 0;
        color: #60739b;
        font-size: 0.88rem;
    }
    .sa-market-stats {
        margin-top: 12px;
        display: grid;
        grid-template-columns: repeat(4, minmax(0, 1fr));
        gap: 10px;
    }
    .sa-market-stat {
        border: 1px solid #d4dff4;
        border-radius: 12px;
        padding: 10px;
        background: #fff;
    }
    .sa-market-stat small {
        display: block;
        color: #7a88a8;
        font-size: 0.72rem;
        text-transform: uppercase;
        letter-spacing: 0.03em;
        font-weight: 700;
        line-height: 1.2;
    }
    .sa-market-stat strong {
        display: block;
        margin-top: 4px;
        color: #1f365f;
        font-size: 1rem;
        line-height: 1.15;
    }
    .sa-market-grid {
        margin-top: 14px;
    }
    .sa-market-grid .vx-integration-logo {
        width: 90px;
        height: 68px;
        min-width: 90px;
        min-height: 68px;
        border-radius: 14px;
        font-size: 1.1rem;
    }
    .sa-market-grid .vx-integration-logo img {
        object-fit: contain;
    }
    .sa-market-grid .vx-integration-card {
        min-height: 272px;
    }
    .sa-market-grid .vx-integration-card .card-body {
        gap: 0.55rem;
    }
    .sa-market-grid .vx-integration-description {
        min-height: 38px;
    }
    .sa-market-actions {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        margin-top: auto;
        align-items: center;
        justify-content: space-between;
    }
    .sa-market-link-btn {
        min-width: 110px;
    }
    .sa-market-soft-btn {
        border-radius: 10px;
        font-weight: 600;
    }
    .sa-market-note {
        color: #6e7f9f;
        font-size: 0.78rem;
        line-height: 1.25;
    }
    .sa-market-form-inline .form-control {
        min-height: 38px;
    }
    .sa-market-form-inline .btn {
        min-height: 38px;
    }
    .sa-wa-meta-section .sa-wa-meta-shell {
        border: 1px solid #e2e9f6;
        border-radius: 20px;
        background: linear-gradient(180deg, #fbfdff 0%, #f6f9fd 100%);
        box-shadow: 0 14px 30px rgba(22, 37, 68, 0.08);
    }
    .sa-wa-meta-section .sa-wa-meta-shell > .card-body {
        padding: 1.2rem;
    }
    .sa-wa-meta-section .sa-market-hero {
        border: 1px solid #e5ebf7;
        border-radius: 16px;
        padding: 0.95rem 1rem;
        background: #ffffff;
        box-shadow: none;
    }
    .sa-wa-meta-section .sa-market-title {
        font-size: 1.12rem;
        color: #1f3156;
        letter-spacing: -0.01em;
    }
    .sa-wa-meta-section .sa-market-subtitle {
        margin-top: 0.35rem;
        color: #5f7297;
        font-size: 0.86rem;
        max-width: 64ch;
        line-height: 1.35;
    }
    .sa-wa-meta-section .sa-market-stats {
        margin-top: 0.8rem;
        gap: 8px;
    }
    .sa-wa-meta-section .sa-market-stat {
        border: 1px solid #e5ebf6;
        border-radius: 11px;
        padding: 8px 10px;
        background: #f8fbff;
    }
    .sa-wa-meta-section .sa-market-stat small {
        font-size: 0.68rem;
        color: #6f81a4;
    }
    .sa-wa-meta-section .sa-market-stat strong {
        margin-top: 3px;
        font-size: 0.92rem;
        color: #20355e;
    }
    .sa-wa-meta-section .sa-market-grid {
        margin-top: 0.95rem;
        gap: 0.95rem;
        grid-auto-rows: auto;
    }
    .sa-wa-meta-section .sa-market-grid .vx-integration-card {
        min-height: 248px;
        border-radius: 15px;
        border: 1px solid #e4ebf8;
        background: #ffffff;
        box-shadow: 0 10px 22px rgba(22, 38, 72, 0.06);
    }
    .sa-wa-meta-section .sa-market-grid .vx-integration-card .card-body {
        gap: 0.65rem;
        padding: 0.95rem;
    }
    .sa-wa-meta-section .sa-market-grid .vx-integration-logo {
        width: 62px;
        height: 62px;
        min-width: 62px;
        min-height: 62px;
        border-radius: 13px;
        font-size: 1.2rem;
        border: 1px solid #dfe8f8;
        box-shadow: none;
        background: #f6f9ff;
    }
    .sa-wa-meta-section .sa-market-grid .vx-integration-logo-image {
        background: #ffffff;
        box-shadow: none;
    }
    .sa-wa-meta-section .sa-market-grid .vx-integration-logo img {
        object-fit: contain;
        padding: 8px;
    }
    .sa-wa-meta-section .sa-market-grid .vx-integration-description {
        min-height: 0;
        font-size: 0.84rem;
        color: #5f7297 !important;
        line-height: 1.32;
    }
    .sa-wa-meta-section .sa-market-grid .vx-integration-badges .badge {
        background: #f3f7fd !important;
        border-color: #e2e9f6 !important;
        color: #5a7098;
        font-size: 0.68rem;
        font-weight: 700;
        border-radius: 999px;
        padding: 0.22rem 0.54rem;
    }
    .sa-wa-meta-section .sa-market-grid .vx-integration-metric {
        min-height: 70px;
        border-radius: 10px;
        border-color: #e4eaf7;
        background: #f9fbff;
        padding: 0.52rem 0.6rem;
    }
    .sa-wa-meta-section .sa-market-grid .vx-integration-metric small {
        font-size: 0.66rem;
        color: #7083a7;
    }
    .sa-wa-meta-section .sa-market-grid .vx-integration-metric strong {
        margin-top: 0.18rem;
        font-size: 0.92rem;
        line-height: 1.2;
        color: #1f365f;
        word-break: break-word;
    }
    .sa-wa-meta-section .sa-market-actions {
        margin-top: 0.35rem;
        padding-top: 0.55rem;
        border-top: 1px dashed #e5ecf8;
        gap: 6px;
    }
    .sa-wa-meta-section .vx-integration-state {
        border-radius: 999px;
        font-size: 0.72rem;
        padding: 0.28rem 0.64rem;
    }
    .sa-wa-meta-section .sa-market-soft-btn,
    .sa-wa-meta-section .sa-market-link-btn,
    .sa-wa-meta-section .sa-market-grid .btn {
        border-radius: 10px;
        font-weight: 600;
        font-size: 0.9rem;
        min-height: 36px;
    }
    .sa-wa-meta-section .sa-market-grid .vx-integration-integrate-btn {
        background: linear-gradient(135deg, #29bbd4 0%, #1a90bd 100%);
        box-shadow: 0 8px 14px rgba(27, 146, 191, 0.22);
    }
    .sa-wa-meta-section .sa-market-note {
        font-size: 0.75rem;
        color: #62779f;
    }
    .sa-wa-meta-section .sa-wa-meta-card-test {
        grid-column: 1 / -1;
        min-height: 0;
    }
    .sa-wa-meta-section .sa-wa-meta-card-test .card-body {
        display: grid;
        grid-template-columns: minmax(0, 0.95fr) minmax(0, 1.05fr);
        gap: 0.95rem;
        align-items: start;
    }
    .sa-wa-meta-section .sa-wa-meta-card-test .sa-wa-meta-test-copy {
        min-width: 0;
    }
    .sa-wa-meta-section .sa-wa-meta-card-test .sa-wa-meta-test-form {
        border: 1px solid #e4ebf8;
        border-radius: 12px;
        background: #f9fbff;
        padding: 0.72rem;
    }
    .sa-wa-meta-section .sa-wa-meta-card-test .sa-wa-meta-test-form .form-label {
        font-size: 0.76rem;
        font-weight: 700;
        color: #4b628f;
        text-transform: uppercase;
        letter-spacing: 0.02em;
    }
    .sa-wa-meta-section .sa-wa-meta-card-test .sa-wa-meta-test-form .form-control {
        border-color: #dce6f6;
        background: #ffffff;
    }
    .sa-wa-meta-section .sa-wa-meta-table-shell {
        border: 1px solid #e4ebf7;
        border-radius: 16px;
        box-shadow: none;
        background: #ffffff;
    }
    .sa-wa-meta-section .sa-wa-meta-table-shell .card-body {
        padding: 1rem;
    }
    .sa-wa-meta-section .sa-template-hub {
        border-color: #e4ebf7;
        background: #f9fbff;
    }
    .sa-wa-meta-section .sa-template-path {
        border-color: #d8e4fa;
        background: #ffffff;
    }
    .sa-wa-meta-section .sa-template-kpi {
        border-color: #e2e9f7;
        background: #ffffff;
    }
    .sa-wa-meta-section .sa-template-link-card {
        border-color: #e2e9f7;
        box-shadow: none;
    }
    .sa-wa-meta-section .sa-template-link-card.is-linked {
        background: linear-gradient(180deg, #ffffff 0%, #f4f9ff 100%);
        border-color: #cddcf6;
    }
    .sa-wa-meta-section .sa-template-table thead th {
        font-size: 0.74rem;
        color: #667ba4;
        text-transform: uppercase;
        letter-spacing: 0.03em;
        border-bottom-color: #e5ecf8;
    }
    .sa-wa-meta-section .sa-template-table tbody td {
        border-bottom-color: #eef2fa;
    }
    .sa-correo-modal .modal-content {
        border: 0;
        border-radius: 18px;
        max-height: calc(100dvh - 2rem);
        height: calc(100dvh - 2rem);
        overflow: hidden;
        display: flex;
        flex-direction: column;
    }
    .sa-correo-modal .modal-content > form {
        display: flex;
        flex: 1 1 auto;
        flex-direction: column;
        height: 100%;
        max-height: 100%;
        min-height: 0;
    }
    .sa-correo-modal .modal-body {
        flex: 1 1 auto;
        min-height: 0;
        overflow-y: auto;
        -webkit-overflow-scrolling: touch;
    }
    .sa-correo-modal .modal-header {
        background: linear-gradient(135deg, #fff7ed 0%, #fff2dd 100%);
        border-bottom: 1px solid #f1dec2;
    }
    .sa-correo-modal .modal-footer {
        border-top: 1px solid #eeddc6;
        background: #fffaf3;
    }
    .sa-template-flow {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        margin-bottom: 12px;
    }
    .sa-template-step {
        border: 1px solid #d6e1f8;
        border-radius: 999px;
        padding: 4px 10px;
        font-size: 0.74rem;
        font-weight: 700;
        color: #5f739d;
        background: #f7f9ff;
    }
    .sa-template-step.is-done {
        border-color: #b9dfcb;
        background: #f2fbf5;
        color: #287455;
    }
    .sa-template-step.is-active {
        border-color: #bcd2ff;
        background: #edf4ff;
        color: #335d9f;
    }
    .sa-template-layout {
        display: grid;
        grid-template-columns: 1.2fr 0.8fr;
        gap: 14px;
    }
    .sa-template-editor {
        border: 1px solid #d8e3fb;
        border-radius: 14px;
        background: #ffffff;
        padding: 12px;
    }
    .sa-template-preview {
        border: 1px solid #d8e3fb;
        border-radius: 14px;
        background: linear-gradient(180deg, #f7fbff 0%, #eff5ff 100%);
        padding: 12px;
    }
    .sa-template-phone {
        border-radius: 12px;
        border: 1px solid #d2def8;
        background: #ffffff;
        box-shadow: 0 8px 20px rgba(23, 43, 86, 0.08);
        padding: 11px;
        min-height: 240px;
    }
    .sa-template-phone-title {
        font-weight: 700;
        color: #223f72;
        margin-bottom: 8px;
    }
    .sa-template-phone-header {
        font-weight: 600;
        color: #3b4e79;
        margin-bottom: 6px;
    }
    .sa-template-phone-body {
        white-space: pre-wrap;
        color: #2e3f63;
        margin-bottom: 8px;
        line-height: 1.35;
    }
    .sa-template-phone-footer {
        color: #6f7d99;
        font-size: 0.8rem;
        margin-bottom: 8px;
    }
    .sa-template-phone-button {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        border: 1px solid #b9cbef;
        border-radius: 10px;
        padding: 6px 10px;
        font-size: 0.82rem;
        font-weight: 700;
        color: #345d9d;
        background: #f5f9ff;
        text-decoration: none;
    }
    .sa-template-phone-button.is-hidden {
        display: none;
    }
    .sa-template-status-badge {
        border-radius: 999px;
        padding: 4px 9px;
        font-size: 0.72rem;
        font-weight: 700;
        letter-spacing: 0.02em;
        text-transform: uppercase;
    }
    .sa-template-status-badge.is-pending {
        background: #fff8e8;
        color: #9f7114;
        border: 1px solid #f4dca8;
    }
    .sa-template-status-badge.is-approved {
        background: #edf9f0;
        color: #237347;
        border: 1px solid #b9dfc4;
    }
    .sa-template-status-badge.is-rejected {
        background: #feeff0;
        color: #9f2c33;
        border: 1px solid #efbdc2;
    }
    .sa-template-status-badge.is-error {
        background: #f2f3f8;
        color: #4a5878;
        border: 1px solid #d7dced;
    }
    .sa-template-table td,
    .sa-template-table th {
        vertical-align: middle;
        white-space: nowrap;
    }
    .sa-template-table td.sa-template-cell-wrap {
        white-space: normal;
    }
    .sa-template-table-modern-wrap {
        border: 1px solid #dbe3f4;
        border-radius: 16px;
        background: #ffffff;
        box-shadow: 0 10px 28px rgba(24, 44, 82, 0.06);
    }
    .sa-template-table-modern {
        margin-bottom: 0;
    }
    .sa-template-table-modern thead th {
        background: #f7faff;
        border-bottom-color: #e1e9f7;
        color: #5f7398;
        font-size: 0.72rem;
        letter-spacing: 0.05em;
        text-transform: uppercase;
        font-weight: 700;
        padding: 0.72rem 0.72rem;
    }
    .sa-template-table-modern tbody td {
        border-bottom-color: #edf2fa;
        padding: 0.82rem 0.72rem;
    }
    .sa-template-table-modern tbody tr:last-child td {
        border-bottom: 0;
    }
    .sa-template-table-modern tbody tr:hover {
        background: #f9fbff;
    }
    .sa-template-table-modern-title {
        margin: 0;
        font-size: 1rem;
        line-height: 1.2;
        font-weight: 700;
        letter-spacing: -0.01em;
        color: #1f355f;
        word-break: break-word;
    }
    .sa-template-table-modern-meta {
        margin-top: 0.34rem;
        display: inline-flex;
        align-items: center;
        border: 1px solid #d5dff1;
        border-radius: 999px;
        background: #f7faff;
        color: #64789e;
        font-size: 0.73rem;
        font-weight: 600;
        padding: 0.16rem 0.52rem;
    }
    .sa-template-table-modern-usage {
        margin-top: 0.34rem;
        display: inline-flex;
        align-items: center;
        border: 1px solid #c8d9f8;
        border-radius: 999px;
        background: #edf4ff;
        color: #2c5da7;
        font-size: 0.72rem;
        font-weight: 700;
        padding: 0.16rem 0.5rem;
    }
    .sa-template-table-modern-lang {
        display: inline-flex;
        align-items: center;
        border: 1px solid #d4dff1;
        border-radius: 999px;
        background: #f8fbff;
        color: #38537d;
        font-size: 0.76rem;
        font-weight: 700;
        padding: 0.22rem 0.58rem;
        text-transform: uppercase;
    }
    .sa-template-table-modern-sync {
        min-width: 148px;
    }
    .sa-template-table-modern-sync .sync-date {
        display: block;
        color: #203864;
        font-size: 0.9rem;
        font-weight: 700;
        line-height: 1.2;
    }
    .sa-template-table-modern-sync .sync-time {
        display: block;
        margin-top: 2px;
        color: #7083a7;
        font-size: 0.76rem;
        font-weight: 600;
    }
    .sa-template-table-modern td.sa-template-actions-cell {
        min-width: 380px;
    }
    .sa-template-actions-modern {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        justify-content: flex-end;
        gap: 6px;
    }
    .sa-template-actions-modern .btn {
        border-radius: 999px;
        min-height: 30px;
        min-width: 0;
        padding: 0.36rem 0.72rem;
        font-size: 0.76rem;
        line-height: 1;
        font-weight: 700;
    }
    .sa-template-actions-modern .btn-outline-secondary {
        border-color: #cad7ec;
        color: #4c628c;
    }
    .sa-template-actions-modern .btn-outline-dark {
        border-color: #cfd9ea;
        color: #415a83;
    }
    .sa-template-actions-modern .btn-outline-danger {
        border-color: #ecc7cc;
        color: #a63a47;
    }
    .sa-template-actions-modern .form-control-sm {
        width: 84px;
        min-width: 0;
        border-radius: 999px;
        border-color: #d2dcf0;
        background: #f9fbff;
        text-align: center;
    }
    .sa-template-hub {
        border: 1px solid #dbe6fb;
        border-radius: 16px;
        background: linear-gradient(180deg, #fbfdff 0%, #f3f8ff 100%);
        padding: 14px;
        margin-bottom: 14px;
    }
    .sa-template-hub-title {
        margin: 0 0 4px;
        font-size: 1rem;
        font-weight: 700;
        color: #223e70;
    }
    .sa-template-hub-subtitle {
        margin: 0;
        color: #5f739c;
        font-size: 0.84rem;
    }
    .sa-template-path {
        margin-top: 8px;
        padding: 8px 10px;
        border: 1px dashed #c8d8fb;
        border-radius: 10px;
        background: #ffffff;
        color: #4c6392;
        font-size: 0.78rem;
    }
    .sa-template-kpis {
        margin-top: 10px;
        display: grid;
        grid-template-columns: repeat(4, minmax(0, 1fr));
        gap: 8px;
    }
    .sa-template-kpi {
        border: 1px solid #d7e3fb;
        border-radius: 12px;
        background: #ffffff;
        padding: 8px 10px;
    }
    .sa-template-kpi small {
        display: block;
        font-size: 0.72rem;
        color: #6a7da3;
        text-transform: uppercase;
        letter-spacing: 0.03em;
        font-weight: 700;
    }
    .sa-template-kpi strong {
        display: block;
        margin-top: 2px;
        color: #203a68;
        font-size: 0.94rem;
    }
    .sa-template-link-grid {
        margin-top: 12px;
        display: grid;
        grid-template-columns: repeat(2, minmax(0, 1fr));
        gap: 10px;
    }
    .sa-template-link-card {
        border: 1px solid #d4e0f7;
        border-radius: 14px;
        background: #fff;
        padding: 12px;
        min-height: 128px;
        display: flex;
        flex-direction: column;
        gap: 8px;
        box-shadow: 0 8px 20px rgba(28, 52, 96, 0.06);
    }
    .sa-template-link-card.is-linked {
        border-color: #b9dfc9;
        background: linear-gradient(180deg, #ffffff 0%, #f4fbf6 100%);
    }
    .sa-template-link-card.is-empty {
        border-style: dashed;
        background: #ffffff;
    }
    .sa-template-link-title {
        font-size: 0.78rem;
        text-transform: uppercase;
        letter-spacing: 0.03em;
        color: #64779f;
        font-weight: 700;
        margin: 0;
    }
    .sa-template-link-name {
        margin: 0;
        font-size: 0.95rem;
        color: #1f3760;
        font-weight: 700;
        line-height: 1.2;
    }
    .sa-template-link-meta {
        margin: 0;
        color: #6d7f9f;
        font-size: 0.76rem;
        line-height: 1.2;
    }
    .sa-template-link-status {
        margin: 0;
        font-size: 0.75rem;
        color: #43618d;
        font-weight: 700;
    }
    .sa-template-link-actions {
        margin-top: auto;
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
    }
    .sa-template-link-modal .modal-dialog {
        max-width: 1240px;
    }
    .sa-template-link-modal .modal-content {
        border: 0;
        border-radius: 20px;
        overflow: hidden;
        background: radial-gradient(130% 130% at 100% 0%, #eef4ff 0%, #f7f9ff 45%, #fbfcff 100%);
        box-shadow: 0 26px 60px rgba(15, 32, 66, 0.2);
    }
    .sa-template-link-modal .modal-header {
        border-bottom: 1px solid #e4e9f5;
        background: rgba(255, 255, 255, 0.8);
        backdrop-filter: blur(3px);
        padding: 1rem 1.25rem;
    }
    .sa-template-link-modal .modal-title {
        font-size: 1.22rem;
        letter-spacing: -0.01em;
        color: #1c315f;
    }
    .sa-template-link-modal .modal-body {
        padding: 1.05rem 1.25rem 1rem;
    }
    .sa-template-link-modal .modal-footer {
        border-top: 1px solid #e5eaf8;
        background: rgba(255, 255, 255, 0.84);
    }
    .sa-template-link-intro {
        display: grid;
        grid-template-columns: minmax(0, 1fr) auto;
        gap: 12px;
        border: 1px solid #dce5f7;
        border-radius: 16px;
        background: linear-gradient(132deg, #ffffff 0%, #f4f8ff 100%);
        padding: 0.9rem 1rem;
        margin-bottom: 0.8rem;
    }
    .sa-template-link-kicker {
        display: inline-block;
        border-radius: 999px;
        border: 1px solid #d2dcf3;
        background: #ffffff;
        color: #4a6292;
        font-weight: 700;
        letter-spacing: 0.04em;
        text-transform: uppercase;
        font-size: 0.66rem;
        padding: 0.22rem 0.56rem;
        margin-bottom: 0.42rem;
    }
    .sa-template-link-intro-copy h6 {
        margin: 0 0 2px;
        font-size: 1rem;
        color: #213865;
        font-weight: 700;
    }
    .sa-template-link-intro-copy p {
        margin: 0;
        color: #5f7398;
        font-size: 0.84rem;
    }
    .sa-template-link-steps {
        margin-top: 8px;
        display: flex;
        flex-wrap: wrap;
        gap: 6px;
    }
    .sa-template-link-step {
        border: 1px solid #d8e2f6;
        border-radius: 999px;
        padding: 0.25rem 0.56rem;
        font-size: 0.71rem;
        color: #4f668f;
        background: #ffffff;
        font-weight: 600;
    }
    .sa-template-link-sync-form {
        display: flex;
        align-items: flex-end;
        gap: 8px;
        padding: 0.7rem 0.78rem;
        border-radius: 12px;
        border: 1px solid #d8e2f7;
        background: #ffffff;
    }
    .sa-template-link-sync-form .form-label {
        margin-bottom: 0.25rem;
        font-size: 0.7rem;
        text-transform: uppercase;
        letter-spacing: 0.04em;
        color: #6a7ea3;
        font-weight: 700;
    }
    .sa-template-link-sync-form .form-control {
        width: 92px;
        border-radius: 10px;
        border-color: #d4deef;
        background: #f9fbff;
        font-weight: 600;
    }
    .sa-template-link-sync-form .btn {
        border-radius: 10px;
        font-weight: 700;
        min-height: 36px;
        padding-inline: 0.9rem;
    }
    .sa-template-link-stats {
        display: grid;
        grid-template-columns: repeat(4, minmax(0, 1fr));
        gap: 9px;
        margin-bottom: 0.82rem;
    }
    .sa-template-link-stat {
        border: 1px solid #dbe4f6;
        border-radius: 12px;
        background: #ffffff;
        padding: 0.54rem 0.66rem;
    }
    .sa-template-link-stat small {
        display: block;
        color: #6b7fa3;
        text-transform: uppercase;
        letter-spacing: 0.035em;
        font-size: 0.66rem;
        font-weight: 700;
    }
    .sa-template-link-stat strong {
        display: block;
        margin-top: 1px;
        color: #203764;
        font-size: 0.95rem;
        line-height: 1.15;
    }
    .sa-template-link-table-wrap {
        border: 1px solid #dbe3f5;
        border-radius: 16px;
        background: #ffffff;
        box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.5);
    }
    .sa-template-link-table-wrap .sa-template-table {
        margin-bottom: 0;
    }
    .sa-template-link-table-wrap .sa-template-table thead th {
        position: sticky;
        top: 0;
        z-index: 1;
        border-bottom-color: #e2e8f6;
        background: #f8faff;
        font-size: 0.7rem;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        color: #5f7399;
        padding: 0.7rem 0.72rem;
    }
    .sa-template-link-table-wrap .sa-template-table tbody td {
        border-bottom-color: #edf1f8;
        padding: 0.7rem 0.72rem;
    }
    .sa-template-link-table-wrap .sa-template-table tbody tr:last-child td {
        border-bottom: 0;
    }
    .sa-template-link-table-wrap .sa-template-table tbody tr:hover {
        background: #f8fbff;
    }
    .sa-wa-template-center-shell {
        border: 1px solid #dde6f7;
        border-radius: 20px;
        background: linear-gradient(180deg, #fbfcff 0%, #f4f8ff 100%);
        box-shadow: 0 18px 34px rgba(27, 45, 83, 0.09);
    }
    .sa-wa-template-center-shell > .card-body {
        padding: 1.2rem;
    }
    .sa-wa-template-center-hero {
        display: grid;
        grid-template-columns: minmax(0, 1fr) auto;
        gap: 0.9rem;
        border: 1px solid #dce6fa;
        border-radius: 16px;
        background: #ffffff;
        padding: 0.95rem 1rem;
    }
    .sa-wa-template-center-hero h2 {
        margin: 0 0 0.2rem;
        font-size: 1.15rem;
        color: #20355f;
        letter-spacing: -0.01em;
    }
    .sa-wa-template-center-hero p {
        margin: 0;
        color: #5b7098;
        font-size: 0.86rem;
    }
    .sa-wa-template-center-actions {
        display: flex;
        flex-wrap: wrap;
        align-items: flex-end;
        justify-content: flex-end;
        gap: 0.5rem;
    }
    .sa-wa-template-center-sync {
        display: flex;
        align-items: flex-end;
        gap: 0.35rem;
        border: 1px solid #dce5f8;
        border-radius: 11px;
        background: #f8fbff;
        padding: 0.35rem 0.45rem;
    }
    .sa-wa-template-center-sync .form-label {
        margin-bottom: 0.12rem;
        font-size: 0.66rem;
        text-transform: uppercase;
        letter-spacing: 0.04em;
        color: #647a9f;
        font-weight: 700;
    }
    .sa-wa-template-center-sync .form-control {
        width: 86px;
        border-radius: 9px;
        border-color: #d2ddf2;
        background: #ffffff;
        font-weight: 600;
    }
    .sa-wa-template-center-kpis {
        margin-top: 0.82rem;
        display: grid;
        grid-template-columns: repeat(5, minmax(0, 1fr));
        gap: 0.5rem;
    }
    .sa-wa-template-center-kpi {
        border: 1px solid #dde6f9;
        border-radius: 12px;
        background: #ffffff;
        padding: 0.55rem 0.65rem;
    }
    .sa-wa-template-center-kpi small {
        display: block;
        font-size: 0.68rem;
        text-transform: uppercase;
        letter-spacing: 0.04em;
        font-weight: 700;
        color: #647a9f;
    }
    .sa-wa-template-center-kpi strong {
        display: block;
        margin-top: 0.12rem;
        font-size: 1rem;
        color: #1f3764;
        line-height: 1.15;
    }
    .sa-wa-template-center-panel {
        border: 1px solid #dce6fa;
        border-radius: 14px;
        background: #ffffff;
        padding: 0.9rem;
        box-shadow: 0 8px 20px rgba(24, 42, 79, 0.05);
    }
    .sa-wa-template-center-panel h3 {
        margin: 0 0 0.25rem;
        font-size: 0.98rem;
        color: #213865;
    }
    .sa-wa-template-center-panel p {
        margin: 0;
        color: #60739a;
        font-size: 0.82rem;
    }
    .sa-wa-template-center-schedule-list {
        margin-top: 0.75rem;
        display: grid;
        gap: 0.48rem;
    }
    .sa-wa-template-center-schedule-row {
        display: grid;
        grid-template-columns: minmax(0, 1fr) 116px;
        gap: 0.5rem;
        align-items: center;
        border: 1px solid #e2e8f8;
        border-radius: 10px;
        background: #f9fbff;
        padding: 0.42rem 0.52rem;
    }
    .sa-wa-template-center-schedule-row strong {
        display: block;
        font-size: 0.83rem;
        color: #1f3765;
        line-height: 1.2;
    }
    .sa-wa-template-center-schedule-row small {
        display: block;
        font-size: 0.72rem;
        color: #6c7f9f;
        line-height: 1.15;
    }
    .sa-wa-template-center-schedule-row input[type="time"] {
        width: 100%;
        border-radius: 9px;
        border: 1px solid #cfdcf3;
        background: #ffffff;
        min-height: 34px;
        padding: 0.3rem 0.46rem;
        font-weight: 700;
        color: #29406d;
    }
    .sa-wa-template-center-table-wrap {
        margin-top: 0.7rem;
        border: 1px solid #dde6f8;
        border-radius: 13px;
        overflow: hidden;
    }
    .sa-wa-template-center-table-wrap .table {
        margin-bottom: 0;
    }
    .sa-wa-template-center-table-wrap thead th {
        border-bottom-color: #e2e9f8;
        background: #f7faff;
        font-size: 0.7rem;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        color: #5e7399;
        padding: 0.64rem 0.65rem;
    }
    .sa-wa-template-center-table-wrap tbody td {
        border-bottom-color: #edf2fa;
        padding: 0.64rem 0.65rem;
        font-size: 0.84rem;
        color: #28406e;
    }
    .sa-wa-template-center-table-wrap tbody tr:last-child td {
        border-bottom: 0;
    }
    .sa-wa-template-center-name {
        font-size: 0.94rem;
        font-weight: 700;
        color: #1f3764;
        line-height: 1.25;
    }
    .sa-wa-template-center-meta {
        display: inline-flex;
        margin-top: 0.2rem;
        border-radius: 999px;
        border: 1px solid #d8e1f5;
        background: #f9fbff;
        padding: 0.12rem 0.45rem;
        font-size: 0.68rem;
        color: #64789f;
        font-weight: 600;
    }
    .sa-wa-template-center-time {
        display: inline-flex;
        border-radius: 999px;
        border: 1px solid #d3def5;
        background: #f7faff;
        color: #35507d;
        font-size: 0.76rem;
        font-weight: 700;
        padding: 0.16rem 0.55rem;
    }
    .sa-wa-template-center-overflow {
        margin-top: 0.5rem;
        font-size: 0.77rem;
        color: #63779e;
    }
    .sa-wa-center-detail-modal .modal-dialog {
        max-width: 860px;
    }
    .sa-wa-center-detail-modal .modal-content {
        border: 0;
        border-radius: 18px;
        overflow: hidden;
    }
    .sa-wa-center-detail-modal .modal-header {
        background: linear-gradient(132deg, #f2f7ff 0%, #ffffff 100%);
        border-bottom: 1px solid #e3ebf8;
    }
    .sa-wa-center-detail-modal .modal-body {
        padding: 1rem;
    }
    .sa-wa-center-detail-grid {
        display: grid;
        grid-template-columns: repeat(2, minmax(0, 1fr));
        gap: 0.7rem;
    }
    .sa-wa-center-detail-card {
        border: 1px solid #dce6f9;
        border-radius: 12px;
        background: #ffffff;
        padding: 0.72rem;
    }
    .sa-wa-center-detail-card h6 {
        margin: 0 0 0.32rem;
        font-size: 0.86rem;
        color: #29426f;
    }
    .sa-wa-center-detail-card p {
        margin: 0;
        font-size: 0.79rem;
        color: #5f7399;
        line-height: 1.34;
        white-space: pre-wrap;
    }
    .sa-wa-center-action-stack {
        display: flex;
        flex-wrap: wrap;
        gap: 0.42rem;
    }
    .sa-wa-center-send-now {
        margin-top: 0.58rem;
        padding-top: 0.58rem;
        border-top: 1px dashed #dce6f8;
    }
    .sa-wa-center-send-now .form-label {
        font-size: 0.72rem;
        color: #5f7398;
        font-weight: 700;
        text-transform: uppercase;
        letter-spacing: 0.03em;
    }
    .sa-wa-center-send-now .form-control {
        border-color: #d5e0f5;
        font-size: 0.83rem;
    }
    .sa-template-table td,
    .sa-template-table th {
        vertical-align: middle;
        white-space: nowrap;
    }
    .sa-template-table td.sa-template-cell-wrap {
        white-space: normal;
        min-width: 226px;
    }
    .sa-template-table-title {
        display: block;
        margin: 0;
        font-size: 1rem;
        line-height: 1.2;
        font-weight: 700;
        color: #1f335e;
        letter-spacing: -0.01em;
        word-break: break-word;
    }
    .sa-template-meta-id {
        display: inline-flex;
        margin-top: 4px;
        border-radius: 999px;
        border: 1px solid #d6dff0;
        background: #f8faff;
        padding: 2px 8px;
        font-size: 0.72rem;
        color: #5f7397;
        font-weight: 600;
    }
    .sa-template-language-chip {
        display: inline-flex;
        align-items: center;
        border-radius: 999px;
        border: 1px solid #d8e1f2;
        background: #f8fbff;
        padding: 0.24rem 0.56rem;
        color: #34527f;
        font-size: 0.74rem;
        font-weight: 700;
        text-transform: uppercase;
    }
    .sa-template-state-detail {
        display: block;
        margin-top: 0.25rem;
        color: #6d7e9f;
        font-size: 0.74rem;
        line-height: 1.25;
        white-space: normal;
        max-width: 240px;
    }
    .sa-template-usage-badge,
    .sa-template-usage-free {
        display: inline-flex;
        align-items: center;
        border-radius: 999px;
        border: 1px solid #d2dcf0;
        background: #f6f9ff;
        padding: 0.24rem 0.58rem;
        color: #3d5884;
        font-size: 0.74rem;
        font-weight: 700;
    }
    .sa-template-usage-badge {
        border-color: #bdd4ff;
        background: #edf4ff;
        color: #2f5ea9;
    }
    .sa-template-actions {
        display: grid;
        gap: 6px;
        justify-items: end;
    }
    .sa-template-actions-main,
    .sa-template-actions-secondary {
        display: flex;
        gap: 6px;
        flex-wrap: wrap;
        justify-content: flex-end;
    }
    .sa-template-actions .btn {
        border-radius: 999px;
        min-height: 30px;
        min-width: 0;
        font-size: 0.76rem;
        font-weight: 700;
        line-height: 1;
        padding: 0.42rem 0.72rem;
    }
    .sa-template-actions .form-control-sm {
        min-width: 0;
        width: 84px;
        border-radius: 999px;
        border-color: #d2dcf0;
        background: #f9fbff;
        text-align: center;
    }
    .sa-template-actions .btn-outline-dark {
        border-color: #ccd8eb;
        color: #3f567e;
    }
    .sa-template-actions .btn-outline-danger {
        border-color: #ecc8ce;
        color: #a63c49;
    }
    .sa-template-actions .btn-outline-secondary {
        border-color: #ccd8eb;
        color: #4b638d;
    }
    .sa-template-mobile-list {
        display: none;
    }
    .sa-template-mobile-card {
        border: 1px solid #d9e3f6;
        border-radius: 14px;
        background: linear-gradient(150deg, #ffffff 0%, #f9fbff 100%);
        padding: 12px;
        margin-bottom: 10px;
        box-shadow: 0 8px 20px rgba(24, 42, 81, 0.08);
    }
    .sa-template-mobile-head {
        display: flex;
        align-items: flex-start;
        justify-content: space-between;
        gap: 8px;
        margin-bottom: 8px;
    }
    .sa-template-mobile-title {
        margin: 0;
        font-size: 0.96rem;
        color: #1f3967;
        font-weight: 700;
    }
    .sa-template-mobile-meta {
        margin: 0;
        color: #6d7f9f;
        font-size: 0.76rem;
    }
    .sa-template-mobile-chips {
        display: flex;
        flex-wrap: wrap;
        gap: 6px;
        margin-bottom: 8px;
    }
    .sa-template-mobile-chip {
        border: 1px solid #d5dff4;
        border-radius: 999px;
        padding: 3px 8px;
        font-size: 0.72rem;
        color: #50638d;
        background: #f6f9ff;
        font-weight: 600;
    }
    .sa-template-mobile-actions {
        display: grid;
        grid-template-columns: repeat(2, minmax(0, 1fr));
        gap: 6px;
    }
    .sa-template-mobile-actions .btn-sm {
        width: 100%;
        border-radius: 999px;
    }
    .sa-template-mobile-actions .form-control-sm {
        width: 100%;
        border-radius: 999px;
    }
    @media (max-width: 1199.98px) {
        .sa-brand-grid {
            grid-template-columns: repeat(3, minmax(0, 1fr));
        }
        .sa-market-stats {
            grid-template-columns: repeat(2, minmax(0, 1fr));
        }
        .sa-template-kpis {
            grid-template-columns: repeat(2, minmax(0, 1fr));
        }
        .sa-template-table-modern td.sa-template-actions-cell {
            min-width: 320px;
        }
        .sa-wa-template-center-kpis {
            grid-template-columns: repeat(3, minmax(0, 1fr));
        }
        .sa-wa-template-center-hero {
            grid-template-columns: 1fr;
        }
        .sa-wa-template-center-actions {
            justify-content: flex-start;
        }
    }
    @media (max-width: 991.98px) {
        .sa-ops-layout {
            grid-template-columns: 1fr;
        }
        .sa-template-layout {
            grid-template-columns: 1fr;
        }
        .sa-template-link-intro {
            grid-template-columns: 1fr;
        }
        .sa-template-link-sync-form {
            justify-content: space-between;
        }
        .sa-template-link-stats {
            grid-template-columns: repeat(2, minmax(0, 1fr));
        }
        .sa-template-link-grid {
            grid-template-columns: 1fr;
        }
        .sa-wa-meta-section .sa-wa-meta-card-test .card-body {
            grid-template-columns: 1fr;
        }
        .sa-wa-center-detail-grid {
            grid-template-columns: 1fr;
        }
    }
    @media (max-width: 767.98px) {
        .sa-brand-grid {
            grid-template-columns: repeat(2, minmax(0, 1fr));
        }
        .sa-mini-integration-list {
            grid-template-columns: 1fr;
        }
        .sa-market-stats {
            grid-template-columns: 1fr;
        }
        .sa-template-table-wrap {
            display: none;
        }
        .sa-template-mobile-list {
            display: block;
        }
        .sa-template-mobile-actions {
            grid-template-columns: 1fr;
        }
        .sa-template-link-stats {
            grid-template-columns: 1fr;
        }
        .sa-wa-meta-section .sa-wa-meta-shell > .card-body {
            padding: 0.9rem;
        }
        .sa-wa-meta-section .sa-market-grid .vx-integration-card {
            min-height: 0;
        }
        .sa-wa-meta-section .sa-market-actions {
            flex-direction: column;
            align-items: stretch;
        }
        .sa-wa-meta-section .sa-market-actions .btn {
            width: 100%;
        }
        .sa-wa-template-center-shell > .card-body {
            padding: 0.85rem;
        }
        .sa-wa-template-center-kpis {
            grid-template-columns: repeat(2, minmax(0, 1fr));
        }
        .sa-wa-template-center-sync {
            width: 100%;
            justify-content: space-between;
        }
        .sa-wa-template-center-schedule-row {
            grid-template-columns: 1fr;
        }
        .sa-whatsapp-modal .modal-content,
        .sa-correo-modal .modal-content {
            height: calc(100dvh - 1rem);
            max-height: calc(100dvh - 1rem);
            border-radius: 14px;
        }
    }
</style>

<div class="sa-section <?= $superadminSection === 'resumen' ? 'is-active' : '' ?>" data-sa-section="resumen">
<div class="row g-3 mb-4">
    <div class="col-md-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <span class="metric-label">Empresas</span>
                <h2 class="h4 mb-0"><?= e((string) ($stats['empresas'] ?? 0)) ?></h2>
                <small class="text-muted">Activas: <?= e((string) ($stats['empresas_activas'] ?? 0)) ?></small>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <span class="metric-label">Suspendidas/Bloqueadas</span>
                <h2 class="h4 mb-0"><?= e((string) (($stats['empresas_suspendidas'] ?? 0) + ($stats['empresas_bloqueadas'] ?? 0))) ?></h2>
                <small class="text-muted">Suspendidas: <?= e((string) ($stats['empresas_suspendidas'] ?? 0)) ?> | Bloqueadas: <?= e((string) ($stats['empresas_bloqueadas'] ?? 0)) ?></small>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <span class="metric-label">Suscripciones</span>
                <h2 class="h4 mb-0"><?= e((string) ($stats['suscripciones_activas'] ?? 0)) ?></h2>
                <small class="text-muted">En alerta: <?= e((string) ($stats['suscripciones_alerta'] ?? 0)) ?></small>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <span class="metric-label">Ingresos del mes</span>
                <h2 class="h4 mb-0"><?= e(money($stats['ingresos_mes'] ?? 0)) ?></h2>
                <small class="text-muted">Pagos pendientes: <?= e((string) ($stats['pagos_pendientes'] ?? 0)) ?></small>
            </div>
        </div>
    </div>
</div>

<div class="row g-3 mb-4">
    <div class="col-md-4">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <span class="metric-label">Cobros SaaS pendientes</span>
                <h2 class="h4 mb-0"><?= e((string) ($stats['notices_pending'] ?? 0)) ?></h2>
                <small class="text-muted">Con error: <?= e((string) ($stats['notices_error'] ?? 0)) ?></small>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <span class="metric-label">Tickets abiertos</span>
                <h2 class="h4 mb-0"><?= e((string) ($stats['support_open'] ?? 0)) ?></h2>
                <small class="text-muted">Total en rango SLA: <?= e((string) ($supportSlaSummary['total_tickets'] ?? 0)) ?></small>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <span class="metric-label">SLA incumplido</span>
                <h2 class="h4 mb-0">
                    <?= e((string) (((int) ($supportSlaSummary['primera_respuesta_incumplida'] ?? 0)) + ((int) ($supportSlaSummary['resolucion_incumplida'] ?? 0)))) ?>
                </h2>
                <small class="text-muted">
                    Primera: <?= e((string) ($supportSlaSummary['primera_respuesta_incumplida'] ?? 0)) ?>
                    | Resolución: <?= e((string) ($supportSlaSummary['resolucion_incumplida'] ?? 0)) ?>
                </small>
            </div>
        </div>
    </div>
</div>

<div class="card border-0 shadow-sm mb-4">
    <div class="card-body d-flex flex-wrap align-items-center justify-content-between gap-2">
        <div>
            <h2 class="h5 mb-1">Automatización de suscripciones</h2>
            <small class="text-muted">Ejecuta la validación diaria de vencidas/morosas, bloqueo y avisos de cobro.</small>
        </div>
        <div class="d-flex flex-wrap gap-2">
            <form action="<?= e(url('superadmin/suscripciones/automatizacion/ejecutar')) ?>" method="post" class="m-0">
                <?= csrf_field() ?>
                <button class="btn btn-outline-primary" type="submit">Ejecutar ahora</button>
            </form>
            <form action="<?= e(url('superadmin/suscripciones/avisos/reintentar')) ?>" method="post" class="m-0 d-flex gap-2">
                <?= csrf_field() ?>
                <input type="hidden" name="limit" value="200">
                <button class="btn btn-outline-secondary" type="submit">Reintentar avisos</button>
            </form>
        </div>
    </div>
</div>
</div>

<div class="sa-section <?= $superadminSection === 'wompi' ? 'is-active' : '' ?>" data-sa-section="wompi">
<div class="card border-0 shadow-sm mb-4">
    <div class="card-body">
        <h2 class="h5 mb-3">Configuración Wompi (Superadmin)</h2>
        <div class="row g-3 mb-3">
            <div class="col-md-4">
                <div class="p-3 rounded border bg-light">
                    <small class="text-muted d-block">Public Key</small>
                    <strong><?= e((string) ($wompi['public_key_masked'] ?? 'No configurada')) ?></strong>
                    <div class="mt-2">
                        <span class="badge <?= !empty($wompi['has_public_key']) ? 'text-bg-success' : 'text-bg-secondary' ?>">
                            <?= !empty($wompi['has_public_key']) ? 'Configurada' : 'Pendiente' ?>
                        </span>
                    </div>
                    <form action="<?= e(url('superadmin/wompi-config/limpiar')) ?>" method="post" class="mt-2" onsubmit="return confirm('¿Limpiar WOMPI_PUBLIC_KEY?');">
                        <?= csrf_field() ?>
                        <input type="hidden" name="key" value="public">
                        <button class="btn btn-sm btn-outline-danger" type="submit">Limpiar llave</button>
                    </form>
                </div>
            </div>
            <div class="col-md-4">
                <div class="p-3 rounded border bg-light">
                    <small class="text-muted d-block">Integrity Secret</small>
                    <strong><?= e((string) ($wompi['integrity_secret_masked'] ?? 'No configurada')) ?></strong>
                    <div class="mt-2">
                        <span class="badge <?= !empty($wompi['has_integrity_secret']) ? 'text-bg-success' : 'text-bg-secondary' ?>">
                            <?= !empty($wompi['has_integrity_secret']) ? 'Configurada' : 'Pendiente' ?>
                        </span>
                    </div>
                    <form action="<?= e(url('superadmin/wompi-config/limpiar')) ?>" method="post" class="mt-2" onsubmit="return confirm('¿Limpiar WOMPI_INTEGRITY_SECRET?');">
                        <?= csrf_field() ?>
                        <input type="hidden" name="key" value="integrity">
                        <button class="btn btn-sm btn-outline-danger" type="submit">Limpiar llave</button>
                    </form>
                </div>
            </div>
            <div class="col-md-4">
                <div class="p-3 rounded border bg-light">
                    <small class="text-muted d-block">Events Secret</small>
                    <strong><?= e((string) ($wompi['events_secret_masked'] ?? 'No configurada')) ?></strong>
                    <div class="mt-2">
                        <span class="badge <?= !empty($wompi['has_events_secret']) ? 'text-bg-success' : 'text-bg-secondary' ?>">
                            <?= !empty($wompi['has_events_secret']) ? 'Configurada' : 'Pendiente' ?>
                        </span>
                    </div>
                    <form action="<?= e(url('superadmin/wompi-config/limpiar')) ?>" method="post" class="mt-2" onsubmit="return confirm('¿Limpiar WOMPI_EVENTS_SECRET?');">
                        <?= csrf_field() ?>
                        <input type="hidden" name="key" value="events">
                        <button class="btn btn-sm btn-outline-danger" type="submit">Limpiar llave</button>
                    </form>
                </div>
            </div>
        </div>

        <div class="alert <?= !empty($wompi['checkout_configured']) ? 'alert-success' : 'alert-warning' ?> py-2 mb-2">
            Checkout: <?= !empty($wompi['checkout_configured']) ? 'Listo (public + integrity configuradas).' : 'Falta configurar public key e integrity secret.' ?>
        </div>
        <div class="alert <?= !empty($wompi['webhook_configured']) ? 'alert-success' : 'alert-warning' ?> py-2 mb-3">
            Webhook: <?= !empty($wompi['webhook_configured']) ? 'Listo (events secret configurada).' : 'Falta configurar events secret.' ?>
            <br>
            <small>URL webhook: <code><?= e((string) ($wompi['webhook_url'] ?? '')) ?></code></small>
        </div>
        <div class="alert alert-info py-2 mb-3">
            Redirect checkout actual:
            <code><?= e((string) ($wompi['redirect_url_effective'] ?? url('login'))) ?></code>
            <br>
            <small><?= !empty($wompi['has_custom_redirect_url']) ? 'Personalizado en configuración global.' : 'Usando fallback automático al login de la app.' ?></small>
        </div>

        <form action="<?= e(url('superadmin/wompi-config')) ?>" method="post" class="row g-2">
            <?= csrf_field() ?>
            <div class="col-md-4">
                <label class="form-label">WOMPI_PUBLIC_KEY</label>
                <input type="password" class="form-control" name="wompi_public_key" autocomplete="off" placeholder="pub_test_...">
            </div>
            <div class="col-md-4">
                <label class="form-label">WOMPI_INTEGRITY_SECRET</label>
                <input type="password" class="form-control" name="wompi_integrity_secret" autocomplete="off" placeholder="integrity secret...">
            </div>
            <div class="col-md-4">
                <label class="form-label">WOMPI_EVENTS_SECRET</label>
                <input type="password" class="form-control" name="wompi_events_secret" autocomplete="off" placeholder="events secret...">
            </div>
            <div class="col-md-12">
                <label class="form-label">WOMPI_REDIRECT_URL (producción)</label>
                <input
                    type="url"
                    class="form-control"
                    name="wompi_redirect_url"
                    autocomplete="off"
                    value="<?= e((string) ($wompi['redirect_url'] ?? '')) ?>"
                    placeholder="https://app.tudominio.com/veltrix/public/login?empresa=hunolabs"
                >
                <small class="text-muted">Si lo defines, todos los links de pago usarán este dominio en `redirect-url`.</small>
            </div>
            <div class="col-12">
                <small class="text-muted">Deja en blanco cualquier campo que no quieras modificar.</small>
            </div>
            <div class="col-12 d-flex flex-wrap gap-2">
                <button class="btn btn-primary" type="submit">Guardar configuración Wompi</button>
                <button class="btn btn-outline-primary" type="submit" formaction="<?= e(url('superadmin/wompi-config/probar')) ?>" formmethod="post">
                    Probar conexión Wompi
                </button>
                <button class="btn btn-outline-danger" type="submit" formaction="<?= e(url('superadmin/wompi-config/limpiar')) ?>" formmethod="post" name="key" value="redirect" onclick="return confirm('¿Limpiar WOMPI_REDIRECT_URL?');">
                    Limpiar redirect URL
                </button>
            </div>
        </form>
        <small class="text-muted d-block mt-2">La prueba valida conectividad con Wompi y reconocimiento de la llave pública.</small>
    </div>
</div>
</div>

<div class="sa-section <?= $superadminSection === 'correo' ? 'is-active' : '' ?>" data-sa-section="correo">
<div class="card border-0 shadow-sm mb-4">
    <div class="card-body">
        <div class="sa-market-hero mb-3">
            <h2 class="sa-market-title">Correo electrónico</h2>
            <p class="sa-market-subtitle">Administra SMTP, remitentes y pruebas desde cards modulares.</p>
            <div class="sa-market-stats">
                <div class="sa-market-stat">
                    <small>Estado SMTP</small>
                    <strong><?= !empty($smtpConfig['is_ready']) ? 'Listo' : 'Pendiente' ?></strong>
                </div>
                <div class="sa-market-stat">
                    <small>Servidor</small>
                    <strong><?= e(($smtpHost !== '' ? $smtpHost : 'Sin host') . ':' . ($smtpPort !== '' ? $smtpPort : '587')) ?></strong>
                </div>
                <div class="sa-market-stat">
                    <small>Seguridad</small>
                    <strong><?= e(strtoupper($smtpSecure)) ?></strong>
                </div>
                <div class="sa-market-stat">
                    <small>Canal Email</small>
                    <strong><?= !empty($notificationConfig['channel_email']) ? 'Activo' : 'Desactivado' ?></strong>
                </div>
            </div>
        </div>

        <div class="vx-integrations-grid sa-market-grid">
            <article class="card border-0 shadow-sm vx-integration-card vx-integration-card-main">
                <div class="card-body">
                    <div class="d-flex align-items-start gap-3">
                        <span class="vx-integration-logo vx-integration-logo-image" aria-hidden="true">
                            <img src="<?= e($gmailLogo) ?>" alt="Gmail">
                        </span>
                        <div>
                            <h2 class="h5 mb-1">Integración SMTP</h2>
                            <p class="text-muted mb-0 vx-integration-description">Configura host, puerto, seguridad y credenciales en modal.</p>
                        </div>
                    </div>
                    <div class="d-flex flex-wrap gap-2 vx-integration-badges">
                        <span class="badge text-bg-light border">Integración</span>
                    </div>
                    <div class="row g-2">
                        <div class="col-6">
                            <div class="vx-integration-metric">
                                <small>Credenciales</small>
                                <strong><?= !empty($smtpConfig['password_masked']) ? 'Configuradas' : 'Pendientes' ?></strong>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="vx-integration-metric">
                                <small>Estado</small>
                                <strong><?= !empty($smtpConfig['is_ready']) ? 'Operativo' : 'Revisar' ?></strong>
                            </div>
                        </div>
                    </div>
                    <div class="sa-market-actions">
                        <span class="badge vx-integration-state <?= !empty($smtpConfig['is_ready']) ? 'is-active' : 'is-inactive' ?>">
                            <?= !empty($smtpConfig['is_ready']) ? 'Activo' : 'Inactivo' ?>
                        </span>
                        <button class="btn btn-primary vx-integration-integrate-btn sa-market-link-btn" type="button" data-bs-toggle="modal" data-bs-target="#saCorreoSmtpModal">
                            <i class="bx bx-link-alt me-1"></i>Integrar
                        </button>
                    </div>
                </div>
            </article>

            <article class="card border-0 shadow-sm vx-integration-card vx-integration-card-main">
                <div class="card-body">
                    <div class="d-flex align-items-start gap-3">
                        <span class="vx-integration-logo vx-integration-logo-muted" aria-hidden="true">
                            <i class="bx bx-paper-plane"></i>
                        </span>
                        <div>
                            <h2 class="h5 mb-1">Remitente transaccional</h2>
                            <p class="text-muted mb-0 vx-integration-description">Define el email y nombre que verán los clientes en avisos.</p>
                        </div>
                    </div>
                    <div class="d-flex flex-wrap gap-2 vx-integration-badges">
                        <span class="badge text-bg-light border">Identidad de envío</span>
                    </div>
                    <div class="row g-2">
                        <div class="col-6">
                            <div class="vx-integration-metric">
                                <small>From</small>
                                <strong><?= e($smtpFromEmail !== '' ? $smtpFromEmail : 'No definido') ?></strong>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="vx-integration-metric">
                                <small>Nombre</small>
                                <strong><?= e($smtpFromName !== '' ? $smtpFromName : 'Veltrix POS') ?></strong>
                            </div>
                        </div>
                    </div>
                    <div class="sa-market-actions">
                        <span class="badge vx-integration-state <?= $gmailConfigured ? 'is-active' : 'is-inactive' ?>">
                            <?= $gmailConfigured ? 'Listo' : 'Pendiente' ?>
                        </span>
                        <a class="btn btn-outline-primary sa-market-soft-btn" href="<?= e(url('superadmin') . '?seccion=notificaciones') ?>">
                            Ajustar en hub
                        </a>
                    </div>
                </div>
            </article>

            <article class="card border-0 shadow-sm vx-integration-card vx-integration-card-main">
                <div class="card-body">
                    <div class="d-flex align-items-start gap-3">
                        <span class="vx-integration-logo vx-integration-logo-muted" aria-hidden="true">
                            <i class="bx bx-send"></i>
                        </span>
                        <div>
                            <h2 class="h5 mb-1">Prueba SMTP</h2>
                            <p class="text-muted mb-0 vx-integration-description">Envía un correo de verificación con la configuración actual guardada.</p>
                        </div>
                    </div>
                    <div class="d-flex flex-wrap gap-2 vx-integration-badges">
                        <span class="badge text-bg-light border">QA</span>
                    </div>
                    <form action="<?= e(url('superadmin/correo-config/probar')) ?>" method="post" class="sa-market-form-inline">
                        <?= csrf_field() ?>
                        <label class="form-label mb-1">Correo destino</label>
                        <div class="d-flex gap-2">
                            <input type="email" class="form-control" name="smtp_test_email" value="<?= e((string) ($smtpConfig['test_email_default'] ?? '')) ?>" placeholder="destino@correo.com">
                            <button class="btn btn-outline-primary" type="submit">Probar</button>
                        </div>
                    </form>
                    <p class="sa-market-note mb-0">Tip: para Gmail usa contraseña de aplicación, puerto <code>587</code> y seguridad <code>tls</code>.</p>
                </div>
            </article>

        </div>
    </div>
</div>
</div>

<div class="sa-section <?= $superadminSection === 'notificaciones' ? 'is-active' : '' ?>" data-sa-section="notificaciones">
<div class="card border-0 shadow-sm mb-4">
    <div class="card-body">
        <div class="d-flex flex-wrap align-items-start justify-content-between gap-2 mb-3">
            <div>
                <h2 class="h5 mb-1">Hub de integraciones</h2>
                <p class="text-muted mb-0">Gestiona proveedores por tarjeta y separa Meta Cloud API de ManyChat para operar con claridad.</p>
            </div>
        </div>

        <div class="sa-brand-grid mb-4">
            <div class="sa-brand-chip <?= $gmailConfigured ? 'is-ready' : '' ?>">
                <div class="sa-brand-chip-head">
                    <span class="sa-brand-chip-logo"><img src="<?= e($gmailLogo) ?>" alt="Gmail"></span>
                    <div>
                        <p class="sa-brand-chip-title">Gmail / SMTP</p>
                        <p class="sa-brand-chip-subtitle">Canal correo</p>
                    </div>
                </div>
                <div class="sa-brand-chip-status">
                    <span class="badge <?= $gmailConfigured ? 'text-bg-success' : 'text-bg-warning' ?>"><?= $gmailConfigured ? 'Listo' : 'Pendiente' ?></span>
                </div>
            </div>
            <div class="sa-brand-chip <?= $metaConfigured ? 'is-ready' : '' ?> <?= $metaProviderActive ? 'is-active' : '' ?>">
                <div class="sa-brand-chip-head">
                    <span class="sa-brand-chip-logo"><img src="<?= e($metaLogo) ?>" alt="Meta"></span>
                    <div>
                        <p class="sa-brand-chip-title">Meta Cloud API</p>
                        <p class="sa-brand-chip-subtitle">WhatsApp oficial</p>
                    </div>
                </div>
                <div class="sa-brand-chip-status d-flex gap-2">
                    <span class="badge <?= $metaProviderActive ? 'text-bg-primary' : 'text-bg-secondary' ?>"><?= $metaProviderActive ? 'Activo' : 'Inactivo' ?></span>
                    <span class="badge <?= $metaConfigured ? 'text-bg-success' : 'text-bg-warning' ?>"><?= $metaConfigured ? 'Credenciales OK' : 'Faltan datos' ?></span>
                </div>
                <div class="sa-brand-chip-actions">
                    <button class="btn btn-sm btn-outline-primary" type="button" data-bs-toggle="modal" data-bs-target="#saWhatsAppMetaModal">
                        Configurar Meta
                    </button>
                </div>
            </div>
            <div class="sa-brand-chip <?= $manyChatConfigured ? 'is-ready' : '' ?> <?= $manyChatProviderActive ? 'is-active' : '' ?>">
                <div class="sa-brand-chip-head">
                    <span class="sa-brand-chip-logo"><i class="bx bx-chat"></i></span>
                    <div>
                        <p class="sa-brand-chip-title">ManyChat API</p>
                        <p class="sa-brand-chip-subtitle">Automatización WA</p>
                    </div>
                </div>
                <div class="sa-brand-chip-status d-flex gap-2">
                    <span class="badge <?= $manyChatProviderActive ? 'text-bg-primary' : 'text-bg-secondary' ?>"><?= $manyChatProviderActive ? 'Activo' : 'Inactivo' ?></span>
                    <span class="badge <?= $manyChatConfigured ? 'text-bg-success' : 'text-bg-warning' ?>"><?= $manyChatConfigured ? 'Credenciales OK' : 'Faltan datos' ?></span>
                </div>
                <div class="sa-brand-chip-actions">
                    <button class="btn btn-sm btn-outline-primary" type="button" data-bs-toggle="modal" data-bs-target="#saWhatsAppManyChatModal">
                        Configurar ManyChat
                    </button>
                </div>
            </div>
            <div class="sa-brand-chip <?= $wompiConfigured ? 'is-ready' : '' ?>">
                <div class="sa-brand-chip-head">
                    <span class="sa-brand-chip-logo"><img src="<?= e($wompiLogo) ?>" alt="Wompi"></span>
                    <div>
                        <p class="sa-brand-chip-title">Wompi</p>
                        <p class="sa-brand-chip-subtitle">Link de cobro</p>
                    </div>
                </div>
                <div class="sa-brand-chip-status">
                    <span class="badge <?= $wompiConfigured ? 'text-bg-success' : 'text-bg-warning' ?>"><?= $wompiConfigured ? 'Checkout listo' : 'Sin configurar' ?></span>
                </div>
            </div>
            <div class="sa-brand-chip <?= $openAiConfigured ? 'is-ready' : '' ?>">
                <div class="sa-brand-chip-head">
                    <span class="sa-brand-chip-logo"><img src="<?= e($openAiLogo) ?>" alt="OpenAI"></span>
                    <div>
                        <p class="sa-brand-chip-title">OpenAI</p>
                        <p class="sa-brand-chip-subtitle">Asistente IA</p>
                    </div>
                </div>
                <div class="sa-brand-chip-status">
                    <span class="badge <?= $openAiConfigured ? 'text-bg-success' : 'text-bg-warning' ?>"><?= $openAiConfigured ? 'Disponible' : 'Pendiente' ?></span>
                </div>
            </div>
        </div>

        <form action="<?= e(url('superadmin/notificaciones-config')) ?>" method="post" class="row g-3">
            <?= csrf_field() ?>

            <div class="col-xl-4">
                <div class="sa-integration-form-card h-100" data-provider="email">
                    <div class="sa-integration-head">
                        <span class="sa-integration-logo"><img src="<?= e($gmailLogo) ?>" alt="Gmail"></span>
                        <div>
                            <p class="sa-integration-title">Correo transaccional</p>
                            <p class="sa-integration-subtitle">Remitentes para cobranzas y alertas</p>
                        </div>
                    </div>
                    <div class="row g-2">
                        <div class="col-md-12">
                            <label class="form-label">Nombre remitente</label>
                            <input type="text" class="form-control" name="notify_email_from_name" value="<?= e((string) ($notificationConfig['email_from_name'] ?? 'Veltrix POS')) ?>" maxlength="120">
                        </div>
                        <div class="col-md-12">
                            <label class="form-label">Correo remitente</label>
                            <input type="email" class="form-control" name="notify_email_from_address" value="<?= e((string) ($notificationConfig['email_from_address'] ?? '')) ?>" placeholder="no-reply@tuempresa.com">
                        </div>
                        <div class="col-12">
                            <label class="form-label">Reply-to</label>
                            <input type="email" class="form-control" name="notify_email_reply_to" value="<?= e((string) ($notificationConfig['email_reply_to'] ?? '')) ?>" placeholder="soporte@tuempresa.com">
                        </div>
                        <div class="col-12 d-flex justify-content-end">
                            <button
                                class="btn btn-sm btn-outline-danger"
                                type="submit"
                                name="key"
                                value="email_reply_to"
                                formaction="<?= e(url('superadmin/notificaciones-config/limpiar')) ?>"
                                formmethod="post"
                                onclick="return confirm('¿Limpiar NOTIFY_EMAIL_REPLY_TO?');"
                            >
                                Limpiar reply-to
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-xl-4">
                <div class="sa-integration-form-card h-100" data-provider="meta">
                    <div class="sa-integration-head">
                        <span class="sa-integration-logo"><img src="<?= e($metaLogo) ?>" alt="Meta"></span>
                        <div>
                            <p class="sa-integration-title">Meta Cloud API</p>
                            <p class="sa-integration-subtitle">Canal directo de WhatsApp Business</p>
                        </div>
                    </div>
                    <div class="sa-provider-toggle">
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="notify_whatsapp_provider" id="notify_whatsapp_provider_meta" value="meta" <?= $metaProviderActive ? 'checked' : '' ?>>
                            <label class="form-check-label" for="notify_whatsapp_provider_meta">Usar Meta como proveedor activo</label>
                        </div>
                    </div>
                    <div class="row g-2">
                        <div class="col-12">
                            <label class="form-label">URL API Meta</label>
                            <input type="url" class="form-control" name="notify_whatsapp_api_url" value="<?= e((string) ($notificationConfig['whatsapp_api_url'] ?? 'https://graph.facebook.com/v20.0')) ?>" placeholder="https://graph.facebook.com/v20.0">
                        </div>
                        <div class="col-md-8">
                            <label class="form-label">Phone Number ID</label>
                            <input type="text" class="form-control" name="notify_whatsapp_phone_number_id" value="<?= e((string) ($notificationConfig['whatsapp_phone_number_id'] ?? '')) ?>" placeholder="123456789012345">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Código país</label>
                            <input type="text" class="form-control" name="notify_whatsapp_default_country_code" value="<?= e((string) ($notificationConfig['whatsapp_default_country_code'] ?? '57')) ?>" maxlength="5" placeholder="57">
                        </div>
                        <div class="col-12">
                            <label class="form-label">Access Token Meta</label>
                            <input type="password" class="form-control" name="notify_whatsapp_access_token" autocomplete="off" placeholder="Pega token nuevo para actualizar">
                            <small class="text-muted d-block mt-1">Guardado: <?= e((string) ($notificationConfig['whatsapp_access_token_masked'] ?? 'No configurado')) ?></small>
                        </div>
                        <div class="col-12">
                            <div class="form-check form-switch mt-1">
                                <input class="form-check-input" type="checkbox" name="notify_whatsapp_template_enabled" id="notify_whatsapp_template_enabled" value="1" <?= !empty($notificationConfig['whatsapp_template_enabled']) ? 'checked' : '' ?>>
                                <label class="form-check-label" for="notify_whatsapp_template_enabled">Enviar plantillas automáticamente en avisos de suscripción</label>
                            </div>
                            <small class="text-muted d-block mt-1">Recomendado para asegurar entrega fuera de la ventana de 24 horas.</small>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Idioma plantilla</label>
                            <input type="text" class="form-control" name="notify_whatsapp_template_language" value="<?= e((string) ($notificationConfig['whatsapp_template_language'] ?? 'es_CO')) ?>" maxlength="10" placeholder="es_CO">
                        </div>
                        <div class="col-md-8">
                            <label class="form-label">Enlace de plantillas</label>
                            <div class="form-control d-flex align-items-center justify-content-between" style="min-height: 40px;">
                                <span class="text-muted">Gestiona enlaces ilimitados por días desde “Estado de plantillas en Veltrix”.</span>
                                <button
                                    class="btn btn-sm btn-outline-primary"
                                    type="button"
                                    data-bs-toggle="modal"
                                    data-bs-target="#saWhatsAppTemplateBuilderModal"
                                >
                                    Crear plantilla
                                </button>
                            </div>
                        </div>
                        <div class="col-12 d-flex flex-wrap justify-content-end gap-2">
                            <button
                                class="btn btn-sm btn-outline-danger"
                                type="submit"
                                name="key"
                                value="whatsapp_phone_number_id"
                                formaction="<?= e(url('superadmin/notificaciones-config/limpiar')) ?>"
                                formmethod="post"
                                onclick="return confirm('¿Limpiar WHATSAPP_PHONE_NUMBER_ID?');"
                            >
                                Limpiar phone ID
                            </button>
                            <button
                                class="btn btn-sm btn-outline-danger"
                                type="submit"
                                name="key"
                                value="whatsapp_access_token"
                                formaction="<?= e(url('superadmin/notificaciones-config/limpiar')) ?>"
                                formmethod="post"
                                onclick="return confirm('¿Limpiar WHATSAPP_ACCESS_TOKEN?');"
                            >
                                Limpiar token Meta
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-xl-4">
                <div class="sa-integration-form-card h-100" data-provider="manychat">
                    <div class="sa-integration-head">
                        <span class="sa-integration-logo"><i class="bx bx-bot"></i></span>
                        <div>
                            <p class="sa-integration-title">ManyChat API</p>
                            <p class="sa-integration-subtitle">Fallback y automatizaciones avanzadas</p>
                        </div>
                    </div>
                    <div class="sa-provider-toggle">
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="notify_whatsapp_provider" id="notify_whatsapp_provider_manychat" value="manychat" <?= $manyChatProviderActive ? 'checked' : '' ?>>
                            <label class="form-check-label" for="notify_whatsapp_provider_manychat">Usar ManyChat como proveedor activo</label>
                        </div>
                    </div>
                    <div class="row g-2">
                        <div class="col-md-12">
                            <label class="form-label">URL API ManyChat</label>
                            <input type="url" class="form-control" name="notify_manychat_api_url" value="<?= e((string) ($notificationConfig['manychat_api_url'] ?? 'https://api.manychat.com')) ?>" placeholder="https://api.manychat.com">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Message Tag</label>
                            <input type="text" class="form-control" name="notify_manychat_message_tag" value="<?= e((string) ($notificationConfig['manychat_message_tag'] ?? 'ACCOUNT_UPDATE')) ?>" maxlength="80" placeholder="ACCOUNT_UPDATE">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Custom Field ID</label>
                            <input type="text" class="form-control" name="notify_manychat_contact_field_id" value="<?= e((string) ($notificationConfig['manychat_contact_field_id'] ?? '')) ?>" maxlength="20" placeholder="Opcional">
                        </div>
                        <div class="col-12">
                            <label class="form-label">Access Token ManyChat</label>
                            <input type="password" class="form-control" name="notify_manychat_access_token" autocomplete="off" placeholder="Pega token nuevo para actualizar">
                            <small class="text-muted d-block mt-1">Guardado: <?= e((string) ($notificationConfig['manychat_access_token_masked'] ?? 'No configurado')) ?></small>
                            <small class="text-muted d-block mt-1">Si ManyChat no devuelve subscriber_id para contactos existentes por WhatsApp ID, configura el Custom Field ID.</small>
                        </div>
                        <div class="col-12 d-flex flex-wrap justify-content-end gap-2">
                            <button
                                class="btn btn-sm btn-outline-danger"
                                type="submit"
                                name="key"
                                value="manychat_access_token"
                                formaction="<?= e(url('superadmin/notificaciones-config/limpiar')) ?>"
                                formmethod="post"
                                onclick="return confirm('¿Limpiar MANYCHAT_ACCESS_TOKEN?');"
                            >
                                Limpiar token ManyChat
                            </button>
                            <button
                                class="btn btn-sm btn-outline-danger"
                                type="submit"
                                name="key"
                                value="manychat_contact_field_id"
                                formaction="<?= e(url('superadmin/notificaciones-config/limpiar')) ?>"
                                formmethod="post"
                                onclick="return confirm('¿Limpiar MANYCHAT_CONTACT_FIELD_ID?');"
                            >
                                Limpiar field ID
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-xl-7">
                <div class="sa-integration-form-card h-100" data-provider="ops">
                    <div class="sa-integration-head">
                        <span class="sa-integration-logo"><i class="bx bx-slider-alt"></i></span>
                        <div>
                            <p class="sa-integration-title">Canales y política de reintentos</p>
                            <p class="sa-integration-subtitle">Controla envíos y resiliencia del sistema</p>
                        </div>
                    </div>
                    <?php
                    $retryBackoffValue = (string) ($notificationConfig['retry_backoff_minutes'] ?? '5,30,180');
                    $retryBackoffPreview = array_values(array_filter(
                        array_map('trim', explode(',', $retryBackoffValue)),
                        static fn (string $v): bool => $v !== '' && ctype_digit($v)
                    ));
                    if ($retryBackoffPreview === []) {
                        $retryBackoffPreview = ['5', '30', '180'];
                    }
                    ?>
                    <div class="sa-ops-layout">
                        <div class="sa-ops-inputs">
                            <div class="row g-2">
                                <div class="col-md-4">
                                    <label class="form-label">Máx. intentos</label>
                                    <input type="number" class="form-control" name="notify_retry_max_attempts" min="1" max="15" value="<?= e((string) ($notificationConfig['retry_max_attempts'] ?? 3)) ?>">
                                </div>
                                <div class="col-md-8">
                                    <label class="form-label">Backoff (minutos)</label>
                                    <input type="text" class="form-control" name="notify_retry_backoff_minutes" value="<?= e($retryBackoffValue) ?>" placeholder="5,30,180">
                                </div>
                            </div>
                            <small class="text-muted d-block mt-2">Formato recomendado: valores separados por coma, por ejemplo <code>5,30,180</code>.</small>
                            <div class="sa-ops-backoff-hints">
                                <?php foreach (array_slice($retryBackoffPreview, 0, 6) as $minutes): ?>
                                    <span class="sa-ops-backoff-chip"><?= e($minutes) ?> min</span>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <div class="sa-ops-channels">
                            <div class="sa-ops-channels-title">Canales habilitados</div>
                            <div class="sa-ops-switch-list">
                                <div class="sa-ops-switch-item">
                                    <div class="form-check form-switch m-0">
                                        <input class="form-check-input" type="checkbox" name="notify_channel_email" id="notify_channel_email" value="1" <?= !empty($notificationConfig['channel_email']) ? 'checked' : '' ?>>
                                        <label class="form-check-label" for="notify_channel_email">Email</label>
                                    </div>
                                    <span class="badge <?= !empty($notificationConfig['channel_email']) ? 'text-bg-success' : 'text-bg-secondary' ?>">
                                        <?= !empty($notificationConfig['channel_email']) ? 'Activo' : 'Off' ?>
                                    </span>
                                </div>
                                <div class="sa-ops-switch-item">
                                    <div class="form-check form-switch m-0">
                                        <input class="form-check-input" type="checkbox" name="notify_channel_whatsapp" id="notify_channel_whatsapp" value="1" <?= !empty($notificationConfig['channel_whatsapp']) ? 'checked' : '' ?>>
                                        <label class="form-check-label" for="notify_channel_whatsapp">WhatsApp</label>
                                    </div>
                                    <span class="badge <?= !empty($notificationConfig['channel_whatsapp']) ? 'text-bg-success' : 'text-bg-secondary' ?>">
                                        <?= !empty($notificationConfig['channel_whatsapp']) ? 'Activo' : 'Off' ?>
                                    </span>
                                </div>
                            </div>
                            <small class="text-muted d-block mt-2">Los tokens de Meta/ManyChat solo cambian cuando escribes uno nuevo.</small>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-xl-5">
                <div class="sa-integration-form-card h-100" data-provider="test">
                    <div class="sa-integration-head">
                        <span class="sa-integration-logo"><i class="bx bx-send"></i></span>
                        <div>
                            <p class="sa-integration-title">Prueba rápida de WhatsApp</p>
                            <p class="sa-integration-subtitle">Valida salida antes de campañas masivas</p>
                        </div>
                    </div>
                    <div class="row g-2">
                        <div class="col-md-5">
                            <label class="form-label">Número destino</label>
                            <input type="text" class="form-control" name="test_whatsapp_phone" value="<?= e((string) old('test_whatsapp_phone', $notificationTestPhoneDefault)) ?>" placeholder="3001234567">
                        </div>
                        <div class="col-md-7">
                            <label class="form-label">Mensaje prueba</label>
                            <input type="text" class="form-control" name="test_whatsapp_message" value="<?= e((string) old('test_whatsapp_message', 'Prueba de notificaciones Veltrix')) ?>" placeholder="Mensaje de prueba">
                        </div>
                        <div class="col-12">
                            <button class="btn btn-outline-primary" type="submit" formaction="<?= e(url('superadmin/notificaciones-config/probar-whatsapp')) ?>" formmethod="post">
                                Probar envío WhatsApp
                            </button>
                        </div>
                    </div>
                    <div class="sa-mini-integration-list">
                        <div class="sa-mini-integration">
                            <span class="sa-brand-chip-logo"><img src="<?= e($wompiLogo) ?>" alt="Wompi"></span>
                            <div>
                                <strong>Wompi checkout</strong>
                                <small><?= $wompiConfigured ? 'Listo para links de pago' : 'Revisar llaves en sección Wompi' ?></small>
                            </div>
                        </div>
                        <div class="sa-mini-integration">
                            <span class="sa-brand-chip-logo"><img src="<?= e($openAiLogo) ?>" alt="OpenAI"></span>
                            <div>
                                <strong>Asistente OpenAI</strong>
                                <small><?= $openAiConfigured ? 'Disponible para soporte interno' : 'Pendiente de configuración' ?></small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-12 d-flex flex-wrap gap-2">
                <button class="btn btn-primary" type="submit">Guardar configuración de integraciones</button>
            </div>
        </form>
</div>
</div>
</div>

<div class="sa-section sa-wa-meta-section <?= $superadminSection === 'whatsapp_meta' ? 'is-active' : '' ?>" data-sa-section="whatsapp_meta">
<div class="card border-0 shadow-sm mb-4 sa-wa-meta-shell">
    <div class="card-body">
        <div class="sa-market-hero mb-3">
            <h2 class="sa-market-title">WhatsApp Meta Cloud API</h2>
            <p class="sa-market-subtitle">Controla conexión, plantillas y estado de aprobación desde una vista más limpia y operativa.</p>
            <div class="sa-market-stats">
                <div class="sa-market-stat">
                    <small>Canal activo</small>
                    <strong><?= e(strtoupper($selectedWhatsAppProvider)) ?></strong>
                </div>
                <div class="sa-market-stat">
                    <small>Enlaces activos</small>
                    <strong><?= e((string) count($whatsAppTemplateLinks)) ?></strong>
                </div>
                <div class="sa-market-stat">
                    <small>Plantillas aprobadas</small>
                    <strong><?= e((string) $whatsAppTemplateApprovedCount) ?></strong>
                </div>
                <div class="sa-market-stat">
                    <small>Pendientes Meta</small>
                    <strong><?= e((string) $whatsAppTemplatePendingCount) ?></strong>
                </div>
            </div>
        </div>

        <div class="vx-integrations-grid sa-market-grid sa-wa-meta-grid">
            <article class="card border-0 shadow-sm vx-integration-card vx-integration-card-main sa-wa-meta-card">
                <div class="card-body">
                    <div class="d-flex align-items-start gap-3">
                        <span class="vx-integration-logo vx-integration-logo-image"><img src="<?= e($metaLogo) ?>" alt="Meta"></span>
                        <div>
                            <h2 class="h5 mb-1">Integración</h2>
                            <p class="text-muted mb-0 vx-integration-description">Configura URL API, Phone Number ID y token oficial de Meta.</p>
                        </div>
                    </div>
                    <div class="d-flex flex-wrap gap-2 vx-integration-badges">
                        <span class="badge text-bg-light border">WhatsApp oficial</span>
                    </div>
                    <div class="row g-2">
                        <div class="col-6">
                            <div class="vx-integration-metric">
                                <small>Phone ID</small>
                                <strong><?= e((string) ($notificationConfig['whatsapp_phone_number_id_masked'] ?? 'No configurado')) ?></strong>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="vx-integration-metric">
                                <small>Token</small>
                                <strong><?= $metaHasToken ? 'Configurado' : 'Pendiente' ?></strong>
                            </div>
                        </div>
                    </div>
                    <div class="sa-market-actions">
                        <span class="badge vx-integration-state <?= $metaConfigured ? 'is-active' : 'is-inactive' ?>"><?= $metaConfigured ? 'Listo' : 'Pendiente' ?></span>
                        <button class="btn btn-primary vx-integration-integrate-btn sa-market-link-btn" type="button" data-bs-toggle="modal" data-bs-target="#saWhatsAppMetaModal">
                            <i class="bx bx-link-alt me-1"></i>Integrar
                        </button>
                    </div>
                </div>
            </article>

            <article class="card border-0 shadow-sm vx-integration-card vx-integration-card-main sa-wa-meta-card">
                <div class="card-body">
                    <div class="d-flex align-items-start gap-3">
                        <span class="vx-integration-logo vx-integration-logo-muted"><i class="bx bx-copy-alt"></i></span>
                        <div>
                            <h2 class="h5 mb-1">Plantillas</h2>
                            <p class="text-muted mb-0 vx-integration-description">Enlaza todas las plantillas que necesites con días dinámicos (10, 7, 3, 1, 0, etc.).</p>
                        </div>
                    </div>
                    <div class="d-flex flex-wrap gap-2 vx-integration-badges">
                        <span class="badge text-bg-light border">Automatización</span>
                    </div>
                    <div class="row g-2">
                        <div class="col-6">
                            <div class="vx-integration-metric">
                                <small>Enlaces activos</small>
                                <strong><?= e((string) count($whatsAppTemplateLinks)) ?></strong>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="vx-integration-metric">
                                <small>Pendientes Meta</small>
                                <strong><?= e((string) $whatsAppTemplatePendingCount) ?></strong>
                            </div>
                        </div>
                    </div>
                    <div class="sa-market-actions">
                        <span class="badge vx-integration-state <?= !empty($notificationConfig['whatsapp_template_enabled']) ? 'is-active' : 'is-inactive' ?>">
                            <?= !empty($notificationConfig['whatsapp_template_enabled']) ? 'Activas' : 'Desactivadas' ?>
                        </span>
                        <button class="btn btn-outline-primary sa-market-soft-btn" type="button" data-bs-toggle="modal" data-bs-target="#saWhatsAppTemplateBuilderModal">
                            Editar plantillas
                        </button>
                    </div>
                </div>
            </article>

            <article class="card border-0 shadow-sm vx-integration-card vx-integration-card-main sa-wa-meta-card">
                <div class="card-body">
                    <div class="d-flex align-items-start gap-3">
                        <span class="vx-integration-logo vx-integration-logo-muted"><i class="bx bx-message-square-edit"></i></span>
                        <div>
                            <h2 class="h5 mb-1">Crear plantillas</h2>
                            <p class="text-muted mb-0 vx-integration-description">Abre WhatsApp Manager para crear o enviar a revisión nuevas plantillas.</p>
                        </div>
                    </div>
                    <div class="d-flex flex-wrap gap-2 vx-integration-badges">
                        <span class="badge text-bg-light border">Business Manager</span>
                    </div>
                    <div class="row g-2">
                        <div class="col-12">
                            <div class="vx-integration-metric">
                                <small>Idioma recomendado</small>
                                <strong><?= e((string) ($notificationConfig['whatsapp_template_language'] ?? 'es_CO')) ?></strong>
                            </div>
                        </div>
                    </div>
                    <div class="sa-market-actions">
                        <span class="badge vx-integration-state is-soon">Manual</span>
                        <a class="btn btn-outline-primary sa-market-soft-btn" href="https://business.facebook.com/latest/whatsapp_manager/message_templates" target="_blank" rel="noopener">
                            Abrir Manager
                        </a>
                    </div>
                </div>
            </article>

            <article class="card border-0 shadow-sm vx-integration-card vx-integration-card-main sa-wa-meta-card sa-wa-meta-card-test">
                <div class="card-body">
                    <div class="sa-wa-meta-test-copy">
                        <div class="d-flex align-items-start gap-3">
                            <span class="vx-integration-logo vx-integration-logo-muted"><i class="bx bx-send"></i></span>
                            <div>
                                <h2 class="h5 mb-1">Prueba WhatsApp</h2>
                                <p class="text-muted mb-0 vx-integration-description">Envía un mensaje de prueba para validar salida desde el proveedor activo.</p>
                            </div>
                        </div>
                        <div class="d-flex flex-wrap gap-2 vx-integration-badges mt-1">
                            <span class="badge text-bg-light border">QA</span>
                        </div>
                        <p class="sa-market-note mb-0 mt-1">Proveedor activo actual: <strong><?= e(strtoupper($selectedWhatsAppProvider)) ?></strong>.</p>
                    </div>
                    <form action="<?= e(url('superadmin/notificaciones-config/probar-whatsapp')) ?>" method="post" class="sa-market-form-inline sa-wa-meta-test-form">
                        <?= csrf_field() ?>
                        <label class="form-label mb-1">Número destino</label>
                        <input type="text" class="form-control mb-2" name="test_whatsapp_phone" value="<?= e((string) old('test_whatsapp_phone', $notificationTestPhoneDefault)) ?>" placeholder="3001234567">
                        <label class="form-label mb-1">Mensaje</label>
                        <input type="text" class="form-control mb-2" name="test_whatsapp_message" value="<?= e((string) old('test_whatsapp_message', 'Prueba de notificaciones Veltrix')) ?>" placeholder="Mensaje de prueba">
                        <button class="btn btn-outline-primary w-100" type="submit">Enviar prueba</button>
                    </form>
                </div>
            </article>

        </div>

        <div class="card border-0 shadow-sm mt-3 sa-wa-meta-table-shell">
            <div class="card-body">
                <div class="d-flex flex-wrap justify-content-between align-items-center gap-2 mb-2">
                    <div>
                        <h2 class="h5 mb-1">Estado de plantillas en Veltrix</h2>
                        <p class="text-muted mb-0">Aquí es donde enlazas plantillas de Meta con los avisos automáticos del sistema.</p>
                    </div>
                    <div class="d-flex flex-wrap gap-2">
                        <a class="btn btn-outline-secondary sa-market-soft-btn" href="<?= e(url('superadmin') . '?seccion=whatsapp_meta_templates') ?>">
                            Enlazar desde Meta
                        </a>
                        <button class="btn btn-outline-primary sa-market-soft-btn" type="button" data-bs-toggle="modal" data-bs-target="#saWhatsAppTemplateBuilderModal">
                            Crear / editar plantilla
                        </button>
                    </div>
                </div>

                <div class="sa-template-hub">
                    <h3 class="sa-template-hub-title">Enlaces activos de automatización</h3>
                    <p class="sa-template-hub-subtitle">Configura qué plantilla usa el sistema para cada aviso: 10, 7, 3, 1, 0 días y más.</p>
                    <p class="sa-template-path mb-0">
                        Ruta rápida: <strong>Integraciones → WhatsApp (Meta Cloud API) → Estado de plantillas en Veltrix</strong>.
                        Desde las acciones de cada fila puedes enlazar en 1 clic para <strong>10 días</strong>, <strong>3 días</strong> o cualquier valor personalizado en <strong>Días antes</strong>.
                    </p>

                    <div class="sa-template-kpis">
                        <div class="sa-template-kpi">
                            <small>Plantillas creadas</small>
                            <strong><?= e((string) count($whatsAppMetaTemplates)) ?></strong>
                        </div>
                        <div class="sa-template-kpi">
                            <small>Aprobadas</small>
                            <strong><?= e((string) $whatsAppTemplateApprovedCount) ?></strong>
                        </div>
                        <div class="sa-template-kpi">
                            <small>Pendientes</small>
                            <strong><?= e((string) $whatsAppTemplatePendingCount) ?></strong>
                        </div>
                        <div class="sa-template-kpi">
                            <small>Enlaces activos</small>
                            <strong><?= e((string) count($whatsAppTemplateLinks)) ?></strong>
                        </div>
                    </div>

                    <div class="sa-template-link-grid">
                        <?php if ($whatsAppTemplateLinks === []) : ?>
                            <article class="sa-template-link-card is-empty">
                                <p class="sa-template-link-title">Sin enlaces activos</p>
                                <p class="sa-template-link-name">Aún no has enlazado plantillas a automatizaciones.</p>
                                <p class="sa-template-link-status">Estado: pendiente de configuración</p>
                                <p class="sa-template-link-meta">Desde cada plantilla puedes enlazar por días (10, 7, 3, 1, 0) y crear todos los avisos que necesites.</p>
                            </article>
                        <?php else : ?>
                            <?php foreach ($whatsAppTemplateLinks as $linkedRow) : ?>
                                <?php
                                $linkedId = (int) ($linkedRow['id'] ?? 0);
                                $linkedUsage = strtolower(trim((string) ($linkedRow['uso'] ?? 'libre')));
                                $linkedLabel = $resolveWhatsAppUsageLabel($linkedUsage);
                                ?>
                                <article class="sa-template-link-card is-linked">
                                    <p class="sa-template-link-title"><?= e($linkedLabel) ?></p>
                                    <p class="sa-template-link-name"><?= e((string) ($linkedRow['nombre'] ?? '')) ?></p>
                                    <p class="sa-template-link-status">Estado: enlazado</p>
                                    <p class="sa-template-link-meta">Idioma: <?= e((string) ($linkedRow['idioma'] ?? 'es_CO')) ?> · Uso: <code><?= e($linkedUsage) ?></code></p>
                                    <div class="sa-template-link-actions">
                                        <form action="<?= e(url('superadmin/whatsapp-meta-templates/' . $linkedId . '/enlazar')) ?>" method="post" class="d-inline">
                                            <?= csrf_field() ?>
                                            <input type="hidden" name="link_slot" value="libre">
                                            <button class="btn btn-sm btn-outline-danger" type="submit">Desenlazar</button>
                                        </form>
                                    </div>
                                </article>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="table-responsive sa-template-table-wrap sa-template-table-modern-wrap">
                    <table class="table table-sm align-middle sa-template-table sa-template-table-modern mb-0">
                        <thead>
                            <tr>
                                <th>Plantilla</th>
                                <th>Idioma</th>
                                <th>Estado Meta</th>
                                <th>Última sincronización</th>
                                <th class="text-end">Acciones rápidas</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($whatsAppMetaTemplates === []) : ?>
                                <tr>
                                    <td colspan="5" class="text-center text-muted py-3">Aún no hay plantillas creadas desde Veltrix.</td>
                                </tr>
                            <?php else : ?>
                                <?php foreach ($whatsAppMetaTemplates as $templateRow) : ?>
                                    <?php
                                    $templateId = (int) ($templateRow['id'] ?? 0);
                                    $usageKey = strtolower(trim((string) ($templateRow['uso'] ?? 'libre')));
                                    $usageLabel = $resolveWhatsAppUsageLabel($usageKey);
                                    $templateState = strtolower(trim((string) ($templateRow['meta_estado'] ?? 'pendiente')));
                                    if (!in_array($templateState, ['pendiente', 'aprobada', 'rechazada', 'error'], true)) {
                                        $templateState = 'error';
                                    }
                                    $stateLabel = match ($templateState) {
                                        'aprobada' => 'Aprobada',
                                        'rechazada' => 'Rechazada',
                                        'error' => 'Error',
                                        default => 'Pendiente',
                                    };
                                    $stateClass = match ($templateState) {
                                        'aprobada' => 'is-approved',
                                        'rechazada' => 'is-rejected',
                                        'error' => 'is-error',
                                        default => 'is-pending',
                                    };
                                    $isLinked10 = $usageKey === 'previo_10_dias';
                                    $isLinked3 = $usageKey === 'previo_3_dias';
                                    $isLinkedAny = $usageKey !== '' && $usageKey !== 'libre';
                                    ?>
                                    <tr>
                                        <td class="sa-template-cell-wrap">
                                            <h6 class="sa-template-table-modern-title"><?= e((string) ($templateRow['nombre'] ?? '')) ?></h6>
                                            <?php if ($isLinkedAny) : ?><span class="sa-template-table-modern-usage"><?= e($usageLabel) ?></span><?php endif; ?>
                                            <?php if (trim((string) ($templateRow['meta_template_id'] ?? '')) !== '') : ?>
                                                <span class="sa-template-table-modern-meta">Meta ID: <?= e((string) $templateRow['meta_template_id']) ?></span>
                                            <?php endif; ?>
                                        </td>
                                        <td><span class="sa-template-table-modern-lang"><?= e((string) ($templateRow['idioma'] ?? 'es_CO')) ?></span></td>
                                        <td>
                                            <span class="sa-template-status-badge <?= e($stateClass) ?>"><?= e($stateLabel) ?></span>
                                            <?php if (trim((string) ($templateRow['meta_estado_detalle'] ?? '')) !== '') : ?>
                                                <div><small class="text-muted"><?= e((string) $templateRow['meta_estado_detalle']) ?></small></div>
                                            <?php endif; ?>
                                        </td>
                                        <?php
                                        $syncRaw = trim((string) ($templateRow['meta_last_sync_at'] ?? ($templateRow['updated_at'] ?? '')));
                                        $syncDateLabel = '-';
                                        $syncTimeLabel = '';
                                        if ($syncRaw !== '' && $syncRaw !== '0000-00-00 00:00:00') {
                                            $syncTs = strtotime($syncRaw);
                                            if ($syncTs !== false) {
                                                $syncDateLabel = date('d/m/Y', $syncTs);
                                                $syncTimeLabel = date('h:i A', $syncTs);
                                            } else {
                                                $syncDateLabel = $syncRaw;
                                            }
                                        }
                                        ?>
                                        <td class="sa-template-table-modern-sync">
                                            <span class="sync-date"><?= e($syncDateLabel) ?></span>
                                            <?php if ($syncTimeLabel !== '') : ?><span class="sync-time"><?= e($syncTimeLabel) ?></span><?php endif; ?>
                                        </td>
                                        <td class="text-end sa-template-actions-cell">
                                            <div class="sa-template-actions sa-template-actions-modern">
                                                <form action="<?= e(url('superadmin/whatsapp-meta-templates/' . $templateId . '/enlazar')) ?>" method="post" class="d-inline">
                                                    <?= csrf_field() ?>
                                                    <input type="hidden" name="link_slot" value="previo_10_dias">
                                                    <button class="btn btn-sm <?= $isLinked10 ? 'btn-primary' : 'btn-outline-primary' ?>" type="submit" <?= $isLinked10 ? 'disabled' : '' ?>><?= $isLinked10 ? 'En uso 10 días' : 'Usar 10 días' ?></button>
                                                </form>
                                                <form action="<?= e(url('superadmin/whatsapp-meta-templates/' . $templateId . '/enlazar')) ?>" method="post" class="d-inline">
                                                    <?= csrf_field() ?>
                                                    <input type="hidden" name="link_slot" value="previo_3_dias">
                                                    <button class="btn btn-sm <?= $isLinked3 ? 'btn-info' : 'btn-outline-info' ?>" type="submit" <?= $isLinked3 ? 'disabled' : '' ?>><?= $isLinked3 ? 'En uso 3 días' : 'Usar 3 días' ?></button>
                                                </form>
                                                <form action="<?= e(url('superadmin/whatsapp-meta-templates/' . $templateId . '/enlazar')) ?>" method="post" class="d-inline-flex gap-1 align-items-center">
                                                    <?= csrf_field() ?>
                                                    <input type="number" class="form-control form-control-sm" name="link_days_before_due" min="0" max="365" placeholder="días">
                                                    <button class="btn btn-sm btn-outline-dark" type="submit">Enlazar día</button>
                                                </form>
                                                <?php if ($isLinkedAny) : ?>
                                                    <form action="<?= e(url('superadmin/whatsapp-meta-templates/' . $templateId . '/enlazar')) ?>" method="post" class="d-inline">
                                                        <?= csrf_field() ?>
                                                        <input type="hidden" name="link_slot" value="libre">
                                                        <button class="btn btn-sm btn-outline-danger" type="submit">Desenlazar</button>
                                                    </form>
                                                <?php endif; ?>
                                                <form action="<?= e(url('superadmin/whatsapp-meta-templates/' . $templateId . '/sincronizar')) ?>" method="post" class="d-inline">
                                                    <?= csrf_field() ?>
                                                    <button class="btn btn-sm btn-outline-secondary" type="submit">Sincronizar</button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <div class="sa-template-mobile-list">
                    <?php if ($whatsAppMetaTemplates === []) : ?>
                        <div class="sa-template-mobile-card">
                            <p class="text-muted mb-0">Aún no hay plantillas creadas desde Veltrix.</p>
                        </div>
                    <?php else : ?>
                        <?php foreach ($whatsAppMetaTemplates as $templateRow) : ?>
                            <?php
                            $templateId = (int) ($templateRow['id'] ?? 0);
                            $usageKey = strtolower(trim((string) ($templateRow['uso'] ?? 'libre')));
                            $usageLabel = $resolveWhatsAppUsageLabel($usageKey);
                            $templateState = strtolower(trim((string) ($templateRow['meta_estado'] ?? 'pendiente')));
                            if (!in_array($templateState, ['pendiente', 'aprobada', 'rechazada', 'error'], true)) {
                                $templateState = 'error';
                            }
                            $stateLabel = match ($templateState) {
                                'aprobada' => 'Aprobada',
                                'rechazada' => 'Rechazada',
                                'error' => 'Error',
                                default => 'Pendiente',
                            };
                            $stateClass = match ($templateState) {
                                'aprobada' => 'is-approved',
                                'rechazada' => 'is-rejected',
                                'error' => 'is-error',
                                default => 'is-pending',
                            };
                            $isLinked10 = $usageKey === 'previo_10_dias';
                            $isLinked3 = $usageKey === 'previo_3_dias';
                            $isLinkedAny = $usageKey !== '' && $usageKey !== 'libre';
                            ?>
                            <article class="sa-template-mobile-card">
                                <div class="sa-template-mobile-head">
                                    <div>
                                        <h3 class="sa-template-mobile-title"><?= e((string) ($templateRow['nombre'] ?? '')) ?></h3>
                                        <p class="sa-template-mobile-meta">Idioma: <?= e((string) ($templateRow['idioma'] ?? 'es_CO')) ?></p>
                                    </div>
                                    <span class="sa-template-status-badge <?= e($stateClass) ?>"><?= e($stateLabel) ?></span>
                                </div>
                                <div class="sa-template-mobile-chips">
                                    <?php if ($isLinkedAny) : ?><span class="sa-template-mobile-chip"><?= e($usageLabel) ?></span><?php endif; ?>
                                    <?php if (trim((string) ($templateRow['meta_last_sync_at'] ?? '')) !== '') : ?>
                                        <span class="sa-template-mobile-chip">Sync: <?= e((string) $templateRow['meta_last_sync_at']) ?></span>
                                    <?php endif; ?>
                                </div>
                                <div class="sa-template-mobile-actions">
                                    <form action="<?= e(url('superadmin/whatsapp-meta-templates/' . $templateId . '/enlazar')) ?>" method="post">
                                        <?= csrf_field() ?>
                                        <input type="hidden" name="link_slot" value="previo_10_dias">
                                        <button class="btn btn-sm <?= $isLinked10 ? 'btn-primary' : 'btn-outline-primary' ?>" type="submit" <?= $isLinked10 ? 'disabled' : '' ?>><?= $isLinked10 ? 'En uso 10 días' : 'Usar 10 días' ?></button>
                                    </form>
                                    <form action="<?= e(url('superadmin/whatsapp-meta-templates/' . $templateId . '/enlazar')) ?>" method="post">
                                        <?= csrf_field() ?>
                                        <input type="hidden" name="link_slot" value="previo_3_dias">
                                        <button class="btn btn-sm <?= $isLinked3 ? 'btn-info' : 'btn-outline-info' ?>" type="submit" <?= $isLinked3 ? 'disabled' : '' ?>><?= $isLinked3 ? 'En uso 3 días' : 'Usar 3 días' ?></button>
                                    </form>
                                    <form action="<?= e(url('superadmin/whatsapp-meta-templates/' . $templateId . '/enlazar')) ?>" method="post" class="d-flex gap-1">
                                        <?= csrf_field() ?>
                                        <input type="number" class="form-control form-control-sm" name="link_days_before_due" min="0" max="365" placeholder="Días">
                                        <button class="btn btn-sm btn-outline-dark" type="submit">Enlazar día</button>
                                    </form>
                                    <?php if ($isLinkedAny) : ?>
                                        <form action="<?= e(url('superadmin/whatsapp-meta-templates/' . $templateId . '/enlazar')) ?>" method="post">
                                            <?= csrf_field() ?>
                                            <input type="hidden" name="link_slot" value="libre">
                                            <button class="btn btn-sm btn-outline-danger" type="submit">Desenlazar</button>
                                        </form>
                                    <?php endif; ?>
                                    <form action="<?= e(url('superadmin/whatsapp-meta-templates/' . $templateId . '/sincronizar')) ?>" method="post">
                                        <?= csrf_field() ?>
                                        <button class="btn btn-sm btn-outline-secondary" type="submit">Sincronizar</button>
                                    </form>
                                </div>
                            </article>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
</div>
</div>
</div>

<div class="sa-section sa-wa-template-center <?= $superadminSection === 'whatsapp_meta_templates' ? 'is-active' : '' ?>" data-sa-section="whatsapp_meta_templates">
<div class="card border-0 shadow-sm mb-4 sa-wa-template-center-shell">
    <div class="card-body">
        <section class="sa-wa-template-center-hero">
            <div>
                <h2>Centro de Enlace de Plantillas Meta</h2>
                <p>Gestiona enlaces, horario de salida y envío inmediato desde una vista corta. Si hay mucha información, se abre en modal por plantilla.</p>
            </div>
            <div class="sa-wa-template-center-actions">
                <form action="<?= e(url('superadmin/whatsapp-meta-templates/sincronizar-meta')) ?>" method="post" class="sa-wa-template-center-sync">
                    <?= csrf_field() ?>
                    <div>
                        <label class="form-label">Límite</label>
                        <input type="number" class="form-control form-control-sm" name="meta_sync_limit" min="1" max="250" value="120">
                    </div>
                    <button class="btn btn-primary btn-sm" type="submit">Sincronizar Meta</button>
                </form>
                <button class="btn btn-outline-primary btn-sm" type="button" data-bs-toggle="modal" data-bs-target="#saWhatsAppTemplateBuilderModal">
                    Crear plantilla
                </button>
                <a class="btn btn-light border btn-sm" href="<?= e(url('superadmin') . '?seccion=whatsapp_meta') ?>">
                    Volver a WhatsApp Meta
                </a>
            </div>
        </section>

        <section class="sa-wa-template-center-kpis">
            <article class="sa-wa-template-center-kpi">
                <small>Total plantillas</small>
                <strong><?= e((string) $whatsAppTemplateTotalCount) ?></strong>
            </article>
            <article class="sa-wa-template-center-kpi">
                <small>Aprobadas</small>
                <strong><?= e((string) $whatsAppTemplateApprovedCount) ?></strong>
            </article>
            <article class="sa-wa-template-center-kpi">
                <small>Pendientes</small>
                <strong><?= e((string) $whatsAppTemplatePendingCount) ?></strong>
            </article>
            <article class="sa-wa-template-center-kpi">
                <small>Enlaces activos</small>
                <strong><?= e((string) $whatsAppTemplateLinkedCount) ?></strong>
            </article>
            <article class="sa-wa-template-center-kpi">
                <small>Hora por defecto</small>
                <strong><?= e($whatsAppDispatchTimeDefault) ?></strong>
            </article>
        </section>

        <div class="row g-3 mt-1">
            <div class="col-xl-4">
                <article class="sa-wa-template-center-panel">
                    <h3>Horario de salida por aviso</h3>
                    <p>Estos horarios controlan cuándo entra a cola cada plantilla automática (zona del servidor).</p>
                    <form action="<?= e(url('superadmin/whatsapp-meta-templates/programacion')) ?>" method="post">
                        <?= csrf_field() ?>
                        <div class="sa-wa-template-center-schedule-list">
                            <div class="sa-wa-template-center-schedule-row">
                                <div>
                                    <strong>Horario por defecto</strong>
                                    <small>Aplica cuando un tipo no tiene hora propia</small>
                                </div>
                                <input type="time" name="dispatch_time[default]" value="<?= e($whatsAppDispatchTimeDefault) ?>" required>
                            </div>
                            <?php foreach ($whatsAppDispatchTypes as $dispatchType): ?>
                                <?php $dispatchTimeValue = $resolveDispatchTimeForUsage((string) $dispatchType); ?>
                                <div class="sa-wa-template-center-schedule-row">
                                    <div>
                                        <strong><?= e($resolveWhatsAppUsageLabel((string) $dispatchType)) ?></strong>
                                        <small>Clave: <?= e((string) $dispatchType) ?></small>
                                    </div>
                                    <input type="time" name="dispatch_time[<?= e((string) $dispatchType) ?>]" value="<?= e($dispatchTimeValue) ?>">
                                </div>
                            <?php endforeach; ?>
                        </div>
                        <button class="btn btn-primary btn-sm mt-2" type="submit">Guardar horarios</button>
                    </form>
                </article>
            </div>

            <div class="col-xl-8">
                <article class="sa-wa-template-center-panel">
                    <div class="d-flex flex-wrap align-items-center justify-content-between gap-2">
                        <div>
                            <h3>Plantillas enlazables (tabla corta)</h3>
                            <p>Mostramos hasta 8 filas. El detalle completo se abre en modal por cada plantilla.</p>
                        </div>
                        <?php if ($whatsAppTemplateCenterHiddenCount > 0): ?>
                            <button class="btn btn-outline-secondary btn-sm" type="button" data-bs-toggle="modal" data-bs-target="#saWhatsAppTemplateLinkModal">
                                Ver catálogo completo (<?= e((string) $whatsAppTemplateCenterHiddenCount) ?>+)
                            </button>
                        <?php endif; ?>
                    </div>

                    <div class="table-responsive sa-wa-template-center-table-wrap">
                        <table class="table table-sm align-middle">
                            <thead>
                                <tr>
                                    <th>Plantilla</th>
                                    <th>Uso</th>
                                    <th>Estado</th>
                                    <th>Hora</th>
                                    <th class="text-end">Acción</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($whatsAppTemplateCenterRows === []): ?>
                                    <tr>
                                        <td colspan="5" class="text-center text-muted py-3">No hay plantillas todavía. Sincroniza catálogo Meta para comenzar.</td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($whatsAppTemplateCenterRows as $templateRow): ?>
                                        <?php
                                        $templateId = (int) ($templateRow['id'] ?? 0);
                                        $usageKey = strtolower(trim((string) ($templateRow['uso'] ?? 'libre')));
                                        $usageLabel = $resolveWhatsAppUsageLabel($usageKey);
                                        $dispatchTime = $resolveDispatchTimeForUsage($usageKey);
                                        $templateState = strtolower(trim((string) ($templateRow['meta_estado'] ?? 'pendiente')));
                                        if (!in_array($templateState, ['pendiente', 'aprobada', 'rechazada', 'error'], true)) {
                                            $templateState = 'error';
                                        }
                                        $stateLabel = match ($templateState) {
                                            'aprobada' => 'Aprobada',
                                            'rechazada' => 'Rechazada',
                                            'error' => 'Error',
                                            default => 'Pendiente',
                                        };
                                        $stateClass = match ($templateState) {
                                            'aprobada' => 'is-approved',
                                            'rechazada' => 'is-rejected',
                                            'error' => 'is-error',
                                            default => 'is-pending',
                                        };
                                        $templateModalId = 'saWaTemplateCenterModal' . ($templateId > 0 ? $templateId : abs((int) crc32((string) ($templateRow['nombre'] ?? 'tpl'))));
                                        ?>
                                        <tr>
                                            <td>
                                                <span class="sa-wa-template-center-name"><?= e((string) ($templateRow['nombre'] ?? 'Sin nombre')) ?></span>
                                                <span class="sa-wa-template-center-meta"><?= e((string) ($templateRow['idioma'] ?? 'es_CO')) ?></span>
                                            </td>
                                            <td><?= e($usageLabel) ?></td>
                                            <td><span class="sa-template-status-badge <?= e($stateClass) ?>"><?= e($stateLabel) ?></span></td>
                                            <td><span class="sa-wa-template-center-time"><?= e($dispatchTime) ?></span></td>
                                            <td class="text-end">
                                                <button class="btn btn-sm btn-outline-primary" type="button" data-bs-toggle="modal" data-bs-target="#<?= e($templateModalId) ?>">
                                                    Ver detalle
                                                </button>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>

                    <?php if ($whatsAppTemplateCenterHiddenCount > 0): ?>
                        <p class="sa-wa-template-center-overflow">
                            Hay más registros fuera de esta tabla corta. Usa “Ver catálogo completo” para gestión masiva.
                        </p>
                    <?php endif; ?>
                </article>
            </div>
        </div>
    </div>
</div>

<?php foreach ($whatsAppTemplateCenterRows as $templateRow): ?>
    <?php
    $templateId = (int) ($templateRow['id'] ?? 0);
    if ($templateId <= 0) {
        continue;
    }
    $usageKey = strtolower(trim((string) ($templateRow['uso'] ?? 'libre')));
    $usageLabel = $resolveWhatsAppUsageLabel($usageKey);
    $templateState = strtolower(trim((string) ($templateRow['meta_estado'] ?? 'pendiente')));
    if (!in_array($templateState, ['pendiente', 'aprobada', 'rechazada', 'error'], true)) {
        $templateState = 'error';
    }
    $stateLabel = match ($templateState) {
        'aprobada' => 'Aprobada',
        'rechazada' => 'Rechazada',
        'error' => 'Error',
        default => 'Pendiente',
    };
    $stateClass = match ($templateState) {
        'aprobada' => 'is-approved',
        'rechazada' => 'is-rejected',
        'error' => 'is-error',
        default => 'is-pending',
    };
    $syncRaw = trim((string) ($templateRow['meta_last_sync_at'] ?? ($templateRow['updated_at'] ?? '')));
    $syncLabel = $syncRaw !== '' ? $syncRaw : 'Sin sincronizar';
    $templateModalId = 'saWaTemplateCenterModal' . $templateId;
    ?>
    <div class="modal fade sa-whatsapp-modal sa-wa-center-detail-modal" id="<?= e($templateModalId) ?>" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <div>
                        <h5 class="modal-title mb-1"><?= e((string) ($templateRow['nombre'] ?? 'Plantilla')) ?></h5>
                        <small class="text-muted">Gestiona enlace, sincronización y envío inmediato de esta plantilla.</small>
                    </div>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                </div>
                <div class="modal-body">
                    <div class="sa-wa-center-detail-grid">
                        <article class="sa-wa-center-detail-card">
                            <h6>Estado y metadata</h6>
                            <p>
                                Estado: <?= e($stateLabel) ?> · Uso actual: <?= e($usageLabel) . PHP_EOL ?>
                                Idioma: <?= e((string) ($templateRow['idioma'] ?? 'es_CO')) . PHP_EOL ?>
                                Meta ID: <?= e((string) ($templateRow['meta_template_id'] ?? 'No asignado')) . PHP_EOL ?>
                                Última sincronización: <?= e($syncLabel) ?>
                            </p>
                        </article>
                        <article class="sa-wa-center-detail-card">
                            <h6>Contenido (resumen)</h6>
                            <p><?= e((string) ($templateRow['cuerpo_texto'] ?? 'Sin contenido local')) ?></p>
                        </article>
                    </div>

                    <div class="sa-wa-center-detail-card mt-2">
                        <h6>Acciones rápidas</h6>
                        <div class="sa-wa-center-action-stack">
                            <form action="<?= e(url('superadmin/whatsapp-meta-templates/' . $templateId . '/enlazar')) ?>" method="post">
                                <?= csrf_field() ?>
                                <input type="hidden" name="link_slot" value="previo_10_dias">
                                <button class="btn btn-sm btn-outline-primary" type="submit">Usar 10 días</button>
                            </form>
                            <form action="<?= e(url('superadmin/whatsapp-meta-templates/' . $templateId . '/enlazar')) ?>" method="post">
                                <?= csrf_field() ?>
                                <input type="hidden" name="link_slot" value="previo_3_dias">
                                <button class="btn btn-sm btn-outline-info" type="submit">Usar 3 días</button>
                            </form>
                            <form action="<?= e(url('superadmin/whatsapp-meta-templates/' . $templateId . '/sincronizar')) ?>" method="post">
                                <?= csrf_field() ?>
                                <button class="btn btn-sm btn-outline-secondary" type="submit">Sincronizar</button>
                            </form>
                            <form action="<?= e(url('superadmin/whatsapp-meta-templates/' . $templateId . '/enlazar')) ?>" method="post" class="d-flex align-items-center gap-1">
                                <?= csrf_field() ?>
                                <input type="number" class="form-control form-control-sm" name="link_days_before_due" min="0" max="365" placeholder="Días" style="width: 90px;">
                                <button class="btn btn-sm btn-outline-dark" type="submit">Enlazar día</button>
                            </form>
                            <?php if ($usageKey !== '' && $usageKey !== 'libre'): ?>
                                <form action="<?= e(url('superadmin/whatsapp-meta-templates/' . $templateId . '/enlazar')) ?>" method="post">
                                    <?= csrf_field() ?>
                                    <input type="hidden" name="link_slot" value="libre">
                                    <button class="btn btn-sm btn-outline-danger" type="submit">Desenlazar</button>
                                </form>
                            <?php endif; ?>
                        </div>

                        <form action="<?= e(url('superadmin/whatsapp-meta-templates/' . $templateId . '/enviar-ahora')) ?>" method="post" class="sa-wa-center-send-now">
                            <?= csrf_field() ?>
                            <h6 class="mb-2">Lanzar ahora</h6>
                            <div class="row g-2">
                                <div class="col-md-6">
                                    <label class="form-label">Número destino</label>
                                    <input type="text" class="form-control" name="send_now_phone" value="<?= e($notificationTestPhoneDefault) ?>" placeholder="3001234567" required>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Nombre</label>
                                    <input type="text" class="form-control" name="send_now_name" value="Cliente">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Valor plan</label>
                                    <input type="number" class="form-control" name="send_now_plan_amount" value="0" min="0" step="0.01">
                                </div>
                                <div class="col-12">
                                    <button class="btn btn-primary btn-sm" type="submit">Enviar ahora</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light border" data-bs-dismiss="modal">Cerrar</button>
                    <span class="sa-template-status-badge <?= e($stateClass) ?>"><?= e($stateLabel) ?></span>
                </div>
            </div>
        </div>
    </div>
<?php endforeach; ?>
</div>

<div class="sa-section <?= $superadminSection === 'whatsapp_manychat' ? 'is-active' : '' ?>" data-sa-section="whatsapp_manychat">
<div class="card border-0 shadow-sm mb-4">
    <div class="card-body">
        <div class="sa-market-hero mb-3">
            <h2 class="sa-market-title">ManyChat</h2>
            <p class="sa-market-subtitle">Vista dedicada ManyChat con cards de integración, operación y soporte.</p>
            <div class="sa-market-stats">
                <div class="sa-market-stat">
                    <small>Proveedor activo</small>
                    <strong><?= $manyChatProviderActive ? 'ManyChat' : 'No activo' ?></strong>
                </div>
                <div class="sa-market-stat">
                    <small>Token</small>
                    <strong><?= $manyChatHasToken ? 'Configurado' : 'Pendiente' ?></strong>
                </div>
                <div class="sa-market-stat">
                    <small>Pendientes</small>
                    <strong><?= e((string) $whatsAppPendingTotal) ?></strong>
                </div>
                <div class="sa-market-stat">
                    <small>Fallidos</small>
                    <strong><?= e((string) $whatsAppFailedTotal) ?></strong>
                </div>
            </div>
        </div>

        <div class="vx-integrations-grid sa-market-grid">
            <article class="card border-0 shadow-sm vx-integration-card vx-integration-card-main">
                <div class="card-body">
                    <div class="d-flex align-items-start gap-3">
                        <span class="vx-integration-logo vx-integration-logo-muted"><i class="bx bx-bot"></i></span>
                        <div>
                            <h2 class="h5 mb-1">Integración ManyChat</h2>
                            <p class="text-muted mb-0 vx-integration-description">Configura API URL y Access Token para envíos por ManyChat.</p>
                        </div>
                    </div>
                    <div class="d-flex flex-wrap gap-2 vx-integration-badges">
                        <span class="badge text-bg-light border">ManyChat API</span>
                    </div>
                    <div class="row g-2">
                        <div class="col-6">
                            <div class="vx-integration-metric">
                                <small>API URL</small>
                                <strong><?= e((string) ($notificationConfig['manychat_api_url'] ?? 'No configurada')) ?></strong>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="vx-integration-metric">
                                <small>Token</small>
                                <strong><?= $manyChatHasToken ? 'Configurado' : 'Pendiente' ?></strong>
                            </div>
                        </div>
                    </div>
                    <div class="sa-market-actions">
                        <span class="badge vx-integration-state <?= $manyChatConfigured ? 'is-active' : 'is-inactive' ?>"><?= $manyChatConfigured ? 'Listo' : 'Pendiente' ?></span>
                        <button class="btn btn-primary vx-integration-integrate-btn sa-market-link-btn" type="button" data-bs-toggle="modal" data-bs-target="#saWhatsAppManyChatModal">
                            <i class="bx bx-link-alt me-1"></i>Integrar
                        </button>
                    </div>
                </div>
            </article>

            <article class="card border-0 shadow-sm vx-integration-card vx-integration-card-main">
                <div class="card-body">
                    <div class="d-flex align-items-start gap-3">
                        <span class="vx-integration-logo vx-integration-logo-muted"><i class="bx bx-user-pin"></i></span>
                        <div>
                            <h2 class="h5 mb-1">Resolución de contactos</h2>
                            <p class="text-muted mb-0 vx-integration-description">Ajusta Message Tag y Custom Field ID para resolver contactos existentes.</p>
                        </div>
                    </div>
                    <div class="d-flex flex-wrap gap-2 vx-integration-badges">
                        <span class="badge text-bg-light border">Operación</span>
                    </div>
                    <div class="row g-2">
                        <div class="col-6">
                            <div class="vx-integration-metric">
                                <small>Message Tag</small>
                                <strong><?= e((string) ($notificationConfig['manychat_message_tag'] ?? 'ACCOUNT_UPDATE')) ?></strong>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="vx-integration-metric">
                                <small>Field ID</small>
                                <strong><?= e((string) ($notificationConfig['manychat_contact_field_id'] ?? 'No definido')) ?></strong>
                            </div>
                        </div>
                    </div>
                    <div class="sa-market-actions">
                        <span class="badge vx-integration-state <?= $manyChatProviderActive ? 'is-active' : 'is-inactive' ?>">
                            <?= $manyChatProviderActive ? 'Activo' : 'Inactivo' ?>
                        </span>
                        <button class="btn btn-outline-primary sa-market-soft-btn" type="button" data-bs-toggle="modal" data-bs-target="#saWhatsAppManyChatModal">
                            Editar opciones
                        </button>
                    </div>
                </div>
            </article>

            <article class="card border-0 shadow-sm vx-integration-card vx-integration-card-main">
                <div class="card-body">
                    <div class="d-flex align-items-start gap-3">
                        <span class="vx-integration-logo vx-integration-logo-muted"><i class="bx bx-send"></i></span>
                        <div>
                            <h2 class="h5 mb-1">Prueba WhatsApp</h2>
                            <p class="text-muted mb-0 vx-integration-description">Prueba rápida para validar entrega al número destino.</p>
                        </div>
                    </div>
                    <div class="d-flex flex-wrap gap-2 vx-integration-badges">
                        <span class="badge text-bg-light border">QA</span>
                    </div>
                    <form action="<?= e(url('superadmin/notificaciones-config/probar-whatsapp')) ?>" method="post" class="sa-market-form-inline">
                        <?= csrf_field() ?>
                        <label class="form-label mb-1">Número destino</label>
                        <input type="text" class="form-control mb-2" name="test_whatsapp_phone" value="<?= e((string) old('test_whatsapp_phone', $notificationTestPhoneDefault)) ?>" placeholder="3001234567">
                        <label class="form-label mb-1">Mensaje</label>
                        <input type="text" class="form-control mb-2" name="test_whatsapp_message" value="<?= e((string) old('test_whatsapp_message', 'Prueba ManyChat desde Veltrix')) ?>" placeholder="Mensaje de prueba">
                        <button class="btn btn-outline-primary w-100" type="submit">Enviar prueba</button>
                    </form>
                    <p class="sa-market-note mb-0 mt-1">Proveedor activo actual: <strong><?= e(strtoupper($selectedWhatsAppProvider)) ?></strong>.</p>
                </div>
            </article>

            <article class="card border-0 shadow-sm vx-integration-card vx-integration-card-main">
                <div class="card-body">
                    <div class="d-flex align-items-start gap-3">
                        <span class="vx-integration-logo vx-integration-logo-muted"><i class="bx bx-slider-alt"></i></span>
                        <div>
                            <h2 class="h5 mb-1">Reintentos y canales</h2>
                            <p class="text-muted mb-0 vx-integration-description">Controla intentos máximos y backoff para reintentos de notificación.</p>
                        </div>
                    </div>
                    <div class="d-flex flex-wrap gap-2 vx-integration-badges">
                        <span class="badge text-bg-light border">Resiliencia</span>
                    </div>
                    <div class="row g-2">
                        <div class="col-6">
                            <div class="vx-integration-metric">
                                <small>Máx intentos</small>
                                <strong><?= e((string) ($notificationConfig['retry_max_attempts'] ?? 3)) ?></strong>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="vx-integration-metric">
                                <small>Backoff</small>
                                <strong><?= e($retryBackoffValue) ?></strong>
                            </div>
                        </div>
                    </div>
                    <div class="sa-market-actions">
                        <span class="badge vx-integration-state <?= !empty($notificationConfig['channel_whatsapp']) ? 'is-active' : 'is-inactive' ?>">
                            <?= !empty($notificationConfig['channel_whatsapp']) ? 'Canal activo' : 'Canal off' ?>
                        </span>
                        <a class="btn btn-outline-primary sa-market-soft-btn" href="<?= e(url('superadmin') . '?seccion=notificaciones') ?>">Abrir hub</a>
                    </div>
                </div>
            </article>

            <article class="card border-0 shadow-sm vx-integration-card vx-integration-card-main">
                <div class="card-body">
                    <div class="d-flex align-items-start gap-3">
                        <span class="vx-integration-logo vx-integration-logo-image"><img src="<?= e($openAiLogo) ?>" alt="OpenAI"></span>
                        <div>
                            <h2 class="h5 mb-1">Asistente OpenAI</h2>
                            <p class="text-muted mb-0 vx-integration-description">Apoya soporte y operación con respuestas automáticas asistidas.</p>
                        </div>
                    </div>
                    <div class="d-flex flex-wrap gap-2 vx-integration-badges">
                        <span class="badge text-bg-light border">IA</span>
                    </div>
                    <div class="row g-2">
                        <div class="col-6">
                            <div class="vx-integration-metric">
                                <small>Estado</small>
                                <strong><?= $openAiConfigured ? 'Disponible' : 'Pendiente' ?></strong>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="vx-integration-metric">
                                <small>Preguntas hoy</small>
                                <strong><?= e((string) ((int) ($openAiReportUsage['day_questions'] ?? 0))) ?></strong>
                            </div>
                        </div>
                    </div>
                    <div class="sa-market-actions">
                        <span class="badge vx-integration-state <?= $openAiConfigured ? 'is-active' : 'is-inactive' ?>"><?= $openAiConfigured ? 'Activo' : 'Inactivo' ?></span>
                        <a class="btn btn-outline-primary sa-market-soft-btn" href="<?= e(url('superadmin') . '?seccion=ai') ?>">Ir a IA</a>
                    </div>
                </div>
            </article>

            <article class="card border-0 shadow-sm vx-integration-card vx-integration-card-main">
                <div class="card-body">
                    <div class="d-flex align-items-start gap-3">
                        <span class="vx-integration-logo vx-integration-logo-image"><img src="<?= e($wompiLogo) ?>" alt="Wompi"></span>
                        <div>
                            <h2 class="h5 mb-1">Wompi checkout</h2>
                            <p class="text-muted mb-0 vx-integration-description">Conecta pagos para renovaciones y soporte de cobranza.</p>
                        </div>
                    </div>
                    <div class="d-flex flex-wrap gap-2 vx-integration-badges">
                        <span class="badge text-bg-light border">Checkout</span>
                    </div>
                    <div class="row g-2">
                        <div class="col-6">
                            <div class="vx-integration-metric">
                                <small>Estado</small>
                                <strong><?= $wompiConfigured ? 'Disponible' : 'Pendiente' ?></strong>
                            </div>
                        </div>
                        <div class="col-6">
                            <div class="vx-integration-metric">
                                <small>Avisos totales</small>
                                <strong><?= e((string) $whatsAppQueueTotal) ?></strong>
                            </div>
                        </div>
                    </div>
                    <div class="sa-market-actions">
                        <span class="badge vx-integration-state <?= $wompiConfigured ? 'is-active' : 'is-inactive' ?>"><?= $wompiConfigured ? 'Activo' : 'Inactivo' ?></span>
                        <a class="btn btn-outline-primary sa-market-soft-btn" href="<?= e(url('superadmin') . '?seccion=wompi') ?>">Ir a Wompi</a>
                    </div>
                </div>
            </article>
        </div>
</div>
</div>
</div>

<div class="modal fade sa-correo-modal" id="saCorreoSmtpModal" tabindex="-1" aria-labelledby="saCorreoSmtpModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content">
            <form action="<?= e(url('superadmin/correo-config')) ?>" method="post">
                <?= csrf_field() ?>
                <div class="modal-header">
                    <div class="d-flex align-items-center gap-2">
                        <span class="sa-integration-logo"><img src="<?= e($gmailLogo) ?>" alt="Gmail"></span>
                        <div>
                            <h5 class="modal-title" id="saCorreoSmtpModalLabel">Configuración SMTP</h5>
                            <small class="text-muted">Configura proveedor, remitente y prueba de correo desde modal.</small>
                        </div>
                    </div>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                </div>
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-4">
                            <label class="form-label">SMTP_HOST</label>
                            <input type="text" class="form-control" name="notify_smtp_host" value="<?= e($smtpHost) ?>" placeholder="smtp.gmail.com" maxlength="190" required>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">SMTP_PORT</label>
                            <input type="number" class="form-control" name="notify_smtp_port" value="<?= e($smtpPort) ?>" min="1" max="65535" required>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">SMTP_SECURE</label>
                            <select class="form-select" name="notify_smtp_secure">
                                <option value="tls" <?= $smtpSecure === 'tls' ? 'selected' : '' ?>>tls</option>
                                <option value="ssl" <?= $smtpSecure === 'ssl' ? 'selected' : '' ?>>ssl</option>
                                <option value="none" <?= $smtpSecure === 'none' ? 'selected' : '' ?>>none</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">SMTP_USERNAME</label>
                            <input type="text" class="form-control" name="notify_smtp_username" value="<?= e($smtpUsername) ?>" placeholder="correo@dominio.com" maxlength="190">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">SMTP_PASSWORD</label>
                            <input type="password" class="form-control" name="notify_smtp_password" autocomplete="new-password" placeholder="Deja en blanco para conservar la actual" maxlength="255">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">SMTP_FROM_EMAIL</label>
                            <input type="email" class="form-control" name="notify_smtp_from_email" value="<?= e($smtpFromEmail) ?>" placeholder="no-reply@tuempresa.com" maxlength="190" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">SMTP_FROM_NAME</label>
                            <input type="text" class="form-control" name="notify_smtp_from_name" value="<?= e($smtpFromName) ?>" placeholder="Veltrix POS" maxlength="120" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Correo de prueba</label>
                            <input type="email" class="form-control" name="smtp_test_email" value="<?= e((string) ($smtpConfig['test_email_default'] ?? '')) ?>" placeholder="destino@correo.com">
                        </div>
                        <div class="col-12">
                            <small class="text-muted d-block">Tip: para Gmail usa contraseña de aplicación y seguridad <code>tls</code> con puerto <code>587</code>.</small>
                            <small class="text-muted d-block">El botón <strong>Probar SMTP</strong> usa la configuración SMTP guardada actualmente.</small>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light border" data-bs-dismiss="modal">Cerrar</button>
                    <button class="btn btn-outline-primary" type="submit" formaction="<?= e(url('superadmin/correo-config/probar')) ?>" formmethod="post">Probar SMTP</button>
                    <button class="btn btn-primary" type="submit">Guardar configuración SMTP</button>
                </div>
            </form>
</div>
</div>
</div>

<div class="modal fade sa-whatsapp-modal sa-template-link-modal" id="saWhatsAppTemplateLinkModal" tabindex="-1" aria-labelledby="saWhatsAppTemplateLinkModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <div class="d-flex align-items-center gap-2">
                    <span class="sa-integration-logo"><img src="<?= e((string) url('assets/img/integrations/logo-facebook.webp')) ?>" alt="Meta"></span>
                    <div>
                        <h5 class="modal-title" id="saWhatsAppTemplateLinkModalLabel">Enlazar plantillas ya creadas en Meta</h5>
                        <small class="text-muted">Sincroniza catálogo de Meta y conecta cada plantilla al flujo automático de recordatorios.</small>
                    </div>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>
            <div class="modal-body">
                <section class="sa-template-link-intro">
                    <div class="sa-template-link-intro-copy">
                        <span class="sa-template-link-kicker">Flujo recomendado</span>
                        <h6>Sincroniza y enlaza en segundos</h6>
                        <p>Primero trae las plantillas activas desde Meta y luego asigna cada una al tipo de aviso que quieres automatizar.</p>
                        <div class="sa-template-link-steps">
                            <span class="sa-template-link-step">1. Sincronizar catálogo</span>
                            <span class="sa-template-link-step">2. Enlazar por tipo</span>
                            <span class="sa-template-link-step">3. Guardado automático</span>
                        </div>
                    </div>
                    <form action="<?= e(url('superadmin/whatsapp-meta-templates/sincronizar-meta')) ?>" method="post" class="sa-template-link-sync-form">
                        <?= csrf_field() ?>
                        <div>
                            <label class="form-label">Límite</label>
                            <input type="number" class="form-control form-control-sm" name="meta_sync_limit" value="120" min="1" max="250">
                        </div>
                        <button type="submit" class="btn btn-primary">Sincronizar catálogo</button>
                    </form>
                </section>

                <section class="sa-template-link-stats">
                    <article class="sa-template-link-stat">
                        <small>Plantillas en sistema</small>
                        <strong><?= e((string) $whatsAppTemplateTotalCount) ?></strong>
                    </article>
                    <article class="sa-template-link-stat">
                        <small>Enlazadas</small>
                        <strong><?= e((string) $whatsAppTemplateLinkedCount) ?></strong>
                    </article>
                    <article class="sa-template-link-stat">
                        <small>Libres</small>
                        <strong><?= e((string) $whatsAppTemplateFreeCount) ?></strong>
                    </article>
                    <article class="sa-template-link-stat">
                        <small>Aprobadas en Meta</small>
                        <strong><?= e((string) $whatsAppTemplateApprovedCount) ?></strong>
                    </article>
                </section>

                <div class="table-responsive sa-template-table-wrap sa-template-link-table-wrap">
                    <table class="table table-sm align-middle sa-template-table mb-0">
                        <thead>
                            <tr>
                                <th>Plantilla</th>
                                <th>Idioma</th>
                                <th>Estado</th>
                                <th>Uso actual</th>
                                <th class="text-end">Acciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($whatsAppMetaTemplates === []) : ?>
                                <tr>
                                    <td colspan="5" class="text-center text-muted py-3">No hay plantillas en el sistema. Usa “Sincronizar catálogo”.</td>
                                </tr>
                            <?php else : ?>
                                <?php foreach ($whatsAppMetaTemplates as $templateRow) : ?>
                                    <?php
                                    $templateId = (int) ($templateRow['id'] ?? 0);
                                    $usageKey = strtolower(trim((string) ($templateRow['uso'] ?? 'libre')));
                                    $usageLabel = $resolveWhatsAppUsageLabel($usageKey);
                                    $templateState = strtolower(trim((string) ($templateRow['meta_estado'] ?? 'pendiente')));
                                    if (!in_array($templateState, ['pendiente', 'aprobada', 'rechazada', 'error'], true)) {
                                        $templateState = 'error';
                                    }
                                    $stateLabel = match ($templateState) {
                                        'aprobada' => 'Aprobada',
                                        'rechazada' => 'Rechazada',
                                        'error' => 'Error',
                                        default => 'Pendiente',
                                    };
                                    $stateClass = match ($templateState) {
                                        'aprobada' => 'is-approved',
                                        'rechazada' => 'is-rejected',
                                        'error' => 'is-error',
                                        default => 'is-pending',
                                    };
                                    $isLinked10 = $usageKey === 'previo_10_dias';
                                    $isLinked3 = $usageKey === 'previo_3_dias';
                                    $isLinkedAny = $usageKey !== '' && $usageKey !== 'libre';
                                    ?>
                                    <tr>
                                        <td class="sa-template-cell-wrap">
                                            <span class="sa-template-table-title"><?= e((string) ($templateRow['nombre'] ?? '')) ?></span>
                                            <?php if (trim((string) ($templateRow['meta_template_id'] ?? '')) !== '') : ?>
                                                <span class="sa-template-meta-id">Meta ID: <?= e((string) $templateRow['meta_template_id']) ?></span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span class="sa-template-language-chip"><?= e((string) ($templateRow['idioma'] ?? 'es_CO')) ?></span>
                                        </td>
                                        <td>
                                            <span class="sa-template-status-badge <?= e($stateClass) ?>"><?= e($stateLabel) ?></span>
                                            <?php if (trim((string) ($templateRow['meta_estado_detalle'] ?? '')) !== '') : ?>
                                                <small class="sa-template-state-detail"><?= e((string) $templateRow['meta_estado_detalle']) ?></small>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($isLinkedAny) : ?>
                                                <span class="sa-template-usage-badge"><?= e($usageLabel) ?></span>
                                            <?php else : ?>
                                                <span class="sa-template-usage-free">Libre</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-end">
                                            <div class="sa-template-actions">
                                                <div class="sa-template-actions-main">
                                                    <form action="<?= e(url('superadmin/whatsapp-meta-templates/' . $templateId . '/enlazar')) ?>" method="post" class="d-inline">
                                                        <?= csrf_field() ?>
                                                        <input type="hidden" name="return_modal" value="template_link">
                                                        <input type="hidden" name="link_slot" value="previo_10_dias">
                                                        <button class="btn btn-sm <?= $isLinked10 ? 'btn-primary' : 'btn-outline-primary' ?>" type="submit" <?= $isLinked10 ? 'disabled' : '' ?>><?= $isLinked10 ? 'En uso 10 días' : 'Usar 10 días' ?></button>
                                                    </form>
                                                    <form action="<?= e(url('superadmin/whatsapp-meta-templates/' . $templateId . '/enlazar')) ?>" method="post" class="d-inline">
                                                        <?= csrf_field() ?>
                                                        <input type="hidden" name="return_modal" value="template_link">
                                                        <input type="hidden" name="link_slot" value="previo_3_dias">
                                                        <button class="btn btn-sm <?= $isLinked3 ? 'btn-info' : 'btn-outline-info' ?>" type="submit" <?= $isLinked3 ? 'disabled' : '' ?>><?= $isLinked3 ? 'En uso 3 días' : 'Usar 3 días' ?></button>
                                                    </form>
                                                    <form action="<?= e(url('superadmin/whatsapp-meta-templates/' . $templateId . '/sincronizar')) ?>" method="post" class="d-inline">
                                                        <?= csrf_field() ?>
                                                        <input type="hidden" name="return_modal" value="template_link">
                                                        <button class="btn btn-sm btn-outline-secondary" type="submit">Sincronizar</button>
                                                    </form>
                                                </div>
                                                <div class="sa-template-actions-secondary">
                                                    <form action="<?= e(url('superadmin/whatsapp-meta-templates/' . $templateId . '/enlazar')) ?>" method="post" class="d-inline-flex gap-1 align-items-center">
                                                        <?= csrf_field() ?>
                                                        <input type="hidden" name="return_modal" value="template_link">
                                                        <input type="number" class="form-control form-control-sm" name="link_days_before_due" min="0" max="365" placeholder="días">
                                                        <button class="btn btn-sm btn-outline-dark" type="submit">Enlazar día</button>
                                                    </form>
                                                    <?php if ($isLinkedAny) : ?>
                                                        <form action="<?= e(url('superadmin/whatsapp-meta-templates/' . $templateId . '/enlazar')) ?>" method="post" class="d-inline">
                                                            <?= csrf_field() ?>
                                                            <input type="hidden" name="return_modal" value="template_link">
                                                            <input type="hidden" name="link_slot" value="libre">
                                                            <button class="btn btn-sm btn-outline-danger" type="submit">Desenlazar</button>
                                                        </form>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <div class="sa-template-mobile-list mt-2">
                    <?php if ($whatsAppMetaTemplates === []) : ?>
                        <div class="sa-template-mobile-card">
                            <p class="text-muted mb-0">No hay plantillas en el sistema. Usa “Sincronizar catálogo”.</p>
                        </div>
                    <?php else : ?>
                        <?php foreach ($whatsAppMetaTemplates as $templateRow) : ?>
                            <?php
                            $templateId = (int) ($templateRow['id'] ?? 0);
                            $usageKey = strtolower(trim((string) ($templateRow['uso'] ?? 'libre')));
                            $usageLabel = $resolveWhatsAppUsageLabel($usageKey);
                            $templateState = strtolower(trim((string) ($templateRow['meta_estado'] ?? 'pendiente')));
                            if (!in_array($templateState, ['pendiente', 'aprobada', 'rechazada', 'error'], true)) {
                                $templateState = 'error';
                            }
                            $stateLabel = match ($templateState) {
                                'aprobada' => 'Aprobada',
                                'rechazada' => 'Rechazada',
                                'error' => 'Error',
                                default => 'Pendiente',
                            };
                            $stateClass = match ($templateState) {
                                'aprobada' => 'is-approved',
                                'rechazada' => 'is-rejected',
                                'error' => 'is-error',
                                default => 'is-pending',
                            };
                            $isLinked10 = $usageKey === 'previo_10_dias';
                            $isLinked3 = $usageKey === 'previo_3_dias';
                            $isLinkedAny = $usageKey !== '' && $usageKey !== 'libre';
                            ?>
                            <article class="sa-template-mobile-card">
                                <div class="sa-template-mobile-head">
                                    <div>
                                        <h3 class="sa-template-mobile-title"><?= e((string) ($templateRow['nombre'] ?? '')) ?></h3>
                                        <p class="sa-template-mobile-meta">Idioma: <?= e((string) ($templateRow['idioma'] ?? 'es_CO')) ?></p>
                                    </div>
                                    <span class="sa-template-status-badge <?= e($stateClass) ?>"><?= e($stateLabel) ?></span>
                                </div>
                                <div class="sa-template-mobile-chips">
                                    <?php if ($isLinkedAny) : ?><span class="sa-template-mobile-chip"><?= e($usageLabel) ?></span><?php endif; ?>
                                </div>
                                <div class="sa-template-mobile-actions">
                                    <form action="<?= e(url('superadmin/whatsapp-meta-templates/' . $templateId . '/enlazar')) ?>" method="post">
                                        <?= csrf_field() ?>
                                        <input type="hidden" name="return_modal" value="template_link">
                                        <input type="hidden" name="link_slot" value="previo_10_dias">
                                        <button class="btn btn-sm <?= $isLinked10 ? 'btn-primary' : 'btn-outline-primary' ?>" type="submit" <?= $isLinked10 ? 'disabled' : '' ?>><?= $isLinked10 ? 'En uso 10 días' : 'Usar 10 días' ?></button>
                                    </form>
                                    <form action="<?= e(url('superadmin/whatsapp-meta-templates/' . $templateId . '/enlazar')) ?>" method="post">
                                        <?= csrf_field() ?>
                                        <input type="hidden" name="return_modal" value="template_link">
                                        <input type="hidden" name="link_slot" value="previo_3_dias">
                                        <button class="btn btn-sm <?= $isLinked3 ? 'btn-info' : 'btn-outline-info' ?>" type="submit" <?= $isLinked3 ? 'disabled' : '' ?>><?= $isLinked3 ? 'En uso 3 días' : 'Usar 3 días' ?></button>
                                    </form>
                                    <form action="<?= e(url('superadmin/whatsapp-meta-templates/' . $templateId . '/enlazar')) ?>" method="post" class="d-flex gap-1">
                                        <?= csrf_field() ?>
                                        <input type="hidden" name="return_modal" value="template_link">
                                        <input type="number" class="form-control form-control-sm" name="link_days_before_due" min="0" max="365" placeholder="Días">
                                        <button class="btn btn-sm btn-outline-dark" type="submit">Enlazar día</button>
                                    </form>
                                    <?php if ($isLinkedAny) : ?>
                                        <form action="<?= e(url('superadmin/whatsapp-meta-templates/' . $templateId . '/enlazar')) ?>" method="post">
                                            <?= csrf_field() ?>
                                            <input type="hidden" name="return_modal" value="template_link">
                                            <input type="hidden" name="link_slot" value="libre">
                                            <button class="btn btn-sm btn-outline-danger" type="submit">Desenlazar</button>
                                        </form>
                                    <?php endif; ?>
                                </div>
                            </article>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light border" data-bs-dismiss="modal">Cerrar</button>
                <button type="button" class="btn btn-outline-primary" data-bs-dismiss="modal" data-bs-toggle="modal" data-bs-target="#saWhatsAppTemplateBuilderModal">Crear nueva plantilla</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade sa-whatsapp-modal" id="saWhatsAppTemplateBuilderModal" tabindex="-1" aria-labelledby="saWhatsAppTemplateBuilderModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content">
            <form action="<?= e(url('superadmin/whatsapp-meta-templates')) ?>" method="post" id="saWhatsAppTemplateBuilderForm">
                <?= csrf_field() ?>
                <div class="modal-header">
                    <div class="d-flex align-items-center gap-2">
                        <span class="sa-integration-logo"><img src="<?= e((string) url('assets/img/integrations/logo-facebook.webp')) ?>" alt="Meta"></span>
                        <div>
                            <h5 class="modal-title" id="saWhatsAppTemplateBuilderModalLabel">Editar plantilla (Veltrix + Meta)</h5>
                            <small class="text-muted">1) Se crea en Veltrix, 2) se envia a Meta automaticamente, 3) ves el estado en este panel.</small>
                        </div>
                    </div>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                </div>
                <div class="modal-body">
                    <div class="sa-template-flow">
                        <span class="sa-template-step is-done">1. Crear en Veltrix</span>
                        <span class="sa-template-step is-active">2. Enviar a Meta</span>
                        <span class="sa-template-step">3. Estado (Pendiente/Aprobada/Rechazada)</span>
                    </div>

                    <div class="sa-template-layout">
                        <div class="sa-template-editor">
                            <div class="row g-3">
                                <div class="col-md-4">
                                    <label class="form-label">Uso inicial</label>
                                    <input type="hidden" name="template_usage" value="libre">
                                    <input type="text" class="form-control" value="Libre (enlaza luego por días)" readonly>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Idioma</label>
                                    <input
                                        type="text"
                                        class="form-control"
                                        name="template_language"
                                        id="template_language"
                                        value="<?= e((string) old('template_language', (string) ($notificationConfig['whatsapp_template_language'] ?? 'es_CO'))) ?>"
                                        maxlength="10"
                                        placeholder="es_CO"
                                    >
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">Categoria Meta</label>
                                    <?php $oldCategory = strtoupper((string) old('template_category', 'UTILITY')); ?>
                                    <select class="form-select" name="template_category" id="template_category">
                                        <option value="UTILITY" <?= $oldCategory === 'UTILITY' ? 'selected' : '' ?>>UTILITY</option>
                                        <option value="MARKETING" <?= $oldCategory === 'MARKETING' ? 'selected' : '' ?>>MARKETING</option>
                                        <option value="AUTHENTICATION" <?= $oldCategory === 'AUTHENTICATION' ? 'selected' : '' ?>>AUTHENTICATION</option>
                                    </select>
                                </div>

                                <div class="col-md-12">
                                    <label class="form-label">Nombre de plantilla</label>
                                    <input
                                        type="text"
                                        class="form-control"
                                        name="template_name"
                                        id="template_name"
                                        value="<?= e((string) old('template_name', '')) ?>"
                                        maxlength="120"
                                        placeholder="en_10_dias_vence_tu_suscripcion"
                                    >
                                    <small class="text-muted">Solo minusculas, numeros y guion bajo.</small>
                                </div>

                                <div class="col-md-12">
                                    <label class="form-label">Encabezado (opcional)</label>
                                    <input
                                        type="text"
                                        class="form-control"
                                        name="template_header_text"
                                        id="template_header_text"
                                        value="<?= e((string) old('template_header_text', '')) ?>"
                                        maxlength="120"
                                        placeholder="En 10 dias vence tu suscripcion"
                                    >
                                </div>
                                <div class="col-md-12">
                                    <label class="form-label">Cuerpo</label>
                                    <textarea
                                        class="form-control"
                                        rows="7"
                                        name="template_body_text"
                                        id="template_body_text"
                                        maxlength="1024"
                                        placeholder="Hola {{1}}, tu suscripcion vence el {{2}}..."
                                    ><?= e((string) old('template_body_text', '')) ?></textarea>
                                    <small class="text-muted">Puedes usar variables con formato {{1}}, {{2}}, {{3}}.</small>
                                </div>
                                <div class="col-md-12">
                                    <label class="form-label">Pie de pagina (opcional)</label>
                                    <input
                                        type="text"
                                        class="form-control"
                                        name="template_footer_text"
                                        id="template_footer_text"
                                        value="<?= e((string) old('template_footer_text', '')) ?>"
                                        maxlength="120"
                                        placeholder="Aplican terminos y condiciones"
                                    >
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">Texto boton URL (opcional)</label>
                                    <input
                                        type="text"
                                        class="form-control"
                                        name="template_button_text"
                                        id="template_button_text"
                                        value="<?= e((string) old('template_button_text', 'Pagar enlace')) ?>"
                                        maxlength="30"
                                        placeholder="Pagar enlace"
                                    >
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">URL boton (opcional)</label>
                                    <input
                                        type="url"
                                        class="form-control"
                                        name="template_button_url"
                                        id="template_button_url"
                                        value="<?= e((string) old('template_button_url', '')) ?>"
                                        maxlength="255"
                                        placeholder="https://checkout.wompi.co/p/..."
                                    >
                                </div>
                                <div class="col-md-12">
                                    <label class="form-label">Muestras variables (opcional)</label>
                                    <textarea
                                        class="form-control"
                                        rows="2"
                                        name="template_variable_examples"
                                        id="template_variable_examples"
                                        placeholder="Daniel&#10;Abril&#10;14 de abril de 2026"
                                    ><?= e((string) old('template_variable_examples', '')) ?></textarea>
                                    <small class="text-muted">Una muestra por linea (Meta las usa para revision).</small>
                                </div>
                                <input type="hidden" name="template_auto_assign" value="0">
                            </div>
                        </div>

                        <div class="sa-template-preview">
                            <div class="sa-template-phone">
                                <div class="sa-template-phone-title">Vista previa interna</div>
                                <div class="sa-template-phone-header" id="saTemplatePreviewHeader">Encabezado</div>
                                <div class="sa-template-phone-body" id="saTemplatePreviewBody">Escribe el cuerpo de la plantilla para ver la previsualizacion.</div>
                                <div class="sa-template-phone-footer" id="saTemplatePreviewFooter">Pie de pagina</div>
                                <a href="#" class="sa-template-phone-button is-hidden" id="saTemplatePreviewButton" target="_blank" rel="noopener">Boton URL</a>
                            </div>
                            <p class="sa-market-note mt-2 mb-0">El estado se actualiza en la tabla principal y puedes forzar sincronizacion con el boton <strong>Sincronizar</strong>.</p>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light border" data-bs-dismiss="modal">Cerrar</button>
                    <button type="submit" class="btn btn-primary">Crear en Veltrix y enviar a Meta</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade sa-whatsapp-modal" id="saWhatsAppMetaModal" tabindex="-1" aria-labelledby="saWhatsAppMetaModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content">
            <form action="<?= e(url('superadmin/notificaciones-config')) ?>" method="post">
                <?= csrf_field() ?>
                <input type="hidden" name="notify_whatsapp_provider" value="meta">
                <input type="hidden" name="notify_channel_email" value="<?= !empty($notificationConfig['channel_email']) ? '1' : '0' ?>">
                <input type="hidden" name="notify_channel_whatsapp" value="<?= !empty($notificationConfig['channel_whatsapp']) ? '1' : '0' ?>">
                <div class="modal-header">
                    <div class="d-flex align-items-center gap-2">
                        <span class="sa-integration-logo"><img src="<?= e((string) url('assets/img/integrations/logo-facebook.webp')) ?>" alt="Meta"></span>
                        <div>
                            <h5 class="modal-title" id="saWhatsAppMetaModalLabel">WhatsApp - Meta Cloud API</h5>
                            <small class="text-muted">Configuración directa del canal oficial de WhatsApp Business.</small>
                        </div>
                    </div>
                    <div class="d-flex align-items-center gap-2">
                        <span class="sa-modal-provider-badge">Proveedor activo: Meta</span>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                    </div>
                </div>
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-12">
                            <label class="form-label">URL API Meta</label>
                            <input type="url" class="form-control" name="notify_whatsapp_api_url" value="<?= e((string) ($notificationConfig['whatsapp_api_url'] ?? 'https://graph.facebook.com/v20.0')) ?>" placeholder="https://graph.facebook.com/v20.0">
                        </div>
                        <div class="col-md-8">
                            <label class="form-label">Phone Number ID</label>
                            <input type="text" class="form-control" name="notify_whatsapp_phone_number_id" value="<?= e((string) ($notificationConfig['whatsapp_phone_number_id'] ?? '')) ?>" placeholder="123456789012345">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Código país</label>
                            <input type="text" class="form-control" name="notify_whatsapp_default_country_code" value="<?= e((string) ($notificationConfig['whatsapp_default_country_code'] ?? '57')) ?>" maxlength="5" placeholder="57">
                        </div>
                        <div class="col-md-12">
                            <label class="form-label">WhatsApp Business Account ID (WABA) (opcional)</label>
                            <input type="text" class="form-control" name="notify_whatsapp_business_account_id" value="<?= e((string) ($notificationConfig['whatsapp_business_account_id'] ?? '')) ?>" placeholder="123456789012345">
                            <small class="text-muted d-block mt-1">Recomendado para enlazar plantillas: evita depender de auto-resolución del WABA desde Phone Number ID.</small>
                        </div>
                        <div class="col-md-12">
                            <label class="form-label">Access Token Meta</label>
                            <input type="password" class="form-control" name="notify_whatsapp_access_token" autocomplete="off" placeholder="Pega token nuevo para actualizar">
                            <small class="text-muted d-block mt-1">Actual: <?= e((string) ($notificationConfig['whatsapp_access_token_masked'] ?? 'No configurado')) ?>. Si lo dejas vacío, se conserva.</small>
                        </div>
                        <div class="col-md-12">
                            <input type="hidden" name="notify_whatsapp_template_enabled" value="0">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" name="notify_whatsapp_template_enabled" id="sa_whatsapp_template_enabled_modal" value="1" <?= !empty($notificationConfig['whatsapp_template_enabled']) ? 'checked' : '' ?>>
                                <label class="form-check-label" for="sa_whatsapp_template_enabled_modal">Enviar plantillas automáticas para avisos de suscripción</label>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Idioma plantilla</label>
                            <input type="text" class="form-control" name="notify_whatsapp_template_language" value="<?= e((string) ($notificationConfig['whatsapp_template_language'] ?? 'es_CO')) ?>" maxlength="10" placeholder="es_CO">
                        </div>
                        <div class="col-md-8">
                            <label class="form-label">Gestión de enlaces</label>
                            <div class="form-control d-flex align-items-center justify-content-between" style="min-height: 40px;">
                                <span class="text-muted">Abre el Centro de enlace para ajustar uso por días, hora de salida y envío inmediato.</span>
                                <a
                                    class="btn btn-sm btn-outline-primary"
                                    href="<?= e(url('superadmin') . '?seccion=whatsapp_meta_templates') ?>"
                                >
                                    Enlazar desde Meta
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light border" data-bs-dismiss="modal">Cerrar</button>
                    <button type="submit" class="btn btn-primary">Guardar Meta Cloud API</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade sa-whatsapp-modal" id="saWhatsAppManyChatModal" tabindex="-1" aria-labelledby="saWhatsAppManyChatModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content">
            <form action="<?= e(url('superadmin/notificaciones-config')) ?>" method="post">
                <?= csrf_field() ?>
                <input type="hidden" name="notify_whatsapp_provider" value="manychat">
                <input type="hidden" name="notify_channel_email" value="<?= !empty($notificationConfig['channel_email']) ? '1' : '0' ?>">
                <input type="hidden" name="notify_channel_whatsapp" value="<?= !empty($notificationConfig['channel_whatsapp']) ? '1' : '0' ?>">
                <input type="hidden" name="notify_whatsapp_template_enabled" value="<?= !empty($notificationConfig['whatsapp_template_enabled']) ? '1' : '0' ?>">
                <div class="modal-header">
                    <div class="d-flex align-items-center gap-2">
                        <span class="sa-integration-logo"><i class="bx bx-bot"></i></span>
                        <div>
                            <h5 class="modal-title" id="saWhatsAppManyChatModalLabel">WhatsApp - ManyChat API</h5>
                            <small class="text-muted">Automatización con ManyChat para resoluciones por contacto.</small>
                        </div>
                    </div>
                    <div class="d-flex align-items-center gap-2">
                        <span class="sa-modal-provider-badge">Proveedor activo: ManyChat</span>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                    </div>
                </div>
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-12">
                            <label class="form-label">URL API ManyChat</label>
                            <input type="url" class="form-control" name="notify_manychat_api_url" value="<?= e((string) ($notificationConfig['manychat_api_url'] ?? 'https://api.manychat.com')) ?>" placeholder="https://api.manychat.com">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Message Tag</label>
                            <input type="text" class="form-control" name="notify_manychat_message_tag" value="<?= e((string) ($notificationConfig['manychat_message_tag'] ?? 'ACCOUNT_UPDATE')) ?>" maxlength="80" placeholder="ACCOUNT_UPDATE">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Custom Field ID</label>
                            <input type="text" class="form-control" name="notify_manychat_contact_field_id" value="<?= e((string) ($notificationConfig['manychat_contact_field_id'] ?? '')) ?>" maxlength="20" placeholder="Opcional">
                        </div>
                        <div class="col-md-12">
                            <label class="form-label">Access Token ManyChat</label>
                            <input type="password" class="form-control" name="notify_manychat_access_token" autocomplete="off" placeholder="Pega token nuevo para actualizar">
                            <small class="text-muted d-block mt-1">Actual: <?= e((string) ($notificationConfig['manychat_access_token_masked'] ?? 'No configurado')) ?>. Si lo dejas vacío, se conserva.</small>
                            <small class="text-muted d-block">Si el contacto ya existe y no retorna subscriber_id, define el Custom Field ID para resolverlo.</small>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light border" data-bs-dismiss="modal">Cerrar</button>
                    <button type="submit" class="btn btn-primary">Guardar ManyChat</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="sa-section <?= $superadminSection === 'ai' ? 'is-active' : '' ?>" data-sa-section="ai">
<div class="card border-0 shadow-sm mb-4">
    <div class="card-body">
        <div class="d-flex flex-wrap align-items-start justify-content-between gap-2 mb-3">
            <div>
                <h2 class="h5 mb-1">Agente IA de ayuda</h2>
                <p class="text-muted mb-0">Configura el asistente para resolver dudas funcionales del software dentro de la plataforma.</p>
            </div>
            <span class="badge <?= !empty($aiConfig['is_ready']) ? 'text-bg-success' : 'text-bg-warning' ?>">
                <?= !empty($aiConfig['is_ready']) ? 'Listo para uso interno' : 'Pendiente de configuración' ?>
            </span>
        </div>

        <div class="row g-3 mb-3">
            <div class="col-md-3">
                <div class="p-3 rounded border bg-light h-100">
                    <small class="text-muted d-block">Estado</small>
                    <strong><?= !empty($aiConfig['enabled']) ? 'Activo' : 'Inactivo' ?></strong>
                    <div class="small text-muted">Proveedor: <?= e(strtoupper((string) ($aiConfig['provider'] ?? 'OPENAI'))) ?></div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="p-3 rounded border bg-light h-100">
                    <small class="text-muted d-block">Modelo</small>
                    <strong><?= e((string) ($aiConfig['model'] ?? 'gpt-4o-mini')) ?></strong>
                    <div class="small text-muted">Temperatura: <?= e((string) ($aiConfig['temperature'] ?? '0.2')) ?></div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="p-3 rounded border bg-light h-100">
                    <small class="text-muted d-block">API key</small>
                    <strong><?= e((string) ($aiConfig['api_key_masked'] ?? 'No configurada')) ?></strong>
                    <div class="small text-muted"><?= !empty($aiConfig['has_api_key']) ? 'Configurada' : 'Falta configurar' ?></div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="p-3 rounded border bg-light h-100">
                    <small class="text-muted d-block">Max output tokens</small>
                    <strong><?= e((string) ($aiConfig['max_output_tokens'] ?? 700)) ?></strong>
                    <div class="small text-muted">URL base: <?= e((string) ($aiConfig['base_url'] ?? 'https://api.openai.com/v1')) ?></div>
                </div>
            </div>
        </div>

        <?php $aiProvider = strtolower((string) ($aiConfig['provider'] ?? 'openai')); ?>
        <form action="<?= e(url('superadmin/ia-config')) ?>" method="post" class="row g-2 mb-3">
            <?= csrf_field() ?>
            <div class="col-md-3">
                <label class="form-label">Proveedor IA</label>
                <select class="form-select" name="ai_provider">
                    <option value="openai" <?= $aiProvider === 'openai' ? 'selected' : '' ?>>OpenAI</option>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label d-block">Asistente activo</label>
                <div class="form-check form-switch mt-2">
                    <input class="form-check-input" type="checkbox" role="switch" id="ai_enabled" name="ai_enabled" value="1" <?= !empty($aiConfig['enabled']) ? 'checked' : '' ?>>
                    <label class="form-check-label" for="ai_enabled">Habilitar agente IA</label>
                </div>
            </div>
            <div class="col-md-3">
                <label class="form-label">Modelo</label>
                <input type="text" class="form-control" name="ai_model" value="<?= e((string) ($aiConfig['model'] ?? 'gpt-4o-mini')) ?>" maxlength="120" required>
            </div>
            <div class="col-md-3">
                <label class="form-label">URL base OpenAI</label>
                <input type="url" class="form-control" name="ai_openai_base_url" value="<?= e((string) ($aiConfig['base_url'] ?? 'https://api.openai.com/v1')) ?>" maxlength="255" required>
            </div>
            <div class="col-md-3">
                <label class="form-label">Temperatura</label>
                <input type="number" step="0.1" min="0" max="1.2" class="form-control" name="ai_temperature" value="<?= e((string) ($aiConfig['temperature'] ?? '0.2')) ?>" required>
            </div>
            <div class="col-md-3">
                <label class="form-label">Max output tokens</label>
                <input type="number" min="120" max="1800" class="form-control" name="ai_max_output_tokens" value="<?= e((string) ($aiConfig['max_output_tokens'] ?? 700)) ?>" required>
            </div>
            <div class="col-md-6">
                <label class="form-label">OpenAI API Key</label>
                <input type="password" class="form-control" name="ai_openai_api_key" autocomplete="off" placeholder="Deja en blanco para conservar la actual" maxlength="500">
            </div>
            <div class="col-12">
                <label class="form-label">System prompt</label>
                <textarea class="form-control" name="ai_system_prompt" rows="4" maxlength="6000" placeholder="Instrucciones internas para el agente IA"><?= e((string) ($aiConfig['system_prompt'] ?? '')) ?></textarea>
                <small class="text-muted">Si no cambias la API key, se conserva la actual. Puedes ajustar este prompt para alinear tono y alcance de respuestas.</small>
            </div>
            <div class="col-md-8">
                <label class="form-label">Pregunta de prueba</label>
                <input type="text" class="form-control" name="ai_test_prompt" value="¿Cómo registrar una venta POS y cerrar caja correctamente?" maxlength="300">
            </div>
            <div class="col-12 d-flex flex-wrap gap-2">
                <button class="btn btn-primary" type="submit">Guardar configuración IA</button>
                <button class="btn btn-outline-primary" type="submit" formaction="<?= e(url('superadmin/ia-config/probar')) ?>" formmethod="post">
                    Probar asistente IA
                </button>
            </div>
        </form>

        <form action="<?= e(url('superadmin/ia-config/limpiar')) ?>" method="post" class="d-flex flex-wrap gap-2 align-items-center">
            <?= csrf_field() ?>
            <input type="hidden" name="key" value="api_key">
            <button class="btn btn-sm btn-outline-danger" type="submit" onclick="return confirm('¿Eliminar la API key guardada del agente IA?');">
                Limpiar API key
            </button>
            <small class="text-muted">Úsalo solo si quieres forzar reconfiguración de acceso al proveedor.</small>
        </form>
    </div>
</div>
</div>

<div class="sa-section <?= $superadminSection === 'reporte_openia' ? 'is-active' : '' ?>" data-sa-section="reporte_openia">
<?php
$openAiDailyBudgetUsd = (float) ($openAiReportSettings['daily_budget_usd'] ?? 0);
$openAiMonthlyBudgetUsd = (float) ($openAiReportSettings['monthly_budget_usd'] ?? 0);
$openAiCompanyDailyQuestionLimit = (int) ($openAiReportSettings['company_daily_question_limit'] ?? 0);
$openAiContextHistoryLimit = (int) ($openAiReportSettings['context_history_limit'] ?? 12);
$openAiInputCostPer1M = (float) ($openAiReportSettings['input_cost_per_1m_usd'] ?? 0.15);
$openAiOutputCostPer1M = (float) ($openAiReportSettings['output_cost_per_1m_usd'] ?? 0.60);

$openAiDayCostUsd = (float) ($openAiReportUsage['day_cost_usd'] ?? 0);
$openAiMonthCostUsd = (float) ($openAiReportUsage['month_cost_usd'] ?? 0);
$openAiDayQuestions = (int) ($openAiReportUsage['day_questions'] ?? 0);
$openAiMonthQuestions = (int) ($openAiReportUsage['month_questions'] ?? 0);
$openAiDayPromptTokens = (int) ($openAiReportUsage['day_prompt_tokens'] ?? 0);
$openAiDayCompletionTokens = (int) ($openAiReportUsage['day_completion_tokens'] ?? 0);
$openAiDayTotalTokens = (int) ($openAiReportUsage['day_total_tokens'] ?? 0);
$openAiMonthPromptTokens = (int) ($openAiReportUsage['month_prompt_tokens'] ?? 0);
$openAiMonthCompletionTokens = (int) ($openAiReportUsage['month_completion_tokens'] ?? 0);
$openAiMonthTotalTokens = (int) ($openAiReportUsage['month_total_tokens'] ?? 0);

$openAiDailyReached = (bool) ($openAiReport['daily_limit_reached'] ?? false);
$openAiMonthlyReached = (bool) ($openAiReport['monthly_limit_reached'] ?? false);
?>
<div class="card border-0 shadow-sm mb-4">
    <div class="card-body">
        <div class="d-flex flex-wrap align-items-start justify-content-between gap-2 mb-3">
            <div>
                <h2 class="h5 mb-1">Reporte OpenIA</h2>
                <p class="text-muted mb-0">Control de gasto, límites de preguntas por empresa y recorte automático de historial.</p>
            </div>
            <span class="badge text-bg-light border">Estimado por tokens registrados</span>
        </div>

        <div class="row g-3 mb-3">
            <div class="col-md-3">
                <div class="p-3 rounded border bg-light h-100">
                    <small class="text-muted d-block">Gasto estimado hoy</small>
                    <strong>USD <?= e(number_format($openAiDayCostUsd, 4, '.', ',')) ?></strong>
                    <div class="small text-muted">Preguntas hoy: <?= e((string) $openAiDayQuestions) ?></div>
                    <div class="mt-2">
                        <span class="badge <?= $openAiDailyReached ? 'text-bg-danger' : 'text-bg-success' ?>">
                            <?= $openAiDailyReached ? 'Tope diario alcanzado' : 'Dentro del tope diario' ?>
                        </span>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="p-3 rounded border bg-light h-100">
                    <small class="text-muted d-block">Gasto estimado mes</small>
                    <strong>USD <?= e(number_format($openAiMonthCostUsd, 4, '.', ',')) ?></strong>
                    <div class="small text-muted">Preguntas mes: <?= e((string) $openAiMonthQuestions) ?></div>
                    <div class="mt-2">
                        <span class="badge <?= $openAiMonthlyReached ? 'text-bg-danger' : 'text-bg-success' ?>">
                            <?= $openAiMonthlyReached ? 'Tope mensual alcanzado' : 'Dentro del tope mensual' ?>
                        </span>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="p-3 rounded border bg-light h-100">
                    <small class="text-muted d-block">Límite preguntas/empresa (día)</small>
                    <strong><?= $openAiCompanyDailyQuestionLimit > 0 ? e((string) $openAiCompanyDailyQuestionLimit) : 'Sin límite' ?></strong>
                    <div class="small text-muted">0 = ilimitado</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="p-3 rounded border bg-light h-100">
                    <small class="text-muted d-block">Recorte de historial</small>
                    <strong><?= e((string) $openAiContextHistoryLimit) ?> mensajes</strong>
                    <div class="small text-muted">Contexto enviado por pregunta</div>
                </div>
            </div>
        </div>

        <div class="row g-3 mb-3">
            <div class="col-md-6">
                <div class="p-3 rounded border bg-light h-100">
                    <small class="text-muted d-block">Tokens hoy</small>
                    <div class="small">Entrada: <strong><?= e(number_format($openAiDayPromptTokens, 0, '.', ',')) ?></strong></div>
                    <div class="small">Salida: <strong><?= e(number_format($openAiDayCompletionTokens, 0, '.', ',')) ?></strong></div>
                    <div class="small">Total: <strong><?= e(number_format($openAiDayTotalTokens, 0, '.', ',')) ?></strong></div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="p-3 rounded border bg-light h-100">
                    <small class="text-muted d-block">Tokens mes</small>
                    <div class="small">Entrada: <strong><?= e(number_format($openAiMonthPromptTokens, 0, '.', ',')) ?></strong></div>
                    <div class="small">Salida: <strong><?= e(number_format($openAiMonthCompletionTokens, 0, '.', ',')) ?></strong></div>
                    <div class="small">Total: <strong><?= e(number_format($openAiMonthTotalTokens, 0, '.', ',')) ?></strong></div>
                </div>
            </div>
        </div>

        <form action="<?= e(url('superadmin/reporte-openia-config')) ?>" method="post" class="row g-2 mb-3">
            <?= csrf_field() ?>
            <div class="col-md-3">
                <label class="form-label">Tope gasto diario (USD)</label>
                <div class="input-group">
                    <span class="input-group-text">$</span>
                    <input type="number" step="0.01" min="0" class="form-control" name="openai_budget_daily_usd" value="<?= e(number_format($openAiDailyBudgetUsd, 2, '.', '')) ?>" required>
                    <span class="input-group-text">USD</span>
                </div>
            </div>
            <div class="col-md-3">
                <label class="form-label">Tope gasto mensual (USD)</label>
                <div class="input-group">
                    <span class="input-group-text">$</span>
                    <input type="number" step="0.01" min="0" class="form-control" name="openai_budget_monthly_usd" value="<?= e(number_format($openAiMonthlyBudgetUsd, 2, '.', '')) ?>" required>
                    <span class="input-group-text">USD</span>
                </div>
            </div>
            <div class="col-md-3">
                <label class="form-label">Límite preguntas/empresa/día</label>
                <input type="number" min="0" class="form-control" name="openai_company_daily_question_limit" value="<?= e((string) $openAiCompanyDailyQuestionLimit) ?>" required>
            </div>
            <div class="col-md-3">
                <label class="form-label">Recorte historial (mensajes)</label>
                <input type="number" min="4" max="30" class="form-control" name="openai_context_history_limit" value="<?= e((string) $openAiContextHistoryLimit) ?>" required>
            </div>
            <div class="col-12 d-flex flex-wrap gap-2 align-items-center">
                <button class="btn btn-primary" type="submit">Guardar política OpenIA</button>
                <small class="text-muted">Formato USD: usa valores como 0.46 o 14.00 (máximo 2 decimales).</small>
                <small class="text-muted">Costo estimado con tarifa de referencia: input USD <?= e(number_format($openAiInputCostPer1M, 2, '.', ',')) ?>/1M y output USD <?= e(number_format($openAiOutputCostPer1M, 2, '.', ',')) ?>/1M tokens.</small>
            </div>
        </form>

        <div class="table-responsive">
            <table class="table table-striped table-hover align-middle">
                <thead>
                <tr>
                    <th>Empresa</th>
                    <th>Preguntas hoy</th>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($openAiTopCompaniesToday as $row): ?>
                    <tr>
                        <td><?= e((string) ($row['empresa'] ?? 'Empresa')) ?></td>
                        <td><?= e((string) ((int) ($row['preguntas_hoy'] ?? 0))) ?></td>
                    </tr>
                <?php endforeach; ?>
                <?php if ($openAiTopCompaniesToday === []): ?>
                    <tr><td colspan="2" class="text-center text-muted py-3">No hay preguntas registradas hoy.</td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
</div>

<div class="sa-section <?= $superadminSection === 'checkout' ? 'is-active' : '' ?>" data-sa-section="checkout">
<div class="card border-0 shadow-sm mb-4">
    <div class="card-body">
        <h2 class="h5 mb-3">Operación de pagos SaaS (checkout no provisionado)</h2>
        <div class="table-responsive">
            <table class="table table-striped table-hover align-middle">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>Referencia</th>
                    <th>Empresa</th>
                    <th>Plan</th>
                    <th>Monto</th>
                    <th>Estado</th>
                    <th>Último error</th>
                    <th>Acción</th>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($checkoutIntents as $intent): ?>
                    <?php
                    $status = strtolower((string) ($intent['estado'] ?? 'pending'));
                    $statusClass = in_array($status, ['approved'], true)
                        ? 'text-bg-success'
                        : (in_array($status, ['failed', 'error', 'declined', 'voided'], true) ? 'text-bg-danger' : 'text-bg-warning');
                    $amount = ((int) ($intent['amount_in_cents'] ?? 0)) / 100;
                    ?>
                    <tr>
                        <td>#<?= e((string) ($intent['id'] ?? '')) ?></td>
                        <td>
                            <code><?= e((string) ($intent['reference'] ?? '')) ?></code><br>
                            <small class="text-muted"><?= e((string) ($intent['wompi_transaction_id'] ?? 'sin tx')) ?></small>
                        </td>
                        <td>
                            <strong><?= e((string) ($intent['empresa_nombre'] ?? '')) ?></strong><br>
                            <small class="text-muted">/<?= e((string) ($intent['empresa_slug'] ?? '')) ?></small>
                        </td>
                        <td><?= e((string) ($intent['plan_nombre'] ?? '')) ?></td>
                        <td><?= e(money($amount)) ?> <?= e((string) ($intent['currency'] ?? 'COP')) ?></td>
                        <td>
                            <span class="badge <?= e($statusClass) ?>"><?= e($status) ?></span><br>
                            <small class="text-muted"><?= e((string) ($intent['wompi_status'] ?? '')) ?></small>
                        </td>
                        <td>
                            <small class="text-muted"><?= e((string) ($intent['failure_reason'] ?? '-')) ?></small>
                        </td>
                        <td>
                            <form action="<?= e(url('superadmin/checkout-intents/' . (int) ($intent['id'] ?? 0) . '/reprocesar')) ?>" method="post">
                                <?= csrf_field() ?>
                                <button class="btn btn-sm btn-outline-primary" type="submit">Reprocesar webhook</button>
                            </form>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <?php if ($checkoutIntents === []): ?>
                    <tr><td colspan="8" class="text-center text-muted py-3">No hay checkouts pendientes/fallidos para reproceso.</td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
</div>

<div class="sa-section <?= $superadminSection === 'cobranza' ? 'is-active' : '' ?>" data-sa-section="cobranza">
<div class="card border-0 shadow-sm mb-4">
    <div class="card-body">
        <h2 class="h5 mb-3">Cobranza automática (email/WhatsApp + reintentos)</h2>
        <p class="text-muted mb-3">
            Esta bandeja muestra avisos pendientes y fallidos. El botón “Reintentar avisos” re-procesa los envíos según los intentos máximos y backoff configurado.
        </p>
        <div class="table-responsive">
            <table class="table table-striped table-hover align-middle">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>Empresa</th>
                    <th>Tipo</th>
                    <th>Canal</th>
                    <th>Destino</th>
                    <th>Estado</th>
                    <th>Intentos</th>
                    <th>Próximo intento</th>
                    <th>Error</th>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($collectionNoticeQueue as $notice): ?>
                    <?php
                    $noticeStatus = strtolower((string) ($notice['estado'] ?? 'pendiente'));
                    $noticeStatusClass = $noticeStatus === 'enviado'
                        ? 'text-bg-success'
                        : ($noticeStatus === 'error' ? 'text-bg-danger' : 'text-bg-warning');
                    ?>
                    <tr>
                        <td>#<?= e((string) ($notice['id'] ?? '')) ?></td>
                        <td><?= e((string) ($notice['empresa'] ?? '')) ?></td>
                        <td><?= e((string) ($notice['tipo'] ?? '')) ?></td>
                        <td><?= e((string) ($notice['canal'] ?? '')) ?></td>
                        <td><small><?= e((string) ($notice['destinatario'] ?? '-')) ?></small></td>
                        <td><span class="badge <?= e($noticeStatusClass) ?>"><?= e($noticeStatus) ?></span></td>
                        <td><?= e((string) ($notice['intentos'] ?? 0)) ?>/<?= e((string) ($notice['max_intentos'] ?? 0)) ?></td>
                        <td><?= e((string) ($notice['proximo_intento_at'] ?? '-')) ?></td>
                        <td><small class="text-muted"><?= e((string) ($notice['error_detalle'] ?? '-')) ?></small></td>
                    </tr>
                <?php endforeach; ?>
                <?php if ($collectionNoticeQueue === []): ?>
                    <tr><td colspan="9" class="text-center text-muted py-3">No hay avisos de cobro registrados aún.</td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
</div>

<div class="sa-section <?= $superadminSection === 'planes' ? 'is-active' : '' ?>" data-sa-section="planes">
<div class="card border-0 shadow-sm mb-4">
    <div class="card-body">
        <div class="d-flex align-items-center justify-content-between mb-4">
            <div>
                <h1 class="h5 mb-1">Planes SaaS</h1>
                <p class="text-muted mb-0" style="font-size:.82rem"><?= count($plans) ?> planes configurados</p>
            </div>
            <a href="<?= e(route('superadmin.planes.create', [], false)) ?>" class="btn btn-primary btn-sm d-flex align-items-center gap-2">
                <i class="bx bx-plus"></i> Nuevo plan
            </a>
        </div>

        <?php
        $allPlanModulos = [];
        $allPlanPromos  = [];
        if (!empty($plans)) {
            $_planIds = array_column($plans, 'id');
            $_modRows = \Illuminate\Support\Facades\DB::table('plan_modulos')->whereIn('plan_id', $_planIds)->get();
            foreach ($_modRows as $_r) { $allPlanModulos[$_r->plan_id][] = $_r->modulo; }
            $_promoRows = \Illuminate\Support\Facades\DB::table('plan_promociones')
                ->whereIn('plan_id', $_planIds)->where('activo', 1)->orderBy('meses')->get();
            foreach ($_promoRows as $_r) { $allPlanPromos[$_r->plan_id][] = $_r; }
        }
        $_mods = config('modulos') ?: [];
        ?>

        <div class="row g-3 align-items-start">
        <?php foreach ($plans as $_plan): ?>
        <?php
        $_id       = (int) $_plan['id'];
        $_modulos  = $allPlanModulos[$_id] ?? [];
        $_promos   = $allPlanPromos[$_id] ?? [];
        $_precio   = (float) ($_plan['precio_mensual'] ?? 0);
        $_featured = ($_plan['slug'] ?? '') === 'profesional';
        ?>
        <div class="col-md-6 col-xl-4">
            <div class="card h-100 <?= $_featured ? 'border-primary' : 'border-light' ?>"
                 style="border-radius:14px;<?= $_featured ? 'box-shadow:0 0 0 2px rgba(79,70,229,.2)' : '' ?>">
                <?php if ($_featured): ?>
                <div class="text-center py-1" style="background:linear-gradient(90deg,#4f46e5,#8b5cf6);border-radius:14px 14px 0 0">
                    <small class="text-white fw-bold" style="font-size:.65rem;letter-spacing:.06em;text-transform:uppercase">Más popular</small>
                </div>
                <?php endif; ?>

                <div class="card-body p-4">
                    <div class="d-flex justify-content-between align-items-start mb-1">
                        <div class="fw-semibold" style="font-size:.72rem;letter-spacing:.08em;color:#64748b;text-transform:uppercase">
                            <?= e((string) ($_plan['nombre'] ?? '')) ?>
                        </div>
                        <span class="badge <?= (int)($_plan['activo']??0) ? 'text-bg-success' : 'text-bg-secondary' ?>" style="font-size:.65rem">
                            <?= (int)($_plan['activo']??0) ? 'Activo' : 'Inactivo' ?>
                        </span>
                    </div>

                    <div class="mb-2">
                        <?php if ($_precio == 0): ?>
                            <span style="font-size:1.9rem;font-weight:800;color:#0f172a">Gratis</span>
                        <?php else: ?>
                            <span style="font-size:1.9rem;font-weight:800;color:#4f46e5">$<?= number_format($_precio, 0, ',', '.') ?></span>
                            <span class="text-muted" style="font-size:.82rem">/mes</span>
                        <?php endif; ?>
                    </div>

                    <?php if (!empty($_promos)): ?>
                    <div class="d-flex flex-wrap gap-1 mb-3">
                        <?php foreach ($_promos as $_p): ?>
                        <span style="background:#fef3c7;color:#92400e;border-radius:6px;padding:2px 9px;font-size:.68rem;font-weight:700">
                            <?= (int)$_p->meses ?>m &minus;<?= number_format((float)$_p->descuento_porcentaje, 0) ?>%
                        </span>
                        <?php endforeach; ?>
                    </div>
                    <?php endif; ?>

                    <div class="d-flex gap-1 flex-wrap mb-3">
                        <span class="badge text-bg-light" style="font-size:.7rem;padding:4px 8px">
                            <i class="bx bxs-user me-1"></i><?= (int)($_plan['max_usuarios']??1) ?> usuarios
                        </span>
                        <span class="badge text-bg-light" style="font-size:.7rem;padding:4px 8px">
                            <i class="bx bxs-building me-1"></i><?= (int)($_plan['max_sucursales']??1) ?> suc.
                        </span>
                        <span class="badge text-bg-light" style="font-size:.7rem;padding:4px 8px">
                            <i class="bx bxs-box me-1"></i><?= number_format((int)($_plan['max_productos']??0)) ?> prod.
                        </span>
                    </div>

                    <hr class="my-2">

                    <div style="max-height:260px;overflow-y:auto;padding-right:4px">
                    <?php foreach ($_mods as $_key => $_meta): ?>
                    <?php $_has = in_array($_key, $_modulos, true); ?>
                    <div class="d-flex align-items-center gap-2" style="padding:5px 0;border-bottom:1px solid #f1f5f9">
                        <?php if ($_has): ?>
                            <i class="bx bxs-check-circle flex-shrink-0" style="color:#10b981;font-size:1rem"></i>
                        <?php else: ?>
                            <i class="bx bx-x-circle flex-shrink-0" style="color:#cbd5e1;font-size:1rem"></i>
                        <?php endif; ?>
                        <span style="font-size:.78rem;color:<?= $_has ? '#1e293b' : '#94a3b8' ?>">
                            <?= e($_meta['label']) ?>
                        </span>
                    </div>
                    <?php endforeach; ?>
                    </div>

                    <div class="d-flex align-items-center justify-content-between mt-3 pt-2">
                        <small class="text-muted"><?= (int)($_plan['empresas_en_plan']??0) ?> empresa<?= (int)($_plan['empresas_en_plan']??0) !== 1 ? 's' : '' ?></small>
                        <a href="<?= e(route('superadmin.planes.edit', ['plan' => $_id], false)) ?>" class="btn btn-outline-primary btn-sm">
                            <i class="bx bx-edit-alt me-1"></i>Editar
                        </a>
                    </div>
                </div>
            </div>
        </div>
        <?php endforeach; ?>

        <?php if ($plans === []): ?>
        <div class="col-12 text-center py-5 text-muted">
            <i class="bx bx-layer" style="font-size:2.5rem;display:block;margin-bottom:12px"></i>
            No hay planes creados aún.
            <div class="mt-3">
                <a href="<?= e(route('superadmin.planes.create', [], false)) ?>" class="btn btn-primary btn-sm">Crear primer plan</a>
            </div>
        </div>
        <?php endif; ?>
        </div>
    </div>
</div>
</div>

<div class="sa-section <?= $superadminSection === 'empresas' ? 'is-active' : '' ?>" data-sa-section="empresas">
<div class="card border-0 shadow-sm mb-4">
    <div class="card-body">
        <h2 class="h5 mb-3">Empresas (activar / suspender / bloquear)</h2>
        <div class="table-responsive sa-company-table-wrap">
            <table class="table align-middle sa-company-table">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>Empresa</th>
                    <th>Plan actual</th>
                    <th>Suscripción</th>
                    <th>Vencimiento</th>
                    <th>Estado empresa</th>
                    <th>Acción</th>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($companies as $company): ?>
                    <?php
                    $companyStatus = (string) ($company['estado'] ?? 'activa');
                    $companyStatusClass = $companyStatus === 'activa'
                        ? 'text-bg-success'
                        : ($companyStatus === 'suspendida' ? 'text-bg-warning' : 'text-bg-danger');
                    $subStatus = (string) ($company['suscripcion_estado'] ?? 'sin_suscripcion');
                    $subStatusClass = $subStatus === 'activa'
                        ? 'text-bg-success'
                        : ($subStatus === 'vencida' ? 'text-bg-warning' : ($subStatus === 'morosa' ? 'text-bg-danger' : 'text-bg-secondary'));
                    $planAllowsFe = (int) ($company['plan_allows_fe'] ?? 0) === 1;
                    $factusFlags = is_array($company['factus_configured_flags'] ?? null)
                        ? $company['factus_configured_flags']
                        : [];
                    $factusApiConfigured = !empty($factusFlags['api_url']) ? '1' : '0';
                    $factusClientIdConfigured = !empty($factusFlags['client_id']) ? '1' : '0';
                    $factusClientSecretConfigured = !empty($factusFlags['client_secret']) ? '1' : '0';
                    $factusUsernameConfigured = !empty($factusFlags['username']) ? '1' : '0';
                    $factusPasswordConfigured = !empty($factusFlags['password']) ? '1' : '0';
                    $factusSoftwareIdConfigured = !empty($factusFlags['software_id']) ? '1' : '0';
                    $factusSoftwarePinConfigured = !empty($factusFlags['software_pin']) ? '1' : '0';
                    $factusRangeConfigured = !empty($factusFlags['numbering_range_id']) ? '1' : '0';
                    $factusMunicipalityConfigured = !empty($factusFlags['municipality_id']) ? '1' : '0';
                    ?>
                    <tr class="sa-company-row">
                        <td>
                            <span class="sa-company-id-pill">#<?= e((string) $company['id']) ?></span>
                        </td>
                        <td>
                            <div class="sa-company-main">
                                <strong class="sa-company-name"><?= e((string) ($company['nombre'] ?? '')) ?></strong>
                                <small class="sa-company-email"><?= e((string) ($company['email'] ?? '')) ?></small>
                            </div>
                        </td>
                        <td>
                            <div class="sa-company-plan">
                                <span class="sa-company-plan-label">Plan</span>
                                <strong class="sa-company-plan-name"><?= e((string) ($company['plan_nombre'] ?? 'Sin plan')) ?></strong>
                            </div>
                        </td>
                        <td>
                            <span class="badge <?= e($subStatusClass) ?> sa-company-badge"><?= e($subStatus) ?></span>
                        </td>
                        <td>
                            <span class="sa-company-date"><?= e((string) ($company['suscripcion_vencimiento'] ?? '-')) ?></span>
                        </td>
                        <td>
                            <span class="badge <?= e($companyStatusClass) ?> sa-company-badge"><?= e($companyStatus) ?></span>
                        </td>
                        <td>
                            <div class="sa-company-actions">
                                <button
                                    type="button"
                                    class="btn btn-sm btn-outline-primary sa-company-btn sa-company-btn-edit js-sa-company-edit-open"
                                    data-bs-toggle="modal"
                                    data-bs-target="#saCompanyEditModal"
                                    data-company-id="<?= e((string) ($company['id'] ?? '0')) ?>"
                                    data-company-name="<?= e((string) ($company['nombre'] ?? '')) ?>"
                                    data-company-email="<?= e((string) ($company['email'] ?? '')) ?>"
                                    data-company-plan="<?= e((string) ($company['plan_nombre'] ?? 'Sin plan')) ?>"
                                    data-company-subscription-status="<?= e($subStatus) ?>"
                                    data-company-vencimiento="<?= e((string) ($company['suscripcion_vencimiento'] ?? '-')) ?>"
                                    data-company-created-at="<?= e((string) ($company['created_at'] ?? '-')) ?>"
                                    data-company-status="<?= e($companyStatus) ?>"
                                    data-vx-tooltip="Editar empresa"
                                >
                                    <i class="bx bx-pencil me-1"></i>
                                    Editar
                                </button>
                                <button
                                    type="button"
                                    class="btn btn-sm btn-outline-secondary sa-company-btn sa-company-btn-factus js-sa-factus-open"
                                    data-bs-toggle="modal"
                                    data-bs-target="#saCompanyFactusModal"
                                    data-company-id="<?= e((string) ($company['id'] ?? '0')) ?>"
                                    data-company-name="<?= e((string) ($company['nombre'] ?? '')) ?>"
                                    data-company-email="<?= e((string) ($company['email'] ?? '')) ?>"
                                    data-company-plan="<?= e((string) ($company['plan_nombre'] ?? 'Sin plan')) ?>"
                                    data-company-plan-fe="<?= $planAllowsFe ? '1' : '0' ?>"
                                    data-company-fe-active="<?= (int) ($company['fe_module_active'] ?? 0) === 1 ? '1' : '0' ?>"
                                    data-company-factus-ready="<?= (int) ($company['factus_ready'] ?? 0) === 1 ? '1' : '0' ?>"
                                    data-company-api-url="<?= e((string) ($company['factus_api_url'] ?? '')) ?>"
                                    data-company-range-id="<?= e((string) ($company['factus_numbering_range_id'] ?? '')) ?>"
                                    data-company-municipality-id="<?= e((string) ($company['factus_municipality_id'] ?? '')) ?>"
                                    data-flag-api-url="<?= e($factusApiConfigured) ?>"
                                    data-flag-client-id="<?= e($factusClientIdConfigured) ?>"
                                    data-flag-client-secret="<?= e($factusClientSecretConfigured) ?>"
                                    data-flag-username="<?= e($factusUsernameConfigured) ?>"
                                    data-flag-password="<?= e($factusPasswordConfigured) ?>"
                                    data-flag-software-id="<?= e($factusSoftwareIdConfigured) ?>"
                                    data-flag-software-pin="<?= e($factusSoftwarePinConfigured) ?>"
                                    data-flag-numbering-range-id="<?= e($factusRangeConfigured) ?>"
                                    data-flag-municipality-id="<?= e($factusMunicipalityConfigured) ?>"
                                    data-vx-tooltip="<?= e($planAllowsFe ? 'Configurar Factus por empresa' : 'El plan de esta empresa no incluye facturación electrónica') ?>"
                                    <?= $planAllowsFe ? '' : 'disabled' ?>
                                >
                                    <i class="bx bx-link-alt me-1"></i>
                                    Factus
                                </button>
                                <form
                                    action="<?= e(route('superadmin.empresas.destroy', ['empresa' => (int) $company['id']])) ?>"
                                    method="post"
                                    class="sa-company-delete-form"
                                    onsubmit="return confirm('¿Eliminar la empresa <?= e((string) ($company['nombre'] ?? '')) ?> y toda su información? Esta acción no se puede deshacer.');"
                                >
                                    <?= csrf_field() ?>
                                    <button class="btn btn-sm btn-outline-danger sa-company-btn sa-company-btn-delete" type="submit" data-vx-tooltip="Eliminar empresa" aria-label="Eliminar empresa">
                                        <i class="bx bx-trash"></i>
                                    </button>
                                </form>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <?php if ($companies === []): ?>
                    <tr><td colspan="7" class="text-center text-muted py-4">No hay empresas registradas.</td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
</div>

<div class="sa-section <?= $superadminSection === 'suscripciones' ? 'is-active' : '' ?>" data-sa-section="suscripciones">
<div class="card border-0 shadow-sm mb-4">
    <div class="card-body">
        <h2 class="h5 mb-3">Suscripciones (estado y vigencia)</h2>
        <div class="table-responsive">
            <table class="table table-striped table-hover align-middle sa-sub-table">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>Empresa</th>
                    <th>Plan</th>
                    <th>Inicio</th>
                    <th>Vence</th>
                    <th>Estado</th>
                    <th>Auto-renovación</th>
                    <th>Acción</th>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($subscriptions as $subscription): ?>
                    <?php
                    $subscriptionStatus = strtolower((string) ($subscription['estado'] ?? 'activa'));
                    $subscriptionStatusClass = match ($subscriptionStatus) {
                        'activa' => 'text-bg-success',
                        'vencida' => 'text-bg-warning',
                        'morosa' => 'text-bg-danger',
                        'cancelada' => 'text-bg-secondary',
                        default => 'text-bg-secondary',
                    };
                    $isAutoRenew = (int) ($subscription['auto_renovacion'] ?? 0) === 1;
                    ?>
                    <tr>
                        <td>
                            <span class="sa-sub-id">#<?= e((string) $subscription['id']) ?></span>
                        </td>
                        <td>
                            <strong class="sa-sub-company"><?= e((string) ($subscription['empresa'] ?? '')) ?></strong>
                        </td>
                        <td>
                            <span class="sa-sub-plan"><?= e((string) ($subscription['plan'] ?? 'Sin plan')) ?></span>
                        </td>
                        <td>
                            <span class="sa-sub-date"><?= e((string) ($subscription['fecha_inicio'] ?? '')) ?></span>
                        </td>
                        <td>
                            <span class="sa-sub-date"><?= e((string) ($subscription['fecha_vencimiento'] ?? '')) ?></span>
                        </td>
                        <td>
                            <span class="badge <?= e($subscriptionStatusClass) ?>"><?= e($subscriptionStatus) ?></span>
                        </td>
                        <td>
                            <span class="sa-sub-auto <?= $isAutoRenew ? 'is-on' : 'is-off' ?>">
                                <i class="bx <?= $isAutoRenew ? 'bx-refresh' : 'bx-pause-circle' ?>"></i>
                                <?= $isAutoRenew ? 'Sí' : 'No' ?>
                            </span>
                        </td>
                        <td>
                            <div class="sa-sub-actions">
                                <button class="btn btn-sm btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#editSub<?= e((string) $subscription['id']) ?>">
                                    Editar
                                </button>
                            </div>
                        </td>
                    </tr>
                    <tr class="sa-sub-edit-row">
                        <td colspan="8" class="p-0 border-0">
                            <div class="collapse" id="editSub<?= e((string) $subscription['id']) ?>">
                                <div class="sa-sub-edit-panel">
                                    <form action="<?= e(url('superadmin/suscripciones/' . (int) $subscription['id'] . '/actualizar')) ?>" method="post" class="row g-2 p-3">
                                        <?= csrf_field() ?>
                                        <div class="col-md-3">
                                            <label class="form-label">Plan</label>
                                            <select class="form-select" name="plan_id" required>
                                                <?php foreach ($plans as $plan): ?>
                                                    <option value="<?= e((string) $plan['id']) ?>" <?= (int) ($subscription['plan_id'] ?? 0) === (int) $plan['id'] ? 'selected' : '' ?>>
                                                        <?= e((string) $plan['nombre']) ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">Inicio</label>
                                            <input type="date" class="form-control" name="fecha_inicio" value="<?= e((string) ($subscription['fecha_inicio'] ?? '')) ?>" required>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">Vence</label>
                                            <input type="date" class="form-control" name="fecha_vencimiento" value="<?= e((string) ($subscription['fecha_vencimiento'] ?? '')) ?>" required>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">Estado</label>
                                            <select class="form-select" name="estado" required>
                                                <?php $subStatus = (string) ($subscription['estado'] ?? 'activa'); ?>
                                                <option value="activa" <?= $subStatus === 'activa' ? 'selected' : '' ?>>Activa</option>
                                                <option value="vencida" <?= $subStatus === 'vencida' ? 'selected' : '' ?>>Vencida</option>
                                                <option value="morosa" <?= $subStatus === 'morosa' ? 'selected' : '' ?>>Morosa</option>
                                                <option value="cancelada" <?= $subStatus === 'cancelada' ? 'selected' : '' ?>>Cancelada</option>
                                            </select>
                                        </div>
                                        <div class="col-md-1">
                                            <label class="form-label d-block">Trial</label>
                                            <input type="hidden" name="trial" value="0">
                                            <div class="form-check mt-2">
                                                <input class="form-check-input" type="checkbox" name="trial" value="1" <?= (int) ($subscription['trial'] ?? 0) === 1 ? 'checked' : '' ?>>
                                            </div>
                                        </div>
                                        <div class="col-md-1">
                                            <label class="form-label d-block">Auto</label>
                                            <input type="hidden" name="auto_renovacion" value="0">
                                            <div class="form-check mt-2">
                                                <input class="form-check-input" type="checkbox" name="auto_renovacion" value="1" <?= (int) ($subscription['auto_renovacion'] ?? 0) === 1 ? 'checked' : '' ?>>
                                            </div>
                                        </div>
                                        <div class="col-md-1 d-flex align-items-end">
                                            <button class="btn btn-sm btn-primary w-100" type="submit">Guardar</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <?php if ($subscriptions === []): ?>
                    <tr><td colspan="8" class="text-center text-muted py-3">No hay suscripciones registradas.</td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
</div>

<div class="sa-section <?= $superadminSection === 'sla' ? 'is-active' : '' ?>" data-sa-section="sla">
<div class="card border-0 shadow-sm mb-4">
    <div class="card-body">
        <h2 class="h5 mb-3">SLA de soporte (respuesta y resolución)</h2>

        <form method="get" action="<?= e(url('superadmin')) ?>" class="row g-2 mb-3">
            <input type="hidden" name="seccion" value="sla">
            <div class="col-md-3">
                <label class="form-label">Desde</label>
                <input type="date" class="form-control" name="soporte_desde" value="<?= e((string) ($supportReportFilter['desde'] ?? date('Y-m-01'))) ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label">Hasta</label>
                <input type="date" class="form-control" name="soporte_hasta" value="<?= e((string) ($supportReportFilter['hasta'] ?? date('Y-m-d'))) ?>">
            </div>
            <div class="col-md-2 d-flex align-items-end">
                <button class="btn btn-outline-primary w-100" type="submit">Filtrar</button>
            </div>
        </form>

        <div class="row g-3 mb-4">
            <div class="col-md-2">
                <div class="border rounded p-3 h-100">
                    <small class="text-muted d-block">Tickets</small>
                    <strong><?= e((string) ($supportSlaSummary['total_tickets'] ?? 0)) ?></strong>
                </div>
            </div>
            <div class="col-md-2">
                <div class="border rounded p-3 h-100">
                    <small class="text-muted d-block">Abiertos</small>
                    <strong><?= e((string) ($supportSlaSummary['abiertos'] ?? 0)) ?></strong>
                </div>
            </div>
            <div class="col-md-2">
                <div class="border rounded p-3 h-100">
                    <small class="text-muted d-block">1ra resp. fuera SLA</small>
                    <strong><?= e((string) ($supportSlaSummary['primera_respuesta_incumplida'] ?? 0)) ?></strong>
                </div>
            </div>
            <div class="col-md-2">
                <div class="border rounded p-3 h-100">
                    <small class="text-muted d-block">Resolución fuera SLA</small>
                    <strong><?= e((string) ($supportSlaSummary['resolucion_incumplida'] ?? 0)) ?></strong>
                </div>
            </div>
            <div class="col-md-2">
                <div class="border rounded p-3 h-100">
                    <small class="text-muted d-block">Prom. 1ra resp (min)</small>
                    <strong><?= e((string) ($supportSlaSummary['promedio_primera_respuesta_min'] ?? 0)) ?></strong>
                </div>
            </div>
            <div class="col-md-2">
                <div class="border rounded p-3 h-100">
                    <small class="text-muted d-block">Prom. resolución (min)</small>
                    <strong><?= e((string) ($supportSlaSummary['promedio_resolucion_min'] ?? 0)) ?></strong>
                </div>
            </div>
        </div>

        <div class="row g-3">
            <div class="col-lg-6">
                <h3 class="h6 mb-2">Reporte por empresa</h3>
                <div class="table-responsive">
                    <table class="table table-sm table-striped align-middle">
                        <thead>
                        <tr>
                            <th>Empresa</th>
                            <th>Total</th>
                            <th>Abiertos</th>
                            <th>1ra SLA</th>
                            <th>Res SLA</th>
                            <th>Prom res (h)</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($supportSlaByCompany as $row): ?>
                            <tr>
                                <td><?= e((string) ($row['empresa'] ?? '')) ?></td>
                                <td><?= e((string) ($row['total_tickets'] ?? 0)) ?></td>
                                <td><?= e((string) ($row['abiertos'] ?? 0)) ?></td>
                                <td><?= e((string) ($row['primera_respuesta_incumplida'] ?? 0)) ?></td>
                                <td><?= e((string) ($row['resolucion_incumplida'] ?? 0)) ?></td>
                                <td><?= e((string) ($row['promedio_resolucion_horas'] ?? 0)) ?></td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if ($supportSlaByCompany === []): ?>
                            <tr><td colspan="6" class="text-center text-muted py-2">Sin datos en el rango.</td></tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="col-lg-6">
                <h3 class="h6 mb-2">Reporte por agente</h3>
                <div class="table-responsive">
                    <table class="table table-sm table-striped align-middle">
                        <thead>
                        <tr>
                            <th>Agente</th>
                            <th>Asignados</th>
                            <th>Resueltos</th>
                            <th>Res SLA</th>
                            <th>1ra resp (min)</th>
                            <th>Prom res (h)</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($supportSlaByAgent as $row): ?>
                            <tr>
                                <td><?= e((string) ($row['agente'] ?? '')) ?></td>
                                <td><?= e((string) ($row['total_asignados'] ?? 0)) ?></td>
                                <td><?= e((string) ($row['resueltos'] ?? 0)) ?></td>
                                <td><?= e((string) ($row['resolucion_incumplida'] ?? 0)) ?></td>
                                <td><?= e((string) ($row['promedio_primera_respuesta_min'] ?? 0)) ?></td>
                                <td><?= e((string) ($row['promedio_resolucion_horas'] ?? 0)) ?></td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if ($supportSlaByAgent === []): ?>
                            <tr><td colspan="6" class="text-center text-muted py-2">Sin datos en el rango.</td></tr>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
</div>

<div class="sa-section <?= $superadminSection === 'soporte' ? 'is-active' : '' ?>" data-sa-section="soporte">
<div class="card border-0 shadow-sm mb-4">
    <div class="card-body">
        <h2 class="h5 mb-3">Soporte Superadmin (tickets por empresa)</h2>

        <form action="<?= e(url('superadmin/soporte/tickets')) ?>" method="post" class="row g-2 mb-4">
            <?= csrf_field() ?>
            <div class="col-md-3">
                <label class="form-label">Empresa</label>
                <select class="form-select" name="empresa_id" required>
                    <option value="">Seleccione...</option>
                    <?php foreach ($companies as $company): ?>
                        <option value="<?= e((string) ($company['id'] ?? '')) ?>">
                            <?= e((string) ($company['nombre'] ?? '')) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-4">
                <label class="form-label">Asunto</label>
                <input class="form-control" name="asunto" maxlength="180" required>
            </div>
            <div class="col-md-2">
                <label class="form-label">Prioridad</label>
                <select class="form-select" name="prioridad">
                    <option value="media">Media</option>
                    <option value="baja">Baja</option>
                    <option value="alta">Alta</option>
                    <option value="critica">Crítica</option>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label">Descripción</label>
                <textarea class="form-control" name="descripcion" rows="1" required></textarea>
            </div>
            <div class="col-12">
                <button class="btn btn-primary" type="submit">Crear ticket</button>
            </div>
        </form>

        <div class="table-responsive">
            <table class="table table-striped table-hover align-middle">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>Empresa</th>
                    <th>Asunto</th>
                    <th>Estado/Prioridad</th>
                    <th>Asignado</th>
                    <th>SLA</th>
                    <th>Actualizado</th>
                    <th>Acción</th>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($supportTickets as $ticket): ?>
                    <?php
                    $ticketId = (int) ($ticket['id'] ?? 0);
                    $ticketStatus = (string) ($ticket['estado'] ?? 'abierto');
                    $ticketPriority = (string) ($ticket['prioridad'] ?? 'media');
                    $ticketStatusClass = $ticketStatus === 'abierto'
                        ? 'text-bg-warning'
                        : ($ticketStatus === 'en_proceso'
                            ? 'text-bg-primary'
                            : (in_array($ticketStatus, ['resuelto', 'cerrado'], true) ? 'text-bg-success' : 'text-bg-secondary'));
                    $ticketPriorityClass = $ticketPriority === 'critica'
                        ? 'text-bg-danger'
                        : ($ticketPriority === 'alta'
                            ? 'text-bg-warning'
                            : ($ticketPriority === 'media' ? 'text-bg-primary' : 'text-bg-secondary'));
                    $slaFirstStatus = (string) ($ticket['sla_primera_respuesta_estado'] ?? 'pendiente');
                    $slaResolutionStatus = (string) ($ticket['sla_resolucion_estado'] ?? 'pendiente');
                    $slaFirstClass = $slaFirstStatus === 'cumplido'
                        ? 'text-bg-success'
                        : ($slaFirstStatus === 'incumplido' ? 'text-bg-danger' : 'text-bg-warning');
                    $slaResolutionClass = $slaResolutionStatus === 'cumplido'
                        ? 'text-bg-success'
                        : ($slaResolutionStatus === 'incumplido' ? 'text-bg-danger' : 'text-bg-warning');
                    $events = is_array($supportEventsByTicket[$ticketId] ?? null) ? $supportEventsByTicket[$ticketId] : [];
                    ?>
                    <tr>
                        <td>#<?= e((string) $ticketId) ?></td>
                        <td><?= e((string) ($ticket['empresa'] ?? '')) ?></td>
                        <td>
                            <strong><?= e((string) ($ticket['asunto'] ?? '')) ?></strong><br>
                            <small class="text-muted"><?= e((string) ($ticket['descripcion'] ?? '')) ?></small>
                        </td>
                        <td>
                            <span class="badge <?= e($ticketStatusClass) ?>"><?= e($ticketStatus) ?></span>
                            <span class="badge <?= e($ticketPriorityClass) ?>"><?= e($ticketPriority) ?></span>
                        </td>
                        <td><?= e((string) (($ticket['asignado_a'] ?? '') !== '' ? $ticket['asignado_a'] : 'Sin asignar')) ?></td>
                        <td>
                            <span class="badge <?= e($slaFirstClass) ?>">1ra: <?= e($slaFirstStatus) ?></span><br>
                            <span class="badge <?= e($slaResolutionClass) ?>">Res: <?= e($slaResolutionStatus) ?></span><br>
                            <small class="text-muted">
                                Límite 1ra: <?= e((string) ($ticket['primera_respuesta_limite_at'] ?? '-')) ?><br>
                                Límite res: <?= e((string) ($ticket['resolucion_limite_at'] ?? '-')) ?>
                            </small>
                        </td>
                        <td><?= e((string) ($ticket['updated_at'] ?? '')) ?></td>
                        <td>
                            <button class="btn btn-sm btn-outline-primary" type="button" data-bs-toggle="collapse" data-bs-target="#supportTicket<?= e((string) $ticketId) ?>">
                                Gestionar
                            </button>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="8" class="bg-light">
                            <div class="collapse" id="supportTicket<?= e((string) $ticketId) ?>">
                                <div class="p-2 border rounded bg-white mb-2">
                                    <form action="<?= e(url('superadmin/soporte/tickets/' . $ticketId . '/actualizar')) ?>" method="post" class="row g-2">
                                        <?= csrf_field() ?>
                                        <div class="col-md-3">
                                            <label class="form-label">Estado</label>
                                            <select class="form-select" name="estado" required>
                                                <option value="abierto" <?= $ticketStatus === 'abierto' ? 'selected' : '' ?>>Abierto</option>
                                                <option value="en_proceso" <?= $ticketStatus === 'en_proceso' ? 'selected' : '' ?>>En proceso</option>
                                                <option value="pendiente_cliente" <?= $ticketStatus === 'pendiente_cliente' ? 'selected' : '' ?>>Pendiente cliente</option>
                                                <option value="resuelto" <?= $ticketStatus === 'resuelto' ? 'selected' : '' ?>>Resuelto</option>
                                                <option value="cerrado" <?= $ticketStatus === 'cerrado' ? 'selected' : '' ?>>Cerrado</option>
                                            </select>
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">Prioridad</label>
                                            <select class="form-select" name="prioridad" required>
                                                <option value="baja" <?= $ticketPriority === 'baja' ? 'selected' : '' ?>>Baja</option>
                                                <option value="media" <?= $ticketPriority === 'media' ? 'selected' : '' ?>>Media</option>
                                                <option value="alta" <?= $ticketPriority === 'alta' ? 'selected' : '' ?>>Alta</option>
                                                <option value="critica" <?= $ticketPriority === 'critica' ? 'selected' : '' ?>>Crítica</option>
                                            </select>
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">Asignar a</label>
                                            <select class="form-select" name="asignado_a_usuario_id">
                                                <option value="">Sin asignar</option>
                                                <?php foreach ($supportAgents as $agent): ?>
                                                    <option value="<?= e((string) ($agent['id'] ?? '')) ?>" <?= (int) ($ticket['asignado_a_usuario_id'] ?? 0) === (int) ($agent['id'] ?? 0) ? 'selected' : '' ?>>
                                                        <?= e((string) ($agent['nombre'] ?? '')) ?> (<?= e((string) ($agent['email'] ?? '')) ?>)
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-3 d-flex align-items-end">
                                            <button class="btn btn-sm btn-primary w-100" type="submit">Guardar cambios</button>
                                        </div>
                                    </form>
                                </div>

                                <div class="p-2 border rounded bg-white mb-2">
                                    <form action="<?= e(url('superadmin/soporte/tickets/' . $ticketId . '/comentario')) ?>" method="post" class="row g-2">
                                        <?= csrf_field() ?>
                                        <div class="col-md-2">
                                            <label class="form-label">Tipo</label>
                                            <select class="form-select" name="tipo">
                                                <option value="comentario">Comentario</option>
                                                <option value="interno">Nota interna</option>
                                            </select>
                                        </div>
                                        <div class="col-md-8">
                                            <label class="form-label">Mensaje</label>
                                            <input class="form-control" name="mensaje" maxlength="500" required>
                                        </div>
                                        <div class="col-md-2 d-flex align-items-end">
                                            <button class="btn btn-sm btn-outline-primary w-100" type="submit">Agregar</button>
                                        </div>
                                    </form>
                                </div>

                                <div class="p-2 border rounded bg-white">
                                    <strong class="d-block mb-2">Historial</strong>
                                    <?php if ($events !== []): ?>
                                        <ul class="list-group list-group-flush">
                                            <?php foreach (array_slice($events, 0, 12) as $event): ?>
                                                <?php
                                                $eventPayload = support_event_message_decode((string) ($event['mensaje'] ?? ''));
                                                $eventMessage = trim((string) ($eventPayload['text'] ?? ''));
                                                if ($eventMessage === '') {
                                                    $eventMessage = 'Adjunto sin comentario.';
                                                }
                                                $eventAttachment = is_array($eventPayload['attachment'] ?? null) ? $eventPayload['attachment'] : null;
                                                ?>
                                                <li class="list-group-item px-0 py-2">
                                                    <div class="d-flex justify-content-between">
                                                        <span>
                                                            <span class="badge text-bg-light border me-1"><?= e((string) ($event['tipo'] ?? '')) ?></span>
                                                            <?= e($eventMessage) ?>
                                                        </span>
                                                        <small class="text-muted"><?= e((string) ($event['created_at'] ?? '')) ?></small>
                                                    </div>
                                                    <?php if ($eventAttachment !== null): ?>
                                                        <div class="mt-1">
                                                            <a href="<?= e((string) ($eventAttachment['url'] ?? '')) ?>" target="_blank" rel="noopener">
                                                                Ver adjunto: <?= e((string) ($eventAttachment['name'] ?? 'imagen')) ?>
                                                            </a>
                                                            <?php if ((bool) ($eventAttachment['is_image'] ?? false)): ?>
                                                                <div class="mt-2">
                                                                    <img
                                                                        src="<?= e((string) ($eventAttachment['url'] ?? '')) ?>"
                                                                        alt="<?= e((string) ($eventAttachment['name'] ?? 'Adjunto')) ?>"
                                                                        style="max-width: 220px; width: 100%; border: 1px solid #dce4f4; border-radius: 8px;"
                                                                    >
                                                                </div>
                                                            <?php endif; ?>
                                                        </div>
                                                    <?php endif; ?>
                                                    <small class="text-muted">
                                                        <?= e((string) (($event['usuario'] ?? '') !== '' ? $event['usuario'] : 'Sistema')) ?>
                                                        <?php if (!empty($event['estado_anterior']) || !empty($event['estado_nuevo'])): ?>
                                                            | Estado: <?= e((string) ($event['estado_anterior'] ?? '-')) ?> -> <?= e((string) ($event['estado_nuevo'] ?? '-')) ?>
                                                        <?php endif; ?>
                                                    </small>
                                                </li>
                                            <?php endforeach; ?>
                                        </ul>
                                    <?php else: ?>
                                        <small class="text-muted">Sin eventos aún.</small>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
                <?php if ($supportTickets === []): ?>
                    <tr><td colspan="8" class="text-center text-muted py-3">No hay tickets de soporte registrados.</td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>
</div>

<div class="sa-section <?= $superadminSection === 'pagos' ? 'is-active' : '' ?>" data-sa-section="pagos">
<div class="card border-0 shadow-sm">
    <div class="card-body">
        <h2 class="h5 mb-3">Pagos SaaS (historial y estados)</h2>

        <form action="<?= e(url('superadmin/pagos')) ?>" method="post" class="row g-2 mb-4">
            <?= csrf_field() ?>
            <div class="col-md-3">
                <label class="form-label">Suscripción</label>
                <select class="form-select" name="suscripcion_id" required>
                    <option value="">Seleccione...</option>
                    <?php foreach ($subscriptions as $subscription): ?>
                        <option value="<?= e((string) $subscription['id']) ?>">
                            #<?= e((string) $subscription['id']) ?> - <?= e((string) ($subscription['empresa'] ?? '')) ?> (<?= e((string) ($subscription['estado'] ?? '')) ?>)
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">Pasarela</label>
                <select class="form-select" name="pasarela">
                    <option value="manual">Manual</option>
                    <option value="wompi">Wompi</option>
                    <option value="epayco">ePayco</option>
                    <option value="mercado_pago">Mercado Pago</option>
                    <option value="stripe">Stripe</option>
                    <option value="payu">PayU</option>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">Referencia</label>
                <input class="form-control" name="referencia">
            </div>
            <div class="col-md-1">
                <label class="form-label">Monto</label>
                <input type="number" step="0.01" min="0.01" class="form-control" name="monto" required>
            </div>
            <div class="col-md-1">
                <label class="form-label">Moneda</label>
                <input class="form-control" name="moneda" value="COP" maxlength="10">
            </div>
            <div class="col-md-1">
                <label class="form-label">Estado</label>
                <select class="form-select" name="estado">
                    <option value="pagado">Pagado</option>
                    <option value="pendiente">Pendiente</option>
                    <option value="fallido">Fallido</option>
                    <option value="reembolsado">Reembolsado</option>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">Fecha pago</label>
                <input type="datetime-local" class="form-control" name="fecha_pago" value="<?= e($paymentDateDefault) ?>">
            </div>
            <div class="col-md-2">
                <label class="form-label">Renovar (días)</label>
                <input type="number" min="0" class="form-control" name="renovar_dias" value="30">
            </div>
            <div class="col-12">
                <button class="btn btn-success" type="submit">Registrar pago</button>
            </div>
        </form>

        <div class="table-responsive">
            <table class="table table-striped table-hover align-middle">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>Empresa</th>
                    <th>Suscripción</th>
                    <th>Plan</th>
                    <th>Pasarela</th>
                    <th>Referencia</th>
                    <th>Monto</th>
                    <th>Estado</th>
                    <th>Fecha</th>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($payments as $payment): ?>
                    <?php
                    $payStatus = (string) ($payment['estado'] ?? 'pagado');
                    $payStatusClass = $payStatus === 'pagado'
                        ? 'text-bg-success'
                        : ($payStatus === 'pendiente' ? 'text-bg-warning' : ($payStatus === 'fallido' ? 'text-bg-danger' : 'text-bg-secondary'));
                    ?>
                    <tr>
                        <td><?= e((string) $payment['id']) ?></td>
                        <td><?= e((string) ($payment['empresa'] ?? '')) ?></td>
                        <td>#<?= e((string) ($payment['suscripcion_id'] ?? '')) ?></td>
                        <td><?= e((string) ($payment['plan'] ?? '')) ?></td>
                        <td><?= e((string) ($payment['pasarela'] ?? '')) ?></td>
                        <td><?= e((string) ($payment['referencia'] ?? '')) ?></td>
                        <td><?= e(money((float) ($payment['monto'] ?? 0))) ?> <?= e((string) ($payment['moneda'] ?? 'COP')) ?></td>
                        <td><span class="badge <?= e($payStatusClass) ?>"><?= e($payStatus) ?></span></td>
                        <td><?= e((string) ($payment['fecha_pago'] ?? '')) ?></td>
                    </tr>
                <?php endforeach; ?>
                <?php if ($payments === []): ?>
                    <tr><td colspan="9" class="text-center text-muted py-3">Sin pagos registrados.</td></tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
</div>
</div>
</div>

<div
    class="modal fade sa-company-edit-modal"
    id="saCompanyEditModal"
    tabindex="-1"
    aria-hidden="true"
    data-update-template="<?= e(url('superadmin/empresas/__ID__/estado')) ?>"
>
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <form id="saCompanyEditForm" method="post" action="">
                <?= csrf_field() ?>
                <div class="modal-header">
                    <h5 class="modal-title">Editar empresa</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                </div>
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-2">
                            <label class="form-label">ID</label>
                            <input type="text" class="form-control" id="saCompanyEditId" readonly>
                        </div>
                        <div class="col-md-5">
                            <label class="form-label">Empresa</label>
                            <input type="text" class="form-control" id="saCompanyEditName" readonly>
                        </div>
                        <div class="col-md-5">
                            <label class="form-label">Email</label>
                            <input type="text" class="form-control" id="saCompanyEditEmail" readonly>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Plan actual</label>
                            <input type="text" class="form-control" id="saCompanyEditPlan" readonly>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Suscripción</label>
                            <input type="text" class="form-control" id="saCompanyEditSubscription" readonly>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Vencimiento</label>
                            <input type="text" class="form-control" id="saCompanyEditExpiration" readonly>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Estado de empresa</label>
                            <select class="form-select" id="saCompanyEditStatus" name="estado" required>
                                <option value="activa">Activa</option>
                                <option value="suspendida">Suspendida</option>
                                <option value="bloqueada">Bloqueada</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Creada</label>
                            <input type="text" class="form-control" id="saCompanyEditCreatedAt" readonly>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-outline-secondary" type="button" data-bs-dismiss="modal">Cancelar</button>
                    <button class="btn btn-primary" type="submit">
                        <i class="bx bx-save me-1"></i>
                        Guardar
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<div
    class="modal fade sa-factus-modal"
    id="saCompanyFactusModal"
    tabindex="-1"
    aria-hidden="true"
    data-open-company-id="<?= e((string) $openFactusCompanyId) ?>"
    data-save-template="<?= e(url('superadmin/empresas/__ID__/factus')) ?>"
    data-test-template="<?= e(url('superadmin/empresas/__ID__/factus/probar')) ?>"
    data-invoice-template="<?= e(url('superadmin/empresas/__ID__/factus/probar-factura')) ?>"
    data-ranges-template="<?= e(url('superadmin/empresas/__ID__/factus/rangos')) ?>"
    data-municipalities-template="<?= e(url('superadmin/empresas/__ID__/factus/municipios')) ?>"
>
    <div class="modal-dialog modal-xl modal-dialog-scrollable">
        <div class="modal-content">
            <form id="saCompanyFactusForm" method="post" action="">
                <?= csrf_field() ?>
                <input type="hidden" name="facturacion_electronica" id="saFactusEnabledInput" value="1">
                <div class="modal-header">
                    <h5 class="modal-title">Facturación electrónica (Factus)</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
                </div>
                <div class="modal-body">
                    <div class="sa-factus-header mb-3">
                        <div>
                            <strong id="saFactusCompanyName">Empresa</strong>
                            <small id="saFactusCompanyMeta" class="d-block text-muted"></small>
                        </div>
                        <div class="sa-factus-status">
                            <span class="badge text-bg-secondary" id="saFactusPlanBadge">Sin plan FE</span>
                            <span class="badge text-bg-secondary" id="saFactusModuleBadge">Módulo pendiente</span>
                            <span class="badge text-bg-secondary" id="saFactusReadyBadge">Factus incompleto</span>
                        </div>
                    </div>

                    <div class="alert alert-warning d-none" id="saFactusPlanWarning">
                        El plan actual de esta empresa no permite facturación electrónica. Cambia primero a un plan con FE.
                    </div>

                    <div class="alert alert-light border mb-3">
                        <strong>Acceso restringido:</strong> solo Superadmin puede gestionar este módulo.
                        Todos los cambios y pruebas quedan registrados en auditoría.
                    </div>

                    <fieldset id="saFactusFieldset">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <label class="form-label">URL API Factus</label>
                                <input
                                    type="url"
                                    class="form-control"
                                    name="factus_api_url"
                                    id="saFactusApiUrlInput"
                                    maxlength="255"
                                    placeholder="https://api-sandbox.factus.com.co"
                                    data-factus-key="api_url"
                                    data-factus-required="1"
                                >
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Usuario / email Factus</label>
                                <div class="d-flex align-items-center gap-2">
                                    <input
                                        class="form-control"
                                        name="factus_username"
                                        id="saFactusUsernameInput"
                                        maxlength="120"
                                        autocomplete="off"
                                        data-factus-key="username"
                                        data-factus-required="1"
                                    >
                                    <span class="badge text-bg-success d-none" data-factus-flag-badge="username">OK</span>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Client ID</label>
                                <div class="d-flex align-items-center gap-2">
                                    <input
                                        class="form-control"
                                        name="factus_client_id"
                                        id="saFactusClientIdInput"
                                        maxlength="120"
                                        autocomplete="off"
                                        data-factus-key="client_id"
                                        data-factus-required="1"
                                    >
                                    <span class="badge text-bg-success d-none" data-factus-flag-badge="client_id">OK</span>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Client Secret</label>
                                <div class="d-flex align-items-center gap-2">
                                    <input
                                        type="password"
                                        class="form-control"
                                        name="factus_client_secret"
                                        id="saFactusClientSecretInput"
                                        maxlength="255"
                                        autocomplete="new-password"
                                        data-factus-key="client_secret"
                                        data-factus-required="1"
                                    >
                                    <span class="badge text-bg-success d-none" data-factus-flag-badge="client_secret">OK</span>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Software ID</label>
                                <div class="d-flex align-items-center gap-2">
                                    <input
                                        class="form-control"
                                        name="factus_software_id"
                                        id="saFactusSoftwareIdInput"
                                        maxlength="120"
                                        autocomplete="off"
                                        data-factus-key="software_id"
                                        data-factus-required="1"
                                    >
                                    <span class="badge text-bg-success d-none" data-factus-flag-badge="software_id">OK</span>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Software PIN</label>
                                <div class="d-flex align-items-center gap-2">
                                    <input
                                        type="password"
                                        class="form-control"
                                        name="factus_software_pin"
                                        id="saFactusSoftwarePinInput"
                                        maxlength="120"
                                        autocomplete="new-password"
                                        data-factus-key="software_pin"
                                        data-factus-required="1"
                                    >
                                    <span class="badge text-bg-success d-none" data-factus-flag-badge="software_pin">OK</span>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label">Contraseña Factus</label>
                                <div class="d-flex align-items-center gap-2">
                                    <input
                                        type="password"
                                        class="form-control"
                                        name="factus_password"
                                        id="saFactusPasswordInput"
                                        maxlength="255"
                                        autocomplete="new-password"
                                        data-factus-key="password"
                                        data-factus-required="1"
                                    >
                                    <span class="badge text-bg-success d-none" data-factus-flag-badge="password">OK</span>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="d-flex align-items-center justify-content-between gap-2">
                                    <label class="form-label mb-0">Numbering Range ID</label>
                                    <button
                                        type="button"
                                        class="btn btn-sm btn-outline-secondary"
                                        id="saFactusLoadRangesBtn"
                                    >
                                        Cargar rangos
                                    </button>
                                </div>
                                <div class="d-flex align-items-center gap-2">
                                    <input
                                        class="form-control"
                                        name="factus_numbering_range_id"
                                        id="saFactusNumberingRangeInput"
                                        maxlength="20"
                                        inputmode="numeric"
                                        pattern="[0-9]+"
                                        placeholder="Ej: 8"
                                        data-factus-key="numbering_range_id"
                                    >
                                    <span class="badge text-bg-success d-none" data-factus-flag-badge="numbering_range_id">OK</span>
                                </div>
                                <select class="form-select mt-2 d-none" id="saFactusNumberingRangeSelect">
                                    <option value="">Selecciona un rango...</option>
                                </select>
                                <small class="text-muted d-block mt-1" id="saFactusRangesHint">Puedes cargar y seleccionar un rango activo desde Factus.</small>
                            </div>
                            <div class="col-md-6">
                                <div class="d-flex align-items-center justify-content-between gap-2">
                                    <label class="form-label mb-0">Municipality ID</label>
                                    <button
                                        type="button"
                                        class="btn btn-sm btn-outline-secondary"
                                        id="saFactusLoadMunicipalitiesBtn"
                                    >
                                        Cargar municipios
                                    </button>
                                </div>
                                <div class="d-flex align-items-center gap-2">
                                    <input
                                        class="form-control"
                                        name="factus_municipality_id"
                                        id="saFactusMunicipalityInput"
                                        maxlength="20"
                                        inputmode="numeric"
                                        pattern="[0-9]+"
                                        placeholder="Ej: 980"
                                        data-factus-key="municipality_id"
                                    >
                                    <span class="badge text-bg-success d-none" data-factus-flag-badge="municipality_id">OK</span>
                                </div>
                                <div class="row g-2 mt-1">
                                    <div class="col-12 col-md-5">
                                        <input
                                            type="search"
                                            class="form-control"
                                            id="saFactusMunicipalitySearch"
                                            placeholder="Buscar municipio..."
                                        >
                                    </div>
                                    <div class="col-12 col-md-7">
                                        <select class="form-select d-none" id="saFactusMunicipalitySelect">
                                            <option value="">Selecciona un municipio...</option>
                                        </select>
                                    </div>
                                </div>
                                <small class="text-muted d-block mt-1" id="saFactusMunicipalitiesHint">Puedes buscar por nombre y seleccionar el ID correcto desde Factus.</small>
                            </div>
                        </div>
                    </fieldset>

                    <small class="text-muted d-block mt-3">
                        Puedes dejar campos sensibles en blanco para conservar credenciales guardadas. Para emisión FE se requieren Numbering Range ID y Municipality ID.
                    </small>
                </div>
                <div class="modal-footer sa-factus-footer">
                    <button class="btn btn-outline-danger d-none" type="button" id="saFactusDisableBtn">Desactivar FE</button>
                    <button class="btn btn-primary" type="submit" id="saFactusSaveBtn">Guardar configuración Factus</button>
                    <button class="btn btn-outline-secondary" type="submit" id="saFactusTestBtn">Probar conexión Factus</button>
                    <button class="btn btn-outline-primary" type="submit" id="saFactusInvoiceBtn">Emitir factura de prueba FE</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
window.addEventListener('DOMContentLoaded', () => {
    const modal = document.getElementById('saCompanyFactusModal');
    const form = document.getElementById('saCompanyFactusForm');
    if (!(modal instanceof HTMLElement) || !(form instanceof HTMLFormElement)) {
        return;
    }

    const triggerButtons = Array.from(document.querySelectorAll('.js-sa-factus-open'));
    if (triggerButtons.length === 0) {
        return;
    }

    const saveTemplate = String(modal.dataset.saveTemplate || '');
    const testTemplate = String(modal.dataset.testTemplate || '');
    const invoiceTemplate = String(modal.dataset.invoiceTemplate || '');
    const rangesTemplate = String(modal.dataset.rangesTemplate || '');
    const municipalitiesTemplate = String(modal.dataset.municipalitiesTemplate || '');
    const autoOpenCompanyId = Number.parseInt(String(modal.dataset.openCompanyId || '0'), 10) || 0;

    const companyNameLabel = document.getElementById('saFactusCompanyName');
    const companyMetaLabel = document.getElementById('saFactusCompanyMeta');
    const planBadge = document.getElementById('saFactusPlanBadge');
    const moduleBadge = document.getElementById('saFactusModuleBadge');
    const readyBadge = document.getElementById('saFactusReadyBadge');
    const planWarning = document.getElementById('saFactusPlanWarning');
    const fieldset = document.getElementById('saFactusFieldset');
    const feEnabledInput = document.getElementById('saFactusEnabledInput');
    const saveButton = document.getElementById('saFactusSaveBtn');
    const testButton = document.getElementById('saFactusTestBtn');
    const invoiceButton = document.getElementById('saFactusInvoiceBtn');
    const disableButton = document.getElementById('saFactusDisableBtn');

    const factusLoadRangesBtn = document.getElementById('saFactusLoadRangesBtn');
    const factusLoadMunicipalitiesBtn = document.getElementById('saFactusLoadMunicipalitiesBtn');
    const factusNumberingRangeInput = document.getElementById('saFactusNumberingRangeInput');
    const factusNumberingRangeSelect = document.getElementById('saFactusNumberingRangeSelect');
    const factusRangesHint = document.getElementById('saFactusRangesHint');
    const factusMunicipalityInput = document.getElementById('saFactusMunicipalityInput');
    const factusMunicipalitySearch = document.getElementById('saFactusMunicipalitySearch');
    const factusMunicipalitySelect = document.getElementById('saFactusMunicipalitySelect');
    const factusMunicipalitiesHint = document.getElementById('saFactusMunicipalitiesHint');

    const factusFieldNames = [
        'factus_api_url',
        'factus_username',
        'factus_client_id',
        'factus_client_secret',
        'factus_software_id',
        'factus_software_pin',
        'factus_password',
        'factus_numbering_range_id',
        'factus_municipality_id',
    ];

    const requiredInputs = Array.from(form.querySelectorAll('[data-factus-required="1"]'));
    const sensitiveInputs = Array.from(form.querySelectorAll('[data-factus-key]'));
    let currentCompanyId = 0;
    let currentPlanAllowsFe = false;
    let currentModuleActive = false;

    const buildCompanyUrl = (template, companyId) => {
        const id = Number.isFinite(companyId) ? Math.max(0, companyId) : 0;
        if (template === '' || id <= 0) {
            return '';
        }
        return template.replace('__ID__', String(id));
    };

    const setFactusHint = (element, message, isError = false) => {
        if (!(element instanceof HTMLElement)) {
            return;
        }
        element.textContent = String(message || '');
        element.classList.toggle('text-danger', isError);
    };

    const setFactusButtonLoading = (button, loading) => {
        if (!(button instanceof HTMLButtonElement)) {
            return;
        }

        if (loading) {
            button.dataset.originalText = button.textContent || '';
            button.disabled = true;
            button.textContent = 'Cargando...';
            return;
        }

        button.disabled = false;
        button.textContent = button.dataset.originalText || button.textContent || '';
    };

    const syncRequiredInputs = () => {
        requiredInputs.forEach((input) => {
            if (!(input instanceof HTMLInputElement)) {
                return;
            }
            const isConfigured = String(input.dataset.factusConfigured || '0') === '1';
            const hasValue = String(input.value || '').trim() !== '';
            input.required = !isConfigured && !hasValue;
        });
    };

    const setBadgeState = (badge, active, trueLabel, falseLabel, trueClass, falseClass) => {
        if (!(badge instanceof HTMLElement)) {
            return;
        }
        badge.textContent = active ? trueLabel : falseLabel;
        badge.className = 'badge ' + (active ? trueClass : falseClass);
    };

    const setInputConfiguredFlag = (key, configured) => {
        const input = form.querySelector(`[data-factus-key="${key}"]`);
        if (input instanceof HTMLInputElement) {
            input.dataset.factusConfigured = configured ? '1' : '0';
            if (configured && String(input.value || '').trim() === '' && key !== 'api_url' && key !== 'numbering_range_id' && key !== 'municipality_id') {
                input.placeholder = 'Configurado (oculto)';
            } else if (!configured && (key === 'api_url' || key === 'numbering_range_id' || key === 'municipality_id')) {
                input.placeholder = key === 'api_url' ? 'https://api-sandbox.factus.com.co' : (key === 'numbering_range_id' ? 'Ej: 8' : 'Ej: 980');
            }
        }

        const badge = form.querySelector(`[data-factus-flag-badge="${key}"]`);
        if (badge instanceof HTMLElement) {
            badge.classList.toggle('d-none', !configured);
        }
    };

    const setFormLocked = (locked) => {
        if (fieldset instanceof HTMLFieldSetElement) {
            fieldset.disabled = locked;
        }
        if (saveButton instanceof HTMLButtonElement) {
            saveButton.disabled = locked;
        }
        if (testButton instanceof HTMLButtonElement) {
            testButton.disabled = locked;
        }
        if (invoiceButton instanceof HTMLButtonElement) {
            invoiceButton.disabled = locked;
        }
    };

    const readInput = (name) => {
        const field = form.querySelector(`[name="${name}"]`);
        if (
            field instanceof HTMLInputElement
            || field instanceof HTMLTextAreaElement
            || field instanceof HTMLSelectElement
        ) {
            return String(field.value || '').trim();
        }
        return '';
    };

    const readCsrf = () => {
        const field = form.querySelector('input[name="_token"]');
        if (field instanceof HTMLInputElement) {
            return String(field.value || '').trim();
        }
        return '';
    };

    const factusPost = async (url, extraPayload = {}) => {
        const csrfToken = readCsrf();
        if (csrfToken === '') {
            throw new Error('Token CSRF inválido. Recarga la página e intenta de nuevo.');
        }

        const payload = new URLSearchParams();
        payload.set('_token', csrfToken);
        factusFieldNames.forEach((name) => payload.set(name, readInput(name)));
        Object.entries(extraPayload).forEach(([key, value]) => {
            payload.set(key, String(value ?? ''));
        });

        const response = await fetch(url, {
            method: 'POST',
            credentials: 'same-origin',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json',
            },
            body: payload.toString(),
        });

        const data = await response.json().catch(() => ({}));
        if (!response.ok || data?.ok !== true) {
            throw new Error(String(data?.message || 'No fue posible consultar Factus.'));
        }

        return data;
    };

    const hydrateModal = (button) => {
        if (!(button instanceof HTMLElement)) {
            return;
        }

        currentCompanyId = Number.parseInt(String(button.dataset.companyId || '0'), 10) || 0;
        const companyName = String(button.dataset.companyName || 'Empresa');
        const companyEmail = String(button.dataset.companyEmail || '');
        const companyPlan = String(button.dataset.companyPlan || 'Sin plan');
        currentPlanAllowsFe = String(button.dataset.companyPlanFe || '0') === '1';
        const moduleActive = String(button.dataset.companyFeActive || '0') === '1';
        currentModuleActive = moduleActive;
        const ready = String(button.dataset.companyFactusReady || '0') === '1';

        if (companyNameLabel instanceof HTMLElement) {
            companyNameLabel.textContent = companyName;
        }
        if (companyMetaLabel instanceof HTMLElement) {
            companyMetaLabel.textContent = `Plan: ${companyPlan}${companyEmail !== '' ? ` · ${companyEmail}` : ''}`;
        }

        setBadgeState(
            planBadge,
            currentPlanAllowsFe,
            'Plan con FE',
            'Plan sin FE',
            'text-bg-success',
            'text-bg-secondary'
        );
        setBadgeState(
            moduleBadge,
            moduleActive,
            'Módulo activo',
            'Módulo pendiente',
            'text-bg-primary',
            'text-bg-secondary'
        );
        setBadgeState(
            readyBadge,
            ready,
            'Factus listo',
            'Factus incompleto',
            'text-bg-success',
            'text-bg-warning'
        );

        if (planWarning instanceof HTMLElement) {
            planWarning.classList.toggle('d-none', currentPlanAllowsFe);
        }
        setFormLocked(!currentPlanAllowsFe);
        if (disableButton instanceof HTMLButtonElement) {
            disableButton.classList.toggle('d-none', !currentModuleActive);
            disableButton.disabled = currentCompanyId <= 0;
        }
        if (feEnabledInput instanceof HTMLInputElement) {
            feEnabledInput.value = '1';
        }

        const saveUrl = buildCompanyUrl(saveTemplate, currentCompanyId);
        const testUrl = buildCompanyUrl(testTemplate, currentCompanyId);
        const invoiceUrl = buildCompanyUrl(invoiceTemplate, currentCompanyId);

        if (saveUrl !== '') {
            form.action = saveUrl;
        }
        if (testButton instanceof HTMLButtonElement && testUrl !== '') {
            testButton.formAction = testUrl;
        }
        if (invoiceButton instanceof HTMLButtonElement && invoiceUrl !== '') {
            invoiceButton.formAction = invoiceUrl;
        }

        const apiUrlInput = document.getElementById('saFactusApiUrlInput');
        if (apiUrlInput instanceof HTMLInputElement) {
            apiUrlInput.value = String(button.dataset.companyApiUrl || '');
        }
        if (factusNumberingRangeInput instanceof HTMLInputElement) {
            factusNumberingRangeInput.value = String(button.dataset.companyRangeId || '');
        }
        if (factusMunicipalityInput instanceof HTMLInputElement) {
            factusMunicipalityInput.value = String(button.dataset.companyMunicipalityId || '');
        }

        sensitiveInputs.forEach((input) => {
            if (!(input instanceof HTMLInputElement)) {
                return;
            }
            const key = String(input.dataset.factusKey || '');
            if (key !== 'api_url' && key !== 'numbering_range_id' && key !== 'municipality_id') {
                input.value = '';
            }
        });

        const flags = {
            api_url: String(button.dataset.flagApiUrl || '0') === '1',
            client_id: String(button.dataset.flagClientId || '0') === '1',
            client_secret: String(button.dataset.flagClientSecret || '0') === '1',
            username: String(button.dataset.flagUsername || '0') === '1',
            password: String(button.dataset.flagPassword || '0') === '1',
            software_id: String(button.dataset.flagSoftwareId || '0') === '1',
            software_pin: String(button.dataset.flagSoftwarePin || '0') === '1',
            numbering_range_id: String(button.dataset.flagNumberingRangeId || '0') === '1',
            municipality_id: String(button.dataset.flagMunicipalityId || '0') === '1',
        };

        Object.entries(flags).forEach(([key, value]) => {
            setInputConfiguredFlag(key, value);
        });
        syncRequiredInputs();

        if (factusNumberingRangeSelect instanceof HTMLSelectElement) {
            factusNumberingRangeSelect.classList.add('d-none');
            factusNumberingRangeSelect.innerHTML = '<option value="">Selecciona un rango...</option>';
        }
        if (factusMunicipalitySelect instanceof HTMLSelectElement) {
            factusMunicipalitySelect.classList.add('d-none');
            factusMunicipalitySelect.innerHTML = '<option value="">Selecciona un municipio...</option>';
        }
        if (factusMunicipalitySearch instanceof HTMLInputElement) {
            factusMunicipalitySearch.value = '';
        }
        setFactusHint(factusRangesHint, 'Puedes cargar y seleccionar un rango activo desde Factus.', false);
        setFactusHint(factusMunicipalitiesHint, 'Puedes buscar por nombre y seleccionar el ID correcto desde Factus.', false);
    };

    requiredInputs.forEach((input) => {
        if (!(input instanceof HTMLInputElement)) {
            return;
        }
        input.addEventListener('input', syncRequiredInputs);
        input.addEventListener('change', syncRequiredInputs);
    });

    if (factusNumberingRangeSelect instanceof HTMLSelectElement && factusNumberingRangeInput instanceof HTMLInputElement) {
        factusNumberingRangeSelect.addEventListener('change', () => {
            const selectedValue = String(factusNumberingRangeSelect.value || '').trim();
            if (selectedValue !== '') {
                factusNumberingRangeInput.value = selectedValue;
            }
        });
    }

    if (factusMunicipalitySelect instanceof HTMLSelectElement && factusMunicipalityInput instanceof HTMLInputElement) {
        factusMunicipalitySelect.addEventListener('change', () => {
            const selectedValue = String(factusMunicipalitySelect.value || '').trim();
            if (selectedValue !== '') {
                factusMunicipalityInput.value = selectedValue;
            }
        });
    }

    if (
        factusLoadRangesBtn instanceof HTMLButtonElement
        && factusNumberingRangeSelect instanceof HTMLSelectElement
        && factusNumberingRangeInput instanceof HTMLInputElement
    ) {
        factusLoadRangesBtn.addEventListener('click', async () => {
            if (!currentPlanAllowsFe || currentCompanyId <= 0) {
                return;
            }

            const rangesUrl = buildCompanyUrl(rangesTemplate, currentCompanyId);
            if (rangesUrl === '') {
                setFactusHint(factusRangesHint, 'No fue posible resolver la URL de rangos Factus.', true);
                return;
            }

            setFactusButtonLoading(factusLoadRangesBtn, true);
            setFactusHint(factusRangesHint, 'Consultando rangos activos en Factus...');

            try {
                const response = await factusPost(rangesUrl, {
                    document: '21',
                    solo_activas: '1',
                });

                const rows = Array.isArray(response?.data) ? response.data : [];
                factusNumberingRangeSelect.innerHTML = '';

                const emptyOption = document.createElement('option');
                emptyOption.value = '';
                emptyOption.textContent = rows.length > 0
                    ? 'Selecciona un rango...'
                    : 'Sin rangos disponibles';
                factusNumberingRangeSelect.appendChild(emptyOption);

                const currentValue = String(factusNumberingRangeInput.value || '').trim();
                rows.forEach((row) => {
                    const rangeId = Number(row?.id || 0);
                    if (!Number.isFinite(rangeId) || rangeId <= 0) {
                        return;
                    }

                    const option = document.createElement('option');
                    option.value = String(rangeId);
                    option.textContent = String(row?.label || `Rango #${rangeId}`);
                    if (currentValue !== '' && currentValue === option.value) {
                        option.selected = true;
                    }
                    factusNumberingRangeSelect.appendChild(option);
                });

                factusNumberingRangeSelect.classList.toggle('d-none', rows.length === 0);
                setFactusHint(
                    factusRangesHint,
                    rows.length > 0
                        ? `Rangos cargados: ${rows.length}. Selecciona uno para completar el ID.`
                        : String(response?.message || 'No se encontraron rangos activos.'),
                    false
                );
            } catch (error) {
                setFactusHint(
                    factusRangesHint,
                    error instanceof Error ? error.message : 'No fue posible cargar rangos en Factus.',
                    true
                );
                factusNumberingRangeSelect.classList.add('d-none');
            } finally {
                setFactusButtonLoading(factusLoadRangesBtn, false);
            }
        });
    }

    if (
        factusLoadMunicipalitiesBtn instanceof HTMLButtonElement
        && factusMunicipalitySelect instanceof HTMLSelectElement
        && factusMunicipalityInput instanceof HTMLInputElement
    ) {
        const fetchMunicipalities = async () => {
            if (!currentPlanAllowsFe || currentCompanyId <= 0) {
                return;
            }

            const municipalitiesUrl = buildCompanyUrl(municipalitiesTemplate, currentCompanyId);
            if (municipalitiesUrl === '') {
                setFactusHint(factusMunicipalitiesHint, 'No fue posible resolver la URL de municipios Factus.', true);
                return;
            }

            setFactusButtonLoading(factusLoadMunicipalitiesBtn, true);
            setFactusHint(factusMunicipalitiesHint, 'Consultando municipios en Factus...');

            try {
                const searchText = factusMunicipalitySearch instanceof HTMLInputElement
                    ? String(factusMunicipalitySearch.value || '').trim()
                    : '';
                const response = await factusPost(municipalitiesUrl, {
                    query: searchText,
                    limit: '120',
                });

                const rows = Array.isArray(response?.data) ? response.data : [];
                factusMunicipalitySelect.innerHTML = '';

                const emptyOption = document.createElement('option');
                emptyOption.value = '';
                emptyOption.textContent = rows.length > 0
                    ? 'Selecciona un municipio...'
                    : 'Sin municipios disponibles';
                factusMunicipalitySelect.appendChild(emptyOption);

                const currentValue = String(factusMunicipalityInput.value || '').trim();
                rows.forEach((row) => {
                    const municipalityId = Number(row?.id || 0);
                    if (!Number.isFinite(municipalityId) || municipalityId <= 0) {
                        return;
                    }

                    const option = document.createElement('option');
                    option.value = String(municipalityId);
                    option.textContent = String(row?.label || `Municipio #${municipalityId}`);
                    if (currentValue !== '' && currentValue === option.value) {
                        option.selected = true;
                    }
                    factusMunicipalitySelect.appendChild(option);
                });

                factusMunicipalitySelect.classList.toggle('d-none', rows.length === 0);
                setFactusHint(
                    factusMunicipalitiesHint,
                    rows.length > 0
                        ? `Municipios cargados: ${rows.length}. Selecciona uno para completar el ID.`
                        : String(response?.message || 'No se encontraron municipios con ese criterio.'),
                    false
                );
            } catch (error) {
                setFactusHint(
                    factusMunicipalitiesHint,
                    error instanceof Error ? error.message : 'No fue posible cargar municipios en Factus.',
                    true
                );
                factusMunicipalitySelect.classList.add('d-none');
            } finally {
                setFactusButtonLoading(factusLoadMunicipalitiesBtn, false);
            }
        };

        factusLoadMunicipalitiesBtn.addEventListener('click', fetchMunicipalities);
        if (factusMunicipalitySearch instanceof HTMLInputElement) {
            factusMunicipalitySearch.addEventListener('keydown', (event) => {
                if (event.key !== 'Enter') {
                    return;
                }
                event.preventDefault();
                fetchMunicipalities();
            });
        }
    }

    triggerButtons.forEach((button) => {
        button.addEventListener('click', () => {
            hydrateModal(button);
        });
    });

    if (saveButton instanceof HTMLButtonElement) {
        saveButton.addEventListener('click', () => {
            if (feEnabledInput instanceof HTMLInputElement) {
                feEnabledInput.value = '1';
            }
        });
    }
    if (testButton instanceof HTMLButtonElement) {
        testButton.addEventListener('click', () => {
            if (feEnabledInput instanceof HTMLInputElement) {
                feEnabledInput.value = '1';
            }
        });
    }
    if (invoiceButton instanceof HTMLButtonElement) {
        invoiceButton.addEventListener('click', () => {
            if (feEnabledInput instanceof HTMLInputElement) {
                feEnabledInput.value = '1';
            }
        });
    }

    if (disableButton instanceof HTMLButtonElement) {
        disableButton.addEventListener('click', (event) => {
            event.preventDefault();
            if (!(feEnabledInput instanceof HTMLInputElement)) {
                return;
            }
            if (currentCompanyId <= 0 || !currentModuleActive) {
                return;
            }

            const submitDisable = () => {
                feEnabledInput.value = '0';
                form.submit();
            };

            if (typeof window.Swal === 'undefined') {
                const accepted = window.confirm('¿Desactivar facturación electrónica para esta empresa?');
                if (accepted) {
                    submitDisable();
                }
                return;
            }

            window.Swal.fire({
                icon: 'warning',
                title: 'Desactivar FE',
                text: 'La empresa dejará de emitir facturación electrónica hasta volver a activarla.',
                showCancelButton: true,
                confirmButtonText: 'Sí, desactivar',
                cancelButtonText: 'Cancelar',
                reverseButtons: true,
            }).then((result) => {
                if (!result.isConfirmed) {
                    return;
                }
                submitDisable();
            });
        });
    }

    if (autoOpenCompanyId > 0) {
        const autoButton = document.querySelector(`.js-sa-factus-open[data-company-id="${autoOpenCompanyId}"]`);
        if (autoButton instanceof HTMLElement) {
            hydrateModal(autoButton);
            if (window.bootstrap?.Modal) {
                const instance = window.bootstrap.Modal.getOrCreateInstance(modal);
                instance.show();
            }
        }
    }
});
</script>
<script>
window.addEventListener('DOMContentLoaded', () => {
    const form = document.getElementById('saWhatsAppTemplateBuilderForm');
    if (!(form instanceof HTMLFormElement)) {
        return;
    }

    const headerInput = document.getElementById('template_header_text');
    const bodyInput = document.getElementById('template_body_text');
    const footerInput = document.getElementById('template_footer_text');
    const buttonTextInput = document.getElementById('template_button_text');
    const buttonUrlInput = document.getElementById('template_button_url');

    const previewHeader = document.getElementById('saTemplatePreviewHeader');
    const previewBody = document.getElementById('saTemplatePreviewBody');
    const previewFooter = document.getElementById('saTemplatePreviewFooter');
    const previewButton = document.getElementById('saTemplatePreviewButton');

    const readValue = (element) => {
        if (
            element instanceof HTMLInputElement
            || element instanceof HTMLTextAreaElement
            || element instanceof HTMLSelectElement
        ) {
            return String(element.value || '').trim();
        }
        return '';
    };

    const updatePreview = () => {
        const header = readValue(headerInput);
        const body = readValue(bodyInput);
        const footer = readValue(footerInput);
        const buttonText = readValue(buttonTextInput);
        const buttonUrl = readValue(buttonUrlInput);

        if (previewHeader instanceof HTMLElement) {
            previewHeader.textContent = header !== '' ? header : 'Encabezado';
            previewHeader.style.display = header !== '' ? '' : 'none';
        }
        if (previewBody instanceof HTMLElement) {
            previewBody.textContent = body !== '' ? body : 'Escribe el cuerpo de la plantilla para ver la previsualizacion.';
        }
        if (previewFooter instanceof HTMLElement) {
            previewFooter.textContent = footer !== '' ? footer : 'Pie de pagina';
            previewFooter.style.display = footer !== '' ? '' : 'none';
        }
        if (previewButton instanceof HTMLAnchorElement) {
            const shouldShowButton = buttonText !== '' && buttonUrl !== '';
            previewButton.textContent = buttonText !== '' ? buttonText : 'Boton URL';
            previewButton.href = shouldShowButton ? buttonUrl : '#';
            previewButton.classList.toggle('is-hidden', !shouldShowButton);
        }
    };

    [headerInput, bodyInput, footerInput, buttonTextInput, buttonUrlInput].forEach((element) => {
        if (
            element instanceof HTMLInputElement
            || element instanceof HTMLTextAreaElement
            || element instanceof HTMLSelectElement
        ) {
            element.addEventListener('input', updatePreview);
            element.addEventListener('change', updatePreview);
        }
    });

    const modalEl = document.getElementById('saWhatsAppTemplateBuilderModal');
    if (modalEl instanceof HTMLElement) {
        modalEl.addEventListener('shown.bs.modal', updatePreview);
    }

    updatePreview();
});
</script>
<script>
window.addEventListener('DOMContentLoaded', () => {
    const modalToOpen = <?= json_encode($whatsAppModalAutoOpen, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
    if (modalToOpen !== 'meta' && modalToOpen !== 'manychat' && modalToOpen !== 'template' && modalToOpen !== 'template_link') {
        return;
    }
    if (typeof window.bootstrap === 'undefined' || typeof window.bootstrap.Modal === 'undefined') {
        return;
    }
    const modalMap = {
        meta: 'saWhatsAppMetaModal',
        manychat: 'saWhatsAppManyChatModal',
        template: 'saWhatsAppTemplateBuilderModal',
        template_link: 'saWhatsAppTemplateLinkModal',
    };
    const modalId = String(modalMap[modalToOpen] || '');
    if (modalId === '') {
        return;
    }
    const modalEl = document.getElementById(modalId);
    if (!(modalEl instanceof HTMLElement)) {
        return;
    }
    const instance = window.bootstrap.Modal.getOrCreateInstance(modalEl);
    instance.show();
});
</script>
<script>
window.addEventListener('DOMContentLoaded', () => {
    const modal = document.getElementById('saCompanyEditModal');
    const form = document.getElementById('saCompanyEditForm');
    if (!(modal instanceof HTMLElement) || !(form instanceof HTMLFormElement)) {
        return;
    }

    const updateTemplate = String(modal.dataset.updateTemplate || '');
    if (updateTemplate === '') {
        return;
    }

    const idInput = document.getElementById('saCompanyEditId');
    const nameInput = document.getElementById('saCompanyEditName');
    const emailInput = document.getElementById('saCompanyEditEmail');
    const planInput = document.getElementById('saCompanyEditPlan');
    const subscriptionInput = document.getElementById('saCompanyEditSubscription');
    const expirationInput = document.getElementById('saCompanyEditExpiration');
    const createdAtInput = document.getElementById('saCompanyEditCreatedAt');
    const statusSelect = document.getElementById('saCompanyEditStatus');

    const setField = (field, value) => {
        if (!(field instanceof HTMLInputElement)) {
            return;
        }
        field.value = String(value || '');
    };

    const hydrate = (button) => {
        if (!(button instanceof HTMLElement)) {
            return;
        }

        const companyId = Number.parseInt(String(button.dataset.companyId || '0'), 10) || 0;
        if (companyId <= 0) {
            return;
        }

        form.action = updateTemplate.replace('__ID__', String(companyId));
        setField(idInput, `#${companyId}`);
        setField(nameInput, button.dataset.companyName || '');
        setField(emailInput, button.dataset.companyEmail || '');
        setField(planInput, button.dataset.companyPlan || 'Sin plan');
        setField(subscriptionInput, button.dataset.companySubscriptionStatus || '-');
        setField(expirationInput, button.dataset.companyVencimiento || '-');
        setField(createdAtInput, button.dataset.companyCreatedAt || '-');

        if (statusSelect instanceof HTMLSelectElement) {
            statusSelect.value = String(button.dataset.companyStatus || 'activa');
        }
    };

    const triggers = Array.from(document.querySelectorAll('.js-sa-company-edit-open'));
    triggers.forEach((button) => {
        button.addEventListener('click', () => hydrate(button));
    });
});
</script>
