<?php
/**
 * Editar Plano - Super Admin
 */
require_once __DIR__ . '/../../../includes/config.php';

if (!isSuperAdmin()) {
    header('Location: /pages/login.php');
    exit;
}

$superAdmin = getSuperAdmin();
$pdo = getDB();

$planId = $_GET['id'] ?? null;
$isNew = empty($planId);

// Buscar plano existente
$plan = null;
if (!$isNew) {
    $stmt = $pdo->prepare("SELECT * FROM plans WHERE id = ?");
    $stmt->execute([$planId]);
    $plan = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$plan) {
        $_SESSION['flash_error'] = 'Plano não encontrado';
        header('Location: plans.php');
        exit;
    }
}

// Processar formulário
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $name = trim($_POST['name'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $priceMonthly = floatval($_POST['price_monthly'] ?? 0);
        $priceYearly = floatval($_POST['price_yearly'] ?? 0);
        $maxProducts = !empty($_POST['max_products']) ? intval($_POST['max_products']) : null;
        $maxOrders = !empty($_POST['max_orders']) ? intval($_POST['max_orders']) : null;
        $maxStaff = !empty($_POST['max_staff']) ? intval($_POST['max_staff']) : null;
        $features = trim($_POST['features'] ?? '');
        $whatsappIntegration = isset($_POST['whatsapp_integration']) ? 1 : 0;
        $customDomain = isset($_POST['custom_domain']) ? 1 : 0;
        $controlPanel = isset($_POST['control_panel']) ? 1 : 0;
        $fullReports = isset($_POST['full_reports']) ? 1 : 0;
        $dedicatedSupport = isset($_POST['dedicated_support']) ? 1 : 0;
        $isActive = isset($_POST['is_active']) ? 1 : 0;
        $isFeatured = isset($_POST['is_featured']) ? 1 : 0;
        $sortOrder = intval($_POST['sort_order'] ?? 0);
        $hasTrial = isset($_POST["has_trial"]) ? 1 : 0;
        $trialDays = intval($_POST["trial_days"] ?? 14);
        
        if (empty($name)) {
            throw new Exception('Nome é obrigatório');
        }
        
        if ($isNew) {
            $id = preg_replace('/[^a-z0-9_-]/', '', strtolower($_POST['plan_id'] ?? ''));
            if (empty($id)) {
                throw new Exception('ID do plano é obrigatório');
            }
            
            // Verificar se ID já existe
            $check = $pdo->prepare("SELECT id FROM plans WHERE id = ?");
            $check->execute([$id]);
            if ($check->fetch()) {
                throw new Exception('Já existe um plano com este ID');
            }
            
            $stmt = $pdo->prepare("
                INSERT INTO plans (id, name, description, price_monthly, price_yearly, max_products, max_orders_per_month, max_staff_users, whatsapp_integration, custom_domain, control_panel, full_reports, dedicated_support, features, is_active, is_featured, has_trial, trial_days, sort_order)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([$id, $name, $description, $priceMonthly, $priceYearly, $maxProducts, $maxOrders, $maxStaff, $whatsappIntegration, $customDomain, $controlPanel, $fullReports, $dedicatedSupport, $features, $isActive, $isFeatured, $hasTrial, $trialDays, $sortOrder]);
            
            $_SESSION['flash_success'] = 'Plano criado com sucesso!';
        } else {
            $stmt = $pdo->prepare("
                UPDATE plans SET 
                    name = ?, description = ?, price_monthly = ?, price_yearly = ?, 
                    max_products = ?, max_orders_per_month = ?, max_staff_users = ?, whatsapp_integration = ?, custom_domain = ?, control_panel = ?, full_reports = ?, dedicated_support = ?, 
                    features = ?, is_active = ?, is_featured = ?, has_trial = ?, trial_days = ?, sort_order = ?
                WHERE id = ?
            ");
            $stmt->execute([$name, $description, $priceMonthly, $priceYearly, $maxProducts, $maxOrders, $maxStaff, $whatsappIntegration, $customDomain, $controlPanel, $fullReports, $dedicatedSupport, $features, $isActive, $isFeatured, $hasTrial, $trialDays, $sortOrder, $planId]);
            
            $_SESSION['flash_success'] = 'Plano atualizado com sucesso!';
        }
        
        header('Location: plans.php');
        exit;
        
    } catch (Exception $e) {
        $_SESSION['flash_error'] = $e->getMessage();
    }
}

$pageTitle = $isNew ? 'Novo Plano' : 'Editar Plano';
$currentPage = 'plans';

include __DIR__ . '/../includes/header.php';
?>
    <div class="app-container">
        <?php include __DIR__ . '/../includes/sidebar.php'; ?>

        <main class="main-content">
            <?php include __DIR__ . '/../includes/topbar.php'; ?>

            <div class="content-area">
                <!-- Flash Messages -->
                <?php if (isset($_SESSION['flash_error'])): ?>
                <div class="alert alert-error">
                    <iconify-icon icon="solar:danger-triangle-bold"></iconify-icon>
                    <span><?= htmlspecialchars($_SESSION['flash_error']) ?></span>
                </div>
                <?php unset($_SESSION['flash_error']); endif; ?>

                <!-- Page Header -->
                <div class="page-header-edit">
                    <a href="plans.php" class="btn-back">
                        <iconify-icon icon="solar:arrow-left-bold"></iconify-icon>
                        Voltar para Planos
                    </a>
                    <div class="page-title">
                        <iconify-icon icon="solar:tag-price-bold" class="title-icon"></iconify-icon>
                        <div>
                            <h2><?= $isNew ? 'Criar Novo Plano' : 'Editar Plano' ?></h2>
                            <?php if (!$isNew): ?>
                            <span class="plan-id">ID: <?= htmlspecialchars($plan['id']) ?></span>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <form method="POST" class="edit-form">
                    <!-- Informações Básicas -->
                    <div class="panel">
                        <div class="panel-header">
                            <div class="panel-icon">
                                <iconify-icon icon="solar:document-text-bold"></iconify-icon>
                            </div>
                            <div>
                                <h3>Informações Básicas</h3>
                                <span class="panel-subtitle">Dados principais do plano</span>
                            </div>
                        </div>
                        
                        <div class="form-grid">
                            <?php if ($isNew): ?>
                            <div class="form-group">
                                <label class="form-label">
                                    <iconify-icon icon="solar:hashtag-bold"></iconify-icon>
                                    ID do Plano *
                                </label>
                                <input type="text" name="plan_id" id="planId" class="form-input" 
                                       placeholder="ex: starter, pro, enterprise" 
                                       required pattern="[a-z0-9_-]+"
                                       value="<?= htmlspecialchars($_POST['plan_id'] ?? '') ?>">
                                <span class="form-hint">
                                    <iconify-icon icon="solar:info-circle-bold"></iconify-icon>
                                    Apenas letras minúsculas, números, - e _ (não pode ser alterado depois)
                                </span>
                            </div>
                            <?php endif; ?>
                            
                            <div class="form-group">
                                <label class="form-label">
                                    <iconify-icon icon="solar:text-bold"></iconify-icon>
                                    Nome do Plano *
                                </label>
                                <input type="text" name="name" id="planName" class="form-input" 
                                       placeholder="Ex: Profissional" required
                                       value="<?= htmlspecialchars($plan['name'] ?? $_POST['name'] ?? '') ?>">
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">
                                <iconify-icon icon="solar:document-bold"></iconify-icon>
                                Descrição
                            </label>
                            <textarea name="description" class="form-input" rows="3" 
                                      placeholder="Descrição detalhada do plano e seus benefícios"><?= htmlspecialchars($plan['description'] ?? $_POST['description'] ?? '') ?></textarea>
                        </div>
                    </div>

                    <!-- Preços -->
                    <div class="panel">
                        <div class="panel-header">
                            <div class="panel-icon green">
                                <iconify-icon icon="solar:wallet-money-bold"></iconify-icon>
                            </div>
                            <div>
                                <h3>Preços</h3>
                                <span class="panel-subtitle">Configure os valores do plano</span>
                            </div>
                        </div>
                        
                        <div class="form-grid">
                            <div class="form-group">
                                <label class="form-label">
                                    <iconify-icon icon="solar:calendar-bold"></iconify-icon>
                                    Preço Mensal (R$) *
                                </label>
                                <input type="number" name="price_monthly" class="form-input" 
                                       step="0.01" min="0" required
                                       value="<?= htmlspecialchars($plan['price_monthly'] ?? $_POST['price_monthly'] ?? '0') ?>">
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">
                                    <iconify-icon icon="solar:calendar-mark-bold"></iconify-icon>
                                    Preço Anual (R$)
                                </label>
                                <input type="number" name="price_yearly" class="form-input" 
                                       step="0.01" min="0"
                                       value="<?= htmlspecialchars($plan['price_yearly'] ?? $_POST['price_yearly'] ?? '0') ?>">
                                <span class="form-hint">
                                    <iconify-icon icon="solar:info-circle-bold"></iconify-icon>
                                    Deixe 0 para não oferecer opção anual
                                </span>
                            </div>
                        </div>
                        
                        <?php 
                        $monthlyPrice = floatval($plan['price_monthly'] ?? 0);
                        $yearlyPrice = floatval($plan['price_yearly'] ?? 0);
                        $discount = 0;
                        if ($monthlyPrice > 0 && $yearlyPrice > 0) {
                            $discount = round((1 - ($yearlyPrice / ($monthlyPrice * 12))) * 100);
                        }
                        ?>
                        <?php if ($discount > 0): ?>
                        <div class="price-comparison">
                            <iconify-icon icon="solar:sale-bold"></iconify-icon>
                            <span>Desconto anual: <strong><?= $discount ?>%</strong> (economia de R$ <?= number_format(($monthlyPrice * 12) - $yearlyPrice, 2, ',', '.') ?>/ano)</span>
                        </div>
                        <?php endif; ?>
                    </div>

                    <!-- Limites -->
                    <div class="panel">
                        <div class="panel-header">
                            <div class="panel-icon blue">
                                <iconify-icon icon="solar:shield-check-bold"></iconify-icon>
                            </div>
                            <div>
                                <h3>Limites e Recursos</h3>
                                <span class="panel-subtitle">Defina os limites do plano (vazio = ilimitado)</span>
                            </div>
                        </div>
                        
                        <div class="form-grid-3">
                            <div class="form-group">
                                <label class="form-label">
                                    <iconify-icon icon="solar:box-bold"></iconify-icon>
                                    Máximo de Produtos
                                </label>
                                <input type="number" name="max_products" class="form-input" min="0"
                                       placeholder="Ilimitado"
                                       value="<?= htmlspecialchars($plan['max_products'] ?? $_POST['max_products'] ?? '') ?>">
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">
                                    <iconify-icon icon="solar:bag-4-bold"></iconify-icon>
                                    Máximo de Pedidos/Mês
                                </label>
                                <input type="number" name="max_orders" class="form-input" min="0"
                                       placeholder="Ilimitado"
                                       value="<?= htmlspecialchars($plan['max_orders_per_month'] ?? $_POST['max_orders'] ?? '') ?>">
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">
                                    <iconify-icon icon="solar:users-group-rounded-bold"></iconify-icon>
                                    Máximo de Usuários
                                </label>
                                <input type="number" name="max_staff" class="form-input" min="0"
                                       placeholder="Ilimitado"
                                       value="<?= htmlspecialchars($plan['max_staff_users'] ?? $_POST['max_staff'] ?? '') ?>">
                            </div>
                        </div>

                        <!-- Recursos do Plano -->
                        <div class="feature-toggles">
                            <label class="toggle-item">
                                <input type="checkbox" name="whatsapp_integration" <?= ($plan['whatsapp_integration'] ?? false) ? 'checked' : '' ?>>
                                <span class="toggle-switch"></span>
                                <span class="toggle-label">
                                    <iconify-icon icon="solar:chat-round-dots-bold"></iconify-icon>
                                    Integração WhatsApp
                                </span>
                            </label>
                            <label class="toggle-item">
                                <input type="checkbox" name="custom_domain" <?= ($plan['custom_domain'] ?? false) ? 'checked' : '' ?>>
                                <span class="toggle-switch"></span>
                                <span class="toggle-label">
                                    <iconify-icon icon="solar:global-bold"></iconify-icon>
                                    Domínio Personalizado
                                </span>
                            </label>
                            <label class="toggle-item">
                                <input type="checkbox" name="control_panel" <?= ($plan['control_panel'] ?? false) ? 'checked' : '' ?>>
                                <span class="toggle-switch"></span>
                                <span class="toggle-label">
                                    <iconify-icon icon="solar:monitor-bold"></iconify-icon>
                                    Painel de Controle
                                </span>
                            </label>
                            <label class="toggle-item">
                                <input type="checkbox" name="full_reports" <?= ($plan['full_reports'] ?? false) ? 'checked' : '' ?>>
                                <span class="toggle-switch"></span>
                                <span class="toggle-label">
                                    <iconify-icon icon="solar:chart-2-bold"></iconify-icon>
                                    Relatórios Completos
                                </span>
                            </label>
                            <label class="toggle-item">
                                <input type="checkbox" name="dedicated_support" <?= ($plan['dedicated_support'] ?? false) ? 'checked' : '' ?>>
                                <span class="toggle-switch"></span>
                                <span class="toggle-label">
                                    <iconify-icon icon="solar:headphones-round-bold"></iconify-icon>
                                    Suporte Dedicado
                                </span>
                            </label>
                        </div>
                    </div>

                    <!-- Recursos Adicionais -->
                    <div class="panel">
                        <div class="panel-header">
                            <div class="panel-icon purple">
                                <iconify-icon icon="solar:code-bold"></iconify-icon>
                            </div>
                            <div>
                                <h3>Recursos Adicionais (Features)</h3>
                                <span class="panel-subtitle">Configuração avançada em formato JSON</span>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">
                                <iconify-icon icon="solar:programming-bold"></iconify-icon>
                                Features (JSON)
                            </label>
                            <textarea name="features" class="form-input code-input" rows="5" 
                                      placeholder='{"analytics": true, "support": "priority", "api_access": true, "custom_domain": false}'><?= htmlspecialchars($plan['features'] ?? $_POST['features'] ?? '') ?></textarea>
                            <span class="form-hint">
                                <iconify-icon icon="solar:info-circle-bold"></iconify-icon>
                                JSON com recursos extras. Ex: analytics, support, api_access, custom_domain, etc.
                            </span>
                        </div>
                    </div>

                    <!-- Configurações -->
                    <div class="panel">
                        <div class="panel-header">
                            <div class="panel-icon orange">
                                <iconify-icon icon="solar:settings-bold"></iconify-icon>
                            </div>
                            <div>
                                <h3>Configurações</h3>
                                <span class="panel-subtitle">Visibilidade e ordenação</span>
                            </div>
                        </div>
                        
                        <div class="form-grid">
                            <div class="form-group">
                                <label class="form-label">
                                    <iconify-icon icon="solar:sort-by-alphabet-bold"></iconify-icon>
                                    Ordem de Exibição
                                </label>
                                <input type="number" name="sort_order" class="form-input" min="0"
                                       value="<?= htmlspecialchars($plan['sort_order'] ?? $_POST['sort_order'] ?? '0') ?>">
                                <span class="form-hint">
                                    <iconify-icon icon="solar:info-circle-bold"></iconify-icon>
                                    Menor número aparece primeiro
                                </span>
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">Opções</label>
                                <div class="checkbox-group">
                                    <label class="checkbox-item">
                                        <input type="checkbox" name="is_active" 
                                               <?= (isset($plan['is_active']) ? $plan['is_active'] : true) ? 'checked' : '' ?>>
                                        <span class="checkbox-box"></span>
                                        <span class="checkbox-text">
                                            <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                                            Plano Ativo
                                        </span>
                                    </label>
                                    <label class="checkbox-item">
                                        <input type="checkbox" name="is_featured"
                                               <?= ($plan['is_featured'] ?? false) ? 'checked' : '' ?>>
                                        <span class="checkbox-box"></span>
                                        <span class="checkbox-text">
                                            <iconify-icon icon="solar:star-bold"></iconify-icon>
                                            Plano Destacado (Popular)
                                        </span>
                                    </label>
                                    <label class="checkbox-item">
                                        <input type="checkbox" name="has_trial" id="has_trial"
                                               <?= ($plan['has_trial'] ?? false) ? 'checked' : '' ?>
                                               onchange="toggleTrialDays()">
                                        <span class="checkbox-box"></span>
                                        <span class="checkbox-text">
                                            <iconify-icon icon="solar:clock-circle-bold"></iconify-icon>
                                            Período de Teste (Trial)
                                        </span>
                                    </label>
                                    <div id="trial-days-container" class="form-group" style="margin-top: 0.5rem; margin-left: 2rem; <?= ($plan['has_trial'] ?? false) ? '' : 'display:none;' ?>">
                                        <label class="form-label">Dias de Trial</label>
                                        <input type="number" name="trial_days" class="form-input" min="1" max="365"
                                               value="<?= htmlspecialchars($plan['trial_days'] ?? $_POST['trial_days'] ?? '14') ?>" style="max-width: 120px;">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Botões de Ação -->
                    <div class="form-actions">
                        <a href="plans.php" class="btn btn-secondary">
                            <iconify-icon icon="solar:close-circle-bold"></iconify-icon>
                            Cancelar
                        </a>
                        <button type="submit" class="btn btn-primary">
                            <iconify-icon icon="solar:diskette-bold"></iconify-icon>
                            <?= $isNew ? 'Criar Plano' : 'Salvar Alterações' ?>
                        </button>
                    </div>
                </form>
            </div>
        </main>
    </div>

    <style>
    .content-area {
        padding: 1.5rem 2rem;
        max-width: 900px;
    }
    
    .page-header-edit {
        margin-bottom: 1.5rem;
    }
    
    .btn-back {
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        color: var(--text-muted);
        text-decoration: none;
        font-size: 0.9rem;
        margin-bottom: 1rem;
        padding: 0.5rem 0;
        transition: color 0.2s;
    }
    
    .btn-back:hover {
        color: var(--gold);
    }
    
    .page-title {
        display: flex;
        align-items: center;
        gap: 1rem;
    }
    
    .title-icon {
        font-size: 2.5rem;
        color: var(--gold);
    }
    
    .page-title h2 {
        font-size: 1.75rem;
        font-weight: 700;
        margin: 0;
        color: var(--text-primary);
    }
    
    .plan-id {
        font-size: 0.85rem;
        color: var(--text-muted);
        font-family: monospace;
        background: var(--bg-input);
        padding: 0.25rem 0.5rem;
        border-radius: var(--radius-sm);
    }
    
    .edit-form .panel {
        margin-bottom: 1.5rem;
    }
    
    .form-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 1rem;
    }
    
    .form-grid-3 {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 1rem;
    }
    
    @media (max-width: 768px) {
        .form-grid,
        .form-grid-3 {
            grid-template-columns: 1fr;
        }
        
        .content-area {
            padding: 1rem;
        }
    }
    
    .form-group {
        margin-bottom: 1rem;
    }
    
    .form-label {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        margin-bottom: 0.5rem;
        font-size: 0.9rem;
        font-weight: 600;
        color: var(--text-primary);
    }
    
    .form-label iconify-icon {
        color: var(--text-muted);
    }
    
    .form-input {
        width: 100%;
        padding: 0.75rem 1rem;
        background: var(--bg-input);
        border: 1px solid var(--border-light);
        border-radius: var(--radius-md);
        color: var(--text-primary);
        font-size: 0.95rem;
        transition: all 0.2s;
    }
    
    .form-input:focus {
        outline: none;
        border-color: var(--gold);
        box-shadow: 0 0 0 3px rgba(204, 164, 59, 0.15);
    }
    
    .form-input::placeholder {
        color: var(--text-muted);
    }
    
    textarea.form-input {
        resize: vertical;
        min-height: 80px;
        font-family: inherit;
    }
    
    .code-input {
        font-family: 'SF Mono', Monaco, Consolas, monospace;
        font-size: 0.85rem;
    }
    
    .form-hint {
        display: flex;
        align-items: center;
        gap: 0.35rem;
        margin-top: 0.5rem;
        font-size: 0.8rem;
        color: var(--text-muted);
    }
    
    .price-comparison {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.75rem 1rem;
        background: rgba(34, 197, 94, 0.1);
        border: 1px solid rgba(34, 197, 94, 0.2);
        border-radius: var(--radius-md);
        color: #22C55E;
        font-size: 0.9rem;
        margin-top: 1rem;
    }
    
    .feature-toggles {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 1rem;
        margin-top: 1.5rem;
        padding-top: 1.5rem;
        border-top: 1px dashed var(--border-light);
    }
    .toggle-item {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        cursor: pointer;
        padding: 1rem;
        background: var(--bg-input);
        border-radius: var(--radius-md);
        transition: all 0.2s;
    }
    .toggle-item:hover {
        background: rgba(204, 164, 59, 0.1);
    }
    .toggle-item input { display: none; }
    .toggle-switch {
        width: 44px;
        height: 24px;
        background: var(--border-light);
        border-radius: 12px;
        position: relative;
        transition: background 0.3s;
        flex-shrink: 0;
    }
    .toggle-switch::after {
        content: '';
        position: absolute;
        width: 18px;
        height: 18px;
        background: white;
        border-radius: 50%;
        top: 3px;
        left: 3px;
        transition: transform 0.3s;
    }
    .toggle-item input:checked + .toggle-switch {
        background: var(--gold);
    }
    .toggle-item input:checked + .toggle-switch::after {
        transform: translateX(20px);
    }
    .toggle-label {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        font-weight: 500;
        color: var(--text-primary);
    }
    .toggle-label iconify-icon {
        font-size: 1.2rem;
        color: var(--gold);
    }

    .checkbox-group {
        display: flex;
        flex-direction: column;
        gap: 0.75rem;
    }
    
    .checkbox-item {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        cursor: pointer;
        padding: 0.75rem 1rem;
        background: var(--bg-input);
        border-radius: var(--radius-md);
        transition: background 0.2s;
    }
    
    .checkbox-item:hover {
        background: rgba(204, 164, 59, 0.1);
    }
    
    .checkbox-item input {
        display: none;
    }
    
    .checkbox-box {
        width: 22px;
        height: 22px;
        border: 2px solid var(--border-light);
        border-radius: 6px;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.2s;
        flex-shrink: 0;
    }
    
    .checkbox-item input:checked + .checkbox-box {
        background: var(--gold);
        border-color: var(--gold);
    }
    
    .checkbox-item input:checked + .checkbox-box::after {
        content: '';
        width: 6px;
        height: 10px;
        border: solid #1a1a2e;
        border-width: 0 2px 2px 0;
        transform: rotate(45deg);
        margin-bottom: 2px;
    }
    
    .checkbox-text {
        display: flex;
        align-items: center;
        gap: 0.5rem;
        color: var(--text-primary);
        font-weight: 500;
    }
    
    .checkbox-text iconify-icon {
        color: var(--text-muted);
    }
    
    .form-actions {
        display: flex;
        justify-content: flex-end;
        gap: 1rem;
        padding-top: 1rem;
        border-top: 1px solid var(--border-light);
        margin-top: 1rem;
    }
    
    .btn {
        display: inline-flex;
        align-items: center;
        gap: 0.5rem;
        padding: 0.875rem 1.5rem;
        border-radius: var(--radius-md);
        font-size: 0.95rem;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s;
        border: none;
        text-decoration: none;
    }
    
    .btn-primary {
        background: var(--gold);
        color: #1a1a2e;
    }
    
    .btn-primary:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(204, 164, 59, 0.4);
    }
    
    .btn-secondary {
        background: var(--bg-input);
        color: var(--text-primary);
        border: 1px solid var(--border-light);
    }
    
    .btn-secondary:hover {
        background: var(--bg-panel);
        border-color: var(--gold);
    }
    
    /* Alert styles */
    .alert {
        display: flex;
        align-items: center;
        gap: 0.75rem;
        padding: 1rem 1.25rem;
        border-radius: var(--radius-md);
        margin-bottom: 1.5rem;
        font-weight: 500;
    }
    
    .alert-error {
        background: rgba(239, 68, 68, 0.1);
        border: 1px solid rgba(239, 68, 68, 0.3);
        color: #EF4444;
    }
    </style>

    <script>
    // Auto-gerar ID baseado no nome (apenas para novo plano)
    <?php if ($isNew): ?>
    document.getElementById('planName').addEventListener('input', function() {
        const planIdInput = document.getElementById('planId');
        if (!planIdInput.dataset.manual) {
            planIdInput.value = this.value
                .toLowerCase()
                .normalize('NFD')
                .replace(/[\u0300-\u036f]/g, '')
                .replace(/[^a-z0-9]+/g, '-')
                .replace(/^-|-$/g, '');
        }
    });
    
    document.getElementById('planId').addEventListener('input', function() {
        this.dataset.manual = 'true';
    });
    <?php endif; ?>
    function toggleTrialDays() {
        var checkbox = document.getElementById("has_trial");
        var container = document.getElementById("trial-days-container");
        container.style.display = checkbox.checked ? "block" : "none";
    }
    </script>
<?php include __DIR__ . '/../includes/footer.php'; ?>
