<?php

declare(strict_types=1);

require_once __DIR__ . '/init.php';

function af_plan_nullable_int(string $key): ?int
{
    $value = trim((string) ($_POST[$key] ?? ''));
    if ($value === '') return null;
    if (!ctype_digit($value)) {
        throw new InvalidArgumentException('Los límites deben ser números enteros mayores que cero o quedar vacíos para uso ilimitado.');
    }

    $number = (int) $value;
    return $number > 0 ? $number : null;
}

function af_plan_nullable_money(string $key): ?float
{
    $value = trim((string) ($_POST[$key] ?? ''));
    if ($value === '') return null;
    if (!is_numeric($value)) {
        throw new InvalidArgumentException('Los precios deben contener un importe válido.');
    }
    $amount = round((float) $value, 2);
    return $amount > 0 ? $amount : null;
}

function af_plan_is_name_protected(string $name): bool
{
    return in_array($name, ['Superadmin', 'Plan Propio'], true);
}

function af_plan_is_protected_record(array $plan): bool
{
    return in_array((int) ($plan['id'] ?? 0), [9, 10], true)
        || af_plan_is_name_protected((string) ($plan['nombre_plan'] ?? ''));
}

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

    try {
        if ($action === 'toggle_status') {
            $id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT) ?: 0;
            if ($id <= 0) throw new InvalidArgumentException('El plan seleccionado no es válido.');

            $stmt = $pdo->prepare(
                'SELECT id, nombre_plan, visible_publico, activo, permite_mensual, permite_anual, precio_mensual, precio_anual
                 FROM planes WHERE id = ? LIMIT 1'
            );
            $stmt->execute([$id]);
            $plan = $stmt->fetch(PDO::FETCH_ASSOC);
            if (!$plan) throw new RuntimeException('El plan ya no existe.');

            $newStatus = (int) ($plan['activo'] ?? 0) === 1 ? 0 : 1;
            $isFree = mb_strtolower((string) ($plan['nombre_plan'] ?? ''), 'UTF-8') === 'gratis';
            $isPublic = (int) ($plan['visible_publico'] ?? 0) === 1;
            if ($newStatus === 1 && $isPublic && !$isFree && !af_plan_is_protected_record($plan)) {
                $hasMonthly = (int) ($plan['permite_mensual'] ?? 0) === 1 && (float) ($plan['precio_mensual'] ?? 0) > 0;
                $hasAnnual = (int) ($plan['permite_anual'] ?? 0) === 1 && (float) ($plan['precio_anual'] ?? 0) > 0;
                if (!$hasMonthly && !$hasAnnual) {
                    throw new RuntimeException('Antes de activar un plan público, habilita una modalidad y registra su precio.');
                }
            }

            $pdo->prepare('UPDATE planes SET activo = ?, fecha_actualizacion = NOW() WHERE id = ?')
                ->execute([$newStatus, $id]);
            $_SESSION['flash_message'] = [
                'type' => 'success',
                'text' => $newStatus === 1 ? 'Plan activado correctamente.' : 'Plan desactivado correctamente.',
            ];
            header('Location: gestionar_planes.php');
            exit;
        }

        if ($action === 'delete_plan') {
            $id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT) ?: 0;
            if ($id <= 0) throw new InvalidArgumentException('El plan seleccionado no es válido.');

            $stmt = $pdo->prepare('SELECT id, nombre_plan, es_interno FROM planes WHERE id = ? LIMIT 1');
            $stmt->execute([$id]);
            $plan = $stmt->fetch(PDO::FETCH_ASSOC);
            if (!$plan) throw new RuntimeException('El plan ya no existe.');
            if (af_plan_is_protected_record($plan)) {
                throw new RuntimeException('Este plan es interno o protegido y no puede eliminarse.');
            }

            $usage = $pdo->prepare(
                'SELECT
                    (SELECT COUNT(*) FROM suscripciones WHERE id_plan = ?) AS suscripciones,
                    (SELECT COUNT(*) FROM renovaciones_credito WHERE id_plan = ?) AS renovaciones,
                    (SELECT COUNT(*) FROM usuarios WHERE id_plan = ?) AS usuarios,
                    (SELECT COUNT(*) FROM planes WHERE id_plan_subadmin_default = ?) AS planes_dependientes'
            );
            $usage->execute([$id, $id, $id, $id]);
            $dependencies = $usage->fetch(PDO::FETCH_ASSOC) ?: [];
            $dependencyTotal = array_sum(array_map('intval', $dependencies));
            if ($dependencyTotal > 0) {
                throw new RuntimeException(
                    'El plan tiene registros vinculados. Reasigna primero sus suscripciones o usuarios y vuelve a intentar; mientras tanto puedes editarlo o desactivarlo.'
                );
            }

            $pdo->prepare('DELETE FROM planes WHERE id = ?')->execute([$id]);
            $_SESSION['flash_message'] = ['type' => 'success', 'text' => 'Plan eliminado correctamente.'];
            header('Location: gestionar_planes.php');
            exit;
        }

        $id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT) ?: null;
        $name = trim((string) ($_POST['nombre_plan'] ?? ''));
        $description = trim((string) ($_POST['descripcion'] ?? ''));
        $monthlyEnabled = (int) ($_POST['permite_mensual'] ?? 0) === 1;
        $annualEnabled = (int) ($_POST['permite_anual'] ?? 0) === 1;
        $monthlyPrice = af_plan_nullable_money('precio_mensual');
        $annualPrice = af_plan_nullable_money('precio_anual');
        $visible = (int) ($_POST['visible_publico'] ?? 0) === 1 ? 1 : 0;
        $active = (int) ($_POST['activo'] ?? 1) === 1 ? 1 : 0;
        $publicOrder = filter_input(INPUT_POST, 'orden_publico', FILTER_VALIDATE_INT);
        $publicOrder = $publicOrder !== false && $publicOrder !== null ? max(0, min(999, (int) $publicOrder)) : 100;

        $limits = [
            'limite_buzones' => af_plan_nullable_int('limite_buzones'),
            'limite_dominios' => af_plan_nullable_int('limite_dominios'),
            'limite_cuentas' => af_plan_nullable_int('limite_cuentas'),
            'limite_usuarios' => af_plan_nullable_int('limite_usuarios'),
            'limite_consultas' => af_plan_nullable_int('limite_consultas'),
        ];
        $trialDays = af_plan_nullable_int('duracion_prueba_dias');

        if ($name === '') throw new InvalidArgumentException('Escribe un nombre para el plan.');
        if (mb_strlen($name, 'UTF-8') > 100) throw new InvalidArgumentException('El nombre del plan es demasiado largo.');
        if (mb_strlen($description, 'UTF-8') > 1000) throw new InvalidArgumentException('La descripción no debe superar 1000 caracteres.');

        $existing = null;
        if ($id !== null) {
            $check = $pdo->prepare('SELECT * FROM planes WHERE id = ? LIMIT 1');
            $check->execute([$id]);
            $existing = $check->fetch(PDO::FETCH_ASSOC);
            if (!$existing) throw new RuntimeException('El plan que intentas editar ya no existe.');

            if (af_plan_is_protected_record($existing) && $name !== (string) $existing['nombre_plan']) {
                throw new RuntimeException('El nombre de este plan está protegido y no puede modificarse.');
            }
        }

        $isProtected = $existing ? af_plan_is_protected_record($existing) : false;
        if ($isProtected) {
            $visible = 0;
            // Los planes propietarios siguen ocultos y protegidos, pero su estado sí puede administrarse.
            $publicOrder = (int) ($existing['orden_publico'] ?? 990);
        }

        $isFree = mb_strtolower($name, 'UTF-8') === 'gratis';
        if (!$isFree && !$isProtected && $active === 1 && $visible === 1) {
            if (!$monthlyEnabled && !$annualEnabled) {
                throw new InvalidArgumentException('Habilita al menos una modalidad: mensual o anual.');
            }
            if ($monthlyEnabled && ($monthlyPrice === null || $monthlyPrice <= 0)) {
                throw new InvalidArgumentException('Ingresa el precio mensual del plan.');
            }
            if ($annualEnabled && ($annualPrice === null || $annualPrice <= 0)) {
                throw new InvalidArgumentException('Ingresa el precio anual del plan.');
            }
        }

        if (!$monthlyEnabled) $monthlyPrice = null;
        if (!$annualEnabled) $annualPrice = null;
        if ($isFree) {
            $monthlyEnabled = false;
            $annualEnabled = false;
            $monthlyPrice = null;
            $annualPrice = null;
        } elseif ($isProtected && $existing) {
            // Conserva la configuración histórica de los planes internos protegidos.
            $monthlyEnabled = (int) ($existing['permite_mensual'] ?? 0) === 1;
            $annualEnabled = (int) ($existing['permite_anual'] ?? 0) === 1;
            $monthlyPrice = $existing['precio_mensual'] !== null ? (float) $existing['precio_mensual'] : null;
            $annualPrice = $existing['precio_anual'] !== null ? (float) $existing['precio_anual'] : null;
        }

        $duplicateSql = 'SELECT COUNT(*) FROM planes WHERE nombre_plan = ?';
        $duplicateParams = [$name];
        if ($id !== null) {
            $duplicateSql .= ' AND id <> ?';
            $duplicateParams[] = $id;
        }
        $duplicate = $pdo->prepare($duplicateSql);
        $duplicate->execute($duplicateParams);
        if ((int) $duplicate->fetchColumn() > 0) {
            throw new RuntimeException('Ya existe otro plan con ese nombre.');
        }

        $params = [
            $name,
            $description !== '' ? $description : null,
            $monthlyPrice,
            $annualPrice,
            $monthlyEnabled ? 1 : 0,
            $annualEnabled ? 1 : 0,
            $limits['limite_buzones'],
            $limits['limite_dominios'],
            $limits['limite_cuentas'],
            $limits['limite_usuarios'],
            $limits['limite_consultas'],
            $trialDays,
            $visible,
            $active,
            $publicOrder,
            $isProtected ? 1 : 0,
        ];

        if ($id !== null) {
            $sql = 'UPDATE planes SET
                        nombre_plan = ?, descripcion = ?, precio_mensual = ?, precio_anual = ?,
                        permite_mensual = ?, permite_anual = ?, limite_buzones = ?, limite_dominios = ?,
                        limite_cuentas = ?, limite_usuarios = ?, limite_consultas = ?, duracion_prueba_dias = ?,
                        visible_publico = ?, activo = ?, orden_publico = ?, es_interno = ?, fecha_actualizacion = NOW()
                    WHERE id = ?';
            $params[] = $id;
            $pdo->prepare($sql)->execute($params);
            $message = 'Plan actualizado correctamente.';
        } else {
            $sql = 'INSERT INTO planes
                        (nombre_plan, descripcion, precio_mensual, precio_anual, permite_mensual, permite_anual,
                         limite_buzones, limite_dominios, limite_cuentas, limite_usuarios, limite_consultas,
                         duracion_prueba_dias, visible_publico, activo, orden_publico, es_interno)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
            $pdo->prepare($sql)->execute($params);
            $message = 'Plan creado correctamente.';
        }

        $_SESSION['flash_message'] = ['type' => 'success', 'text' => $message];
    } catch (Throwable $e) {
        $_SESSION['flash_message'] = ['type' => 'error', 'text' => $e->getMessage()];
    }

    header('Location: gestionar_planes.php');
    exit;
}

$titulo_pagina = 'Gestionar Planes';
require_once __DIR__ . '/admin_header.php';

try {
    $planes = $pdo->query(
        'SELECT * FROM planes
         ORDER BY es_interno DESC, visible_publico DESC, orden_publico ASC, nombre_plan ASC, id ASC'
    )->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $planes = [];
    $error_message_db = 'No se pudieron cargar los planes: ' . $e->getMessage();
}

$totalPlanes = count($planes);
$publicPlans = count(array_filter($planes, static fn(array $p): bool => (int) ($p['visible_publico'] ?? 0) === 1 && (int) ($p['activo'] ?? 0) === 1));
$monthlyPlans = count(array_filter($planes, static fn(array $p): bool => (int) ($p['permite_mensual'] ?? 0) === 1));
$annualPlans = count(array_filter($planes, static fn(array $p): bool => (int) ($p['permite_anual'] ?? 0) === 1));
?>
<link rel="stylesheet" href="../assets/css/superadmin-commercial.css?v=1.3.0">
<div class="super-commercial-ui px-4 md:px-6 pb-8">
    <div class="sc-shell">
        <?php if (!empty($error_message_db)): ?>
            <div class="sc-alert error"><i class="fas fa-database"></i><div><strong>Error de base de datos</strong><br><?= htmlspecialchars($error_message_db) ?></div></div>
        <?php else: ?>
            <section class="sc-card sc-hero">
                <div class="sc-hero-main">
                    <span class="sc-icon"><i class="fas fa-layer-group"></i></span>
                    <div>
                        <div class="sc-eyebrow">Oferta comercial</div>
                        <h1 class="sc-title">Planes</h1>
                        <p class="sc-copy">Cada plan puede ofrecer modalidad mensual, anual o ambas. Los planes privados pueden permanecer activos sin precio público; Superadmin y Plan Propio siguen protegidos contra eliminación.</p>
                    </div>
                </div>
                <div class="sc-actions"><button type="button" id="openModalBtn" class="sc-btn-primary"><i class="fas fa-plus"></i> Nuevo plan</button></div>
            </section>

            <section class="sc-stats">
                <article class="sc-stat"><span class="sc-stat-icon"><i class="fas fa-layer-group"></i></span><div><div class="sc-stat-label">Planes</div><div class="sc-stat-value"><?= $totalPlanes ?></div><div class="sc-stat-note">Catálogo completo</div></div></article>
                <article class="sc-stat"><span class="sc-stat-icon green"><i class="fas fa-eye"></i></span><div><div class="sc-stat-label">Públicos activos</div><div class="sc-stat-value"><?= $publicPlans ?></div><div class="sc-stat-note">Visibles en la portada</div></div></article>
                <article class="sc-stat"><span class="sc-stat-icon blue"><i class="fas fa-calendar-day"></i></span><div><div class="sc-stat-label">Mensuales</div><div class="sc-stat-value"><?= $monthlyPlans ?></div><div class="sc-stat-note">Modalidad habilitada</div></div></article>
                <article class="sc-stat"><span class="sc-stat-icon amber"><i class="fas fa-calendar-check"></i></span><div><div class="sc-stat-label">Anuales</div><div class="sc-stat-value"><?= $annualPlans ?></div><div class="sc-stat-note">Modalidad habilitada</div></div></article>
            </section>

            <section class="sc-card sc-records">
                <div class="sc-records-head"><span class="sc-section-icon"><i class="fas fa-list"></i></span><div><h2 class="sc-records-title">Registros de planes</h2><p class="sc-records-copy">Administra modalidades, precios, límites, orden y publicación.</p></div></div>
                <div class="sc-toolbar plan-toolbar">
                    <div class="plan-toolbar-left">
                        <div class="plan-search-filter"><label class="sc-label" for="search-input-planes"><i class="fas fa-search"></i>Buscar</label><div class="sc-search"><i class="fas fa-search"></i><input type="search" id="search-input-planes" class="sc-field" placeholder="Buscar por nombre o descripción"></div></div>
                        <div class="plan-visibility-filter"><label class="sc-label" for="planVisibility"><i class="fas fa-eye"></i>Visibilidad</label><select id="planVisibility" class="sc-field"><option value="">Todos</option><option value="Público">Públicos</option><option value="Privado">No públicos</option></select></div>
                    </div>
                    <div class="plan-toolbar-right">
                        <div class="plan-length-filter"><label class="sc-label" for="planPageLength"><i class="fas fa-list-ol"></i>Mostrar</label><select id="planPageLength" class="sc-field"><option value="100" selected>100 registros</option><option value="200">200 registros</option><option value="400">400 registros</option><option value="-1">Todos</option></select></div>
                        <div class="sc-filter-actions"><button type="button" id="clearPlanFilters" class="sc-btn-secondary"><i class="fas fa-eraser"></i> Limpiar</button></div>
                    </div>
                </div>
                <div class="sc-summary"><span><?= $totalPlanes ?> planes registrados</span><span id="planInfo">Mostrando 0–0 de 0 registros</span></div>
                <div class="sc-table-wrap">
                    <table id="tablaPlanes">
                        <thead><tr><th>Plan</th><th>Descripción</th><th>Modalidades y precios</th><th>Límites</th><th>Estado</th><th>Visibilidad</th><th class="text-right">Acciones</th></tr></thead>
                        <tbody>
                        <?php foreach ($planes as $plan): ?>
                            <?php
                                $isInternal = (int) ($plan['es_interno'] ?? 0) === 1;
                                $protected = af_plan_is_protected_record($plan);
                            ?>
                            <tr>
                                <td><strong><?= htmlspecialchars((string) $plan['nombre_plan']) ?></strong><div class="sc-muted"><?= $protected ? 'Plan interno protegido' : ((int) ($plan['es_interno'] ?? 0) === 1 ? 'Plan privado editable' : 'Orden público: ' . (int) ($plan['orden_publico'] ?? 100)) ?></div></td>
                                <td title="<?= htmlspecialchars((string) ($plan['descripcion'] ?? '')) ?>"><span class="sc-plan-description"><?= htmlspecialchars((string) ($plan['descripcion'] ?: 'Sin descripción')) ?></span></td>
                                <td>
                                    <?php if ((int) ($plan['permite_mensual'] ?? 0) === 1): ?><div><span class="sc-pill blue">Mensual</span> <strong>S/ <?= number_format((float) $plan['precio_mensual'], 2) ?></strong></div><?php endif; ?>
                                    <?php if ((int) ($plan['permite_anual'] ?? 0) === 1): ?><div class="sc-price-second"><span class="sc-pill amber">Anual</span> <strong>S/ <?= number_format((float) $plan['precio_anual'], 2) ?></strong></div><?php endif; ?>
                                    <?php if ((int) ($plan['permite_mensual'] ?? 0) !== 1 && (int) ($plan['permite_anual'] ?? 0) !== 1): ?><span class="sc-pill gray">Sin cobro directo</span><?php endif; ?>
                                </td>
                                <td><div>Buzones: <strong><?= $plan['limite_buzones'] === null ? 'Ilimitado' : (int) $plan['limite_buzones'] ?></strong> · Dominios: <strong><?= $plan['limite_dominios'] === null ? 'Ilimitado' : (int) $plan['limite_dominios'] ?></strong></div><div class="sc-muted">Cuentas de streaming: <?= $plan['limite_cuentas'] === null ? 'Ilimitado' : (int) $plan['limite_cuentas'] ?> · Clientes/usuarios: <?= $plan['limite_usuarios'] === null ? 'Ilimitado' : (int) $plan['limite_usuarios'] ?> · Consultas públicas/mes: <?= $plan['limite_consultas'] === null ? 'Ilimitado' : (int) $plan['limite_consultas'] ?></div></td>
                                <td><span class="sc-pill <?= (int) ($plan['activo'] ?? 0) === 1 ? 'green' : 'red' ?>"><?= (int) ($plan['activo'] ?? 0) === 1 ? 'Activo' : 'Inactivo' ?></span></td>
                                <td><span class="sc-pill <?= (int) ($plan['visible_publico'] ?? 0) === 1 ? 'green' : 'gray' ?>"><?= (int) ($plan['visible_publico'] ?? 0) === 1 ? 'Público' : 'Privado' ?></span></td>
                                <td class="sc-actions-cell">
                                    <button type="button" class="sc-action <?= (int) ($plan['activo'] ?? 0) === 1 ? 'warning' : 'success' ?> toggle-plan-btn" data-id="<?= (int) $plan['id'] ?>" data-name="<?= htmlspecialchars((string) $plan['nombre_plan'], ENT_QUOTES) ?>" data-active="<?= (int) ($plan['activo'] ?? 0) ?>" title="<?= (int) ($plan['activo'] ?? 0) === 1 ? 'Desactivar' : 'Activar' ?>"><i class="fas <?= (int) ($plan['activo'] ?? 0) === 1 ? 'fa-pause' : 'fa-play' ?>"></i></button>
                                    <button type="button" class="sc-action edit edit-btn" data-plan='<?= htmlspecialchars(json_encode($plan, JSON_HEX_APOS | JSON_HEX_QUOT), ENT_QUOTES, 'UTF-8') ?>' title="Editar"><i class="fas fa-pen"></i></button>
                                    <?php if (!$protected): ?><button type="button" class="sc-action delete delete-plan-btn" data-id="<?= (int) $plan['id'] ?>" data-name="<?= htmlspecialchars((string) $plan['nombre_plan'], ENT_QUOTES) ?>" title="Eliminar"><i class="fas fa-trash"></i></button><?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <div class="sc-table-foot"><span>Para conservar el historial, desactiva un plan usado en lugar de eliminarlo.</span><div id="planPagination" class="sc-pagination"></div></div>
            </section>
        <?php endif; ?>
    </div>
</div>

<div id="planModal" class="super-commercial-ui sc-modal fixed inset-0 hidden items-center justify-center z-[2147483000] px-3 py-4">
    <div class="sc-modal-shell wide">
        <div class="sc-modal-head"><div class="sc-modal-main"><span class="sc-modal-icon"><i class="fas fa-layer-group"></i></span><div><div class="sc-modal-kicker">Planes · configuración</div><div class="sc-modal-title" id="modalTitle">Nuevo plan</div><p class="sc-modal-copy">Define las modalidades disponibles y sus precios sin duplicar el mismo plan.</p></div></div><button type="button" id="closeModalBtn" class="sc-modal-close"><i class="fas fa-times"></i></button></div>
        <form id="planForm" method="POST" action="gestionar_planes.php" class="contents">
            <?= Security::csrfField() ?>
            <input type="hidden" name="action" value="save_plan">
            <input type="hidden" name="id" id="planId">
            <div class="sc-modal-body">
                <div class="sc-note"><i class="fas fa-circle-info"></i><span>Deja un límite vacío para uso ilimitado. Un plan puede ofrecer mensual, anual o ambas modalidades.</span></div>
                <div class="sc-grid-3">
                    <div><label class="sc-label" for="nombre_plan"><i class="fas fa-tag"></i>Nombre *</label><input type="text" name="nombre_plan" id="nombre_plan" required maxlength="100" class="sc-field" placeholder="Ejemplo: Lite"></div>
                    <div><label class="sc-label" for="activo"><i class="fas fa-power-off"></i>Estado *</label><select name="activo" id="activo" class="sc-field"><option value="1">Activo</option><option value="0">Inactivo</option></select></div>
                    <div><label class="sc-label" for="visible_publico"><i class="fas fa-eye"></i>Visible en portada *</label><select name="visible_publico" id="visible_publico" class="sc-field"><option value="1">Sí</option><option value="0">No</option></select></div>
                </div>
                <div><label class="sc-label" for="descripcion"><i class="fas fa-align-left"></i>Descripción comercial</label><textarea name="descripcion" id="descripcion" rows="3" maxlength="1000" class="sc-textarea" placeholder="Resume para quién es el plan y qué capacidad ofrece."></textarea></div>

                <div class="sc-cycle-editor">
                    <div class="sc-cycle-card">
                        <div class="sc-cycle-head"><span><i class="fas fa-calendar-day"></i></span><div><strong>Modalidad mensual</strong><small>Cobro y renovación por un mes calendario.</small></div></div>
                        <div class="sc-cycle-fields">
                            <div><label class="sc-label" for="permite_mensual">Disponible</label><select name="permite_mensual" id="permite_mensual" class="sc-field"><option value="1">Sí</option><option value="0">No</option></select></div>
                            <div><label class="sc-label" for="precio_mensual">Precio mensual (S/)</label><input type="number" min="0" step="0.01" name="precio_mensual" id="precio_mensual" class="sc-field" placeholder="Ej.: 20.00"></div>
                        </div>
                    </div>
                    <div class="sc-cycle-card">
                        <div class="sc-cycle-head"><span><i class="fas fa-calendar-check"></i></span><div><strong>Modalidad anual</strong><small>Cobro y renovación por doce meses calendario.</small></div></div>
                        <div class="sc-cycle-fields">
                            <div><label class="sc-label" for="permite_anual">Disponible</label><select name="permite_anual" id="permite_anual" class="sc-field"><option value="1">Sí</option><option value="0">No</option></select></div>
                            <div><label class="sc-label" for="precio_anual">Precio anual (S/)</label><input type="number" min="0" step="0.01" name="precio_anual" id="precio_anual" class="sc-field" placeholder="Ej.: 200.00"></div>
                        </div>
                    </div>
                </div>

                <div class="sc-divider"></div>
                <div class="sc-resource-note"><i class="fas fa-circle-question"></i><div><strong>¿Qué controla cada límite?</strong><span><b>Cuentas de streaming</b> son los accesos/correos que el Admin registra en el módulo Cuentas. <b>Consultas públicas/mes</b> son las búsquedas realizadas con código desde la consulta pública. Campo vacío = ilimitado.</span></div></div>
                <div class="sc-grid-3 sc-resource-grid">
                    <div><label class="sc-label" for="limite_buzones"><i class="fas fa-inbox"></i>Buzones IMAP</label><input type="number" min="1" name="limite_buzones" id="limite_buzones" class="sc-field" placeholder="Ilimitado"><div class="sc-help">Buzones de correo configurables.</div></div>
                    <div><label class="sc-label" for="limite_dominios"><i class="fas fa-at"></i>Dominios</label><input type="number" min="1" name="limite_dominios" id="limite_dominios" class="sc-field" placeholder="Ilimitado"><div class="sc-help">Dominios que puede registrar el Admin.</div></div>
                    <div><label class="sc-label" for="limite_cuentas"><i class="fas fa-envelope-open-text"></i>Cuentas de streaming</label><input type="number" min="1" name="limite_cuentas" id="limite_cuentas" class="sc-field" placeholder="Ilimitado"><div class="sc-help">Cantidad de cuentas/accesos que puede registrar.</div></div>
                    <div><label class="sc-label" for="limite_usuarios"><i class="fas fa-users"></i>Clientes y usuarios</label><input type="number" min="1" name="limite_usuarios" id="limite_usuarios" class="sc-field" placeholder="Ilimitado"><div class="sc-help">Clientes o revendedores administrados.</div></div>
                    <div><label class="sc-label" for="limite_consultas"><i class="fas fa-search"></i>Consultas públicas / mes</label><input type="number" min="1" name="limite_consultas" id="limite_consultas" class="sc-field" placeholder="Ilimitado"><div class="sc-help">Búsquedas por código en la consulta pública.</div></div>
                    <div><label class="sc-label" for="duracion_prueba_dias"><i class="fas fa-flask"></i>Días de prueba</label><input type="number" min="1" name="duracion_prueba_dias" id="duracion_prueba_dias" class="sc-field" placeholder="Sin prueba"><div class="sc-help">Solo aplica cuando el plan ofrece prueba.</div></div>
                </div>
                <div><label class="sc-label" for="orden_publico"><i class="fas fa-arrow-down-1-9"></i>Orden en la portada</label><input type="number" min="0" max="999" name="orden_publico" id="orden_publico" class="sc-field" value="100"><div class="sc-help">Los números menores aparecen primero.</div></div>
            </div>
            <div class="sc-modal-foot"><button type="button" id="cancelModalBtn" class="sc-btn-secondary">Cancelar</button><button type="submit" class="sc-btn-primary"><i class="fas fa-save"></i> Guardar plan</button></div>
        </form>
    </div>
</div>

<form id="togglePlanForm" method="POST" action="gestionar_planes.php" hidden>
    <?= Security::csrfField() ?>
    <input type="hidden" name="action" value="toggle_status">
    <input type="hidden" name="id" id="togglePlanId">
</form>

<form id="deletePlanForm" method="POST" action="gestionar_planes.php" hidden>
    <?= Security::csrfField() ?>
    <input type="hidden" name="action" value="delete_plan">
    <input type="hidden" name="id" id="deletePlanId">
</form>

<style>
.super-commercial-ui .sc-plan-description{display:block;max-width:320px;white-space:normal;line-height:1.45}.super-commercial-ui .sc-price-second{margin-top:7px}.super-commercial-ui .sc-cycle-editor{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}.super-commercial-ui .sc-cycle-card{padding:14px;border:1px solid #dce5ef;border-radius:13px;background:#f8fafc;min-width:0}.super-commercial-ui .sc-cycle-head{display:flex;align-items:center;gap:10px;margin-bottom:12px}.super-commercial-ui .sc-cycle-head>span{width:38px;height:38px;border-radius:11px;display:grid;place-items:center;background:#feecee;color:#dc2626;flex:0 0 auto}.super-commercial-ui .sc-cycle-head strong,.super-commercial-ui .sc-cycle-head small{display:block}.super-commercial-ui .sc-cycle-head strong{font-size:13px;color:#0f172a}.super-commercial-ui .sc-cycle-head small{margin-top:3px;font-size:10px;color:#64748b}.super-commercial-ui .sc-cycle-fields{display:grid;grid-template-columns:minmax(112px,.78fr) minmax(150px,1.22fr);gap:10px;align-items:end}.super-commercial-ui .sc-cycle-fields>div{min-width:0}.super-commercial-ui .sc-cycle-fields .sc-label{min-height:18px;display:flex;align-items:flex-end;white-space:nowrap}.super-commercial-ui .sc-cycle-fields .af-optional,.super-commercial-ui .sc-resource-grid .af-optional{display:none!important}.super-commercial-ui .sc-resource-note{display:flex;gap:10px;align-items:flex-start;padding:11px 13px;margin-bottom:12px;border:1px solid #bfdbfe;border-radius:12px;background:#eff6ff;color:#1e3a8a}.super-commercial-ui .sc-resource-note>i{margin-top:2px}.super-commercial-ui .sc-resource-note strong,.super-commercial-ui .sc-resource-note span{display:block}.super-commercial-ui .sc-resource-note strong{font-size:11px;margin-bottom:3px}.super-commercial-ui .sc-resource-note span{font-size:10px;line-height:1.45}.super-commercial-ui .sc-resource-grid>div{min-width:0}.super-commercial-ui .sc-resource-grid .sc-label{min-height:20px;align-items:flex-end}.super-commercial-ui .sc-help{margin-top:5px;color:#64748b;font-size:10px;line-height:1.35}.super-commercial-ui .sc-action.warning{background:#fff7ed;color:#c2410c;border-color:#fed7aa}.super-commercial-ui .sc-action.success{background:#ecfdf5;color:#047857;border-color:#a7f3d0}@media(max-width:900px){.super-commercial-ui .sc-cycle-editor{grid-template-columns:1fr}}@media(max-width:520px){.super-commercial-ui .sc-cycle-fields{grid-template-columns:1fr}.super-commercial-ui .sc-cycle-fields .sc-label{white-space:normal}}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(function(){
    const table=$('#tablaPlanes').DataTable({dom:'t',language:{url:'//cdn.datatables.net/plug-ins/1.11.3/i18n/es_es.json'},pageLength:100,lengthMenu:[[100,200,400,-1],[100,200,400,'Todos']],order:[],autoWidth:false,columnDefs:[{orderable:false,targets:[6]}]});
    function render(){const i=table.page.info(),t=i.recordsDisplay||0,s=t?i.start+1:0,e=t?i.end:0,p=i.pages||0,c=i.page||0;$('#planInfo').text(`Mostrando ${s}–${e} de ${t} registros`);let h=`<button class="sc-page" data-page="prev" ${c===0||!p?'disabled':''}><i class="fas fa-chevron-left"></i></button>`;if(!p)h+='<button class="sc-page active" disabled>1</button>';else for(let n=0;n<p;n++){if(p<=5||n===0||n===p-1||Math.abs(n-c)<=1)h+=`<button class="sc-page ${n===c?'active':''}" data-page="${n}">${n+1}</button>`;else if(n===c-2||n===c+2)h+='<span>…</span>';}h+=`<button class="sc-page" data-page="next" ${c>=p-1||!p?'disabled':''}><i class="fas fa-chevron-right"></i></button>`;$('#planPagination').html(h)}
    $('#search-input-planes').on('input',function(){table.search(this.value).draw()});
    $('#planVisibility').on('change',function(){table.column(5).search(this.value?`^${this.value}$`:'',true,false).draw()});
    $('#planPageLength').on('change',function(){table.page.len(parseInt(this.value,10)).draw()});
    $('#clearPlanFilters').on('click',function(){$('#search-input-planes,#planVisibility').val('');table.search('').columns().search('').draw()});
    table.on('draw page.dt search.dt length.dt',render);render();
    $('#planPagination').on('click','.sc-page',function(){if(this.disabled)return;const p=$(this).data('page');if(p==='prev')table.page('previous').draw('page');else if(p==='next')table.page('next').draw('page');else table.page(parseInt(p,10)).draw('page')});

    <?php if (isset($_SESSION['flash_message'])): ?>Swal.fire({icon:<?= json_encode($_SESSION['flash_message']['type']) ?>,title:<?= json_encode($_SESSION['flash_message']['type']==='success'?'Operación completada':'No se pudo completar') ?>,text:<?= json_encode($_SESSION['flash_message']['text']) ?>,confirmButtonColor:'#dc2626'});<?php unset($_SESSION['flash_message']); endif; ?>

    const modal=$('#planModal'),form=$('#planForm');
    const protectedNames=['Superadmin','Plan Propio'];
    function setCycleState(){const locked=Boolean($('#planId').val())&&protectedNames.includes($('#nombre_plan').val());[['#permite_mensual','#precio_mensual'],['#permite_anual','#precio_anual']].forEach(([toggle,input])=>{const enabled=$(toggle).val()==='1';$(input).prop('disabled',locked||!enabled).prop('required',!locked&&enabled)})}
    function close(){$('body').removeClass('overflow-hidden sc-commercial-modal-open');modal.addClass('hidden').removeClass('flex')}
    function open(edit=false,data={}){form[0].reset();$('#planId').val('');$('#modalTitle').text(edit?'Editar plan':'Nuevo plan');$('#nombre_plan').prop('readonly',false);$('#activo,#visible_publico,#permite_mensual,#permite_anual').val('1');$('#orden_publico').val('100');if(edit){Object.keys(data).forEach(key=>{const el=$('#'+key);if(el.length)el.val(data[key]===null?'':String(data[key]))});$('#planId').val(data.id);if(protectedNames.includes(data.nombre_plan))$('#nombre_plan').prop('readonly',true);if(protectedNames.includes(data.nombre_plan)){$('#visible_publico').val('0').prop('disabled',true);$('#permite_mensual,#permite_anual,#precio_mensual,#precio_anual,#orden_publico').prop('disabled',true);$('#activo').prop('disabled',false)}else{$('#visible_publico,#activo,#permite_mensual,#permite_anual,#precio_mensual,#precio_anual,#orden_publico').prop('disabled',false)}}else{$('#visible_publico,#activo,#permite_mensual,#permite_anual,#precio_mensual,#precio_anual,#orden_publico').prop('disabled',false)}setCycleState();$('body').addClass('overflow-hidden sc-commercial-modal-open');modal.removeClass('hidden').addClass('flex');setTimeout(()=>$('#nombre_plan').trigger('focus'),60)}
    $('#permite_mensual,#permite_anual').on('change',setCycleState);
    $('#openModalBtn').on('click',()=>open(false));
    $('#tablaPlanes').on('click','.edit-btn',function(){open(true,$(this).data('plan'))});
    $('#closeModalBtn,#cancelModalBtn').on('click',close);modal.on('click',function(e){if(e.target===this)close()});$(document).on('keydown.planModal',function(e){if(e.key==='Escape')close()});
    $('#tablaPlanes').on('click','.toggle-plan-btn',function(){const id=$(this).data('id'),name=$(this).data('name'),active=Number($(this).data('active'))===1;Swal.fire({title:active?'¿Desactivar plan?':'¿Activar plan?',html:`El plan <strong>${name}</strong> quedará ${active?'inactivo':'activo'}.`,icon:'question',showCancelButton:true,confirmButtonText:active?'Sí, desactivar':'Sí, activar',cancelButtonText:'Cancelar',confirmButtonColor:active?'#c2410c':'#047857'}).then(r=>{if(r.isConfirmed){$('#togglePlanId').val(id);$('#togglePlanForm')[0].submit()}})});
    $('#tablaPlanes').on('click','.delete-plan-btn',function(){const id=$(this).data('id'),name=$(this).data('name');Swal.fire({title:'¿Eliminar plan?',html:`Se eliminará <strong>${name}</strong> únicamente si no tiene suscripciones registradas.`,icon:'warning',showCancelButton:true,confirmButtonText:'Sí, eliminar',cancelButtonText:'Cancelar',confirmButtonColor:'#dc2626'}).then(r=>{if(r.isConfirmed){$('#deletePlanId').val(id);$('#deletePlanForm')[0].submit()}})});
});
</script>
<?php require_once __DIR__ . '/admin_footer.php'; ?>
