<?php
/**
 * Gerenciamento de Planos - Super Admin
 */
require_once __DIR__ . '/../../../includes/config.php';

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

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

// Processar exclusão
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete') {
    try {
        $id = $_POST['plan_id'] ?? '';
        
        // Verificar se há assinantes ativos
        $check = $pdo->prepare("SELECT COUNT(*) FROM subscriptions WHERE plan_id = ? AND status = 'active'");
        $check->execute([$id]);
        if ($check->fetchColumn() > 0) {
            throw new Exception('Não é possível excluir um plano com assinantes ativos');
        }
        
        $stmt = $pdo->prepare("DELETE FROM plans WHERE id = ?");
        $stmt->execute([$id]);
        
        $_SESSION['flash_success'] = 'Plano excluído com sucesso!';
    } catch (Exception $e) {
        $_SESSION['flash_error'] = $e->getMessage();
    }
    
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// Buscar planos
$plans = $pdo->query("
    SELECT p.*,
           (SELECT COUNT(*) FROM stores s WHERE s.plan_id = p.id AND s.deleted_at IS NULL) as active_subscriptions
    FROM plans p
    ORDER BY p.sort_order ASC, p.price_monthly ASC
")->fetchAll(PDO::FETCH_ASSOC);

$pageTitle = 'Gerenciar Planos';
$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">
                <?php if (isset($_SESSION['flash_success'])): ?>
                <div class="alert alert-success">
                    <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                    <span><?= htmlspecialchars($_SESSION['flash_success']) ?></span>
                </div>
                <?php unset($_SESSION['flash_success']); endif; ?>

                <?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; ?>

                <div class="page-header">
                    <div>
                        <h2>Gerenciar Planos</h2>
                        <p>Configure os planos de assinatura do SaaS</p>
                    </div>
                    <a href="plan-edit.php" class="btn btn-primary">
                        <iconify-icon icon="solar:add-circle-bold"></iconify-icon>
                        Novo Plano
                    </a>
                </div>

                <div class="plans-grid">
                    <?php foreach ($plans as $plan): ?>
                    <div class="plan-card <?= !$plan['is_active'] ? 'inactive' : '' ?>">
                        <?php if ($plan['is_featured'] ?? false): ?>
                        <div class="plan-badge popular">Popular</div>
                        <?php endif; ?>

                        <?php if (!$plan['is_active']): ?>
                        <div class="plan-badge inactive-badge">Inativo</div>
                        <?php endif; ?>

                        <?php if ($plan['has_trial'] ?? false): ?>
                        <div class="plan-badge trial-badge">
                            <iconify-icon icon="solar:clock-circle-bold"></iconify-icon>
                            Trial: <?= $plan['trial_days'] ?> dias
                        </div>
                        <?php endif; ?>

                        <div class="plan-header">
                            <span class="plan-id">ID: <?= htmlspecialchars($plan['id']) ?></span>
                            <h3 class="plan-name"><?= htmlspecialchars($plan['name']) ?></h3>
                            <div class="plan-price">
                                <?= formatMoney($plan['price_monthly']) ?>
                                <span class="price-period">/mês</span>
                            </div>
                            <?php if ($plan['price_yearly'] > 0): ?>
                            <div class="plan-price-yearly">ou <?= formatMoney($plan['price_yearly']) ?>/ano</div>
                            <?php endif; ?>
                        </div>

                        <div class="plan-features">
                            <?php
                            // Definir todas as features
                            $features = [
                                ['key' => 'max_products', 'label' => $plan['max_products'] ? $plan['max_products'] . ' produtos' : 'Produtos ilimitados', 'enabled' => true],
                                ['key' => 'max_staff_users', 'label' => $plan['max_staff_users'] ? $plan['max_staff_users'] . ' usuários' : 'Usuários ilimitados', 'enabled' => true],
                                ['key' => 'max_orders_per_month', 'label' => $plan['max_orders_per_month'] ? $plan['max_orders_per_month'] . ' pedidos/mês' : 'Pedidos ilimitados', 'enabled' => true],
                                ['key' => 'whatsapp_integration', 'label' => 'Integração WhatsApp', 'enabled' => (bool)($plan['whatsapp_integration'] ?? false)],
                                ['key' => 'custom_domain', 'label' => 'Domínio Personalizado', 'enabled' => (bool)($plan['custom_domain'] ?? false)],
                                ['key' => 'control_panel', 'label' => 'Painel de Controle', 'enabled' => (bool)($plan['control_panel'] ?? false)],
                                ['key' => 'full_reports', 'label' => 'Relatórios Completos', 'enabled' => (bool)($plan['full_reports'] ?? false)],
                                ['key' => 'dedicated_support', 'label' => 'Suporte Dedicado', 'enabled' => (bool)($plan['dedicated_support'] ?? false)],
                            ];
                            // Ordenar: ativados primeiro, desativados depois
                            usort($features, function($a, $b) {
                                return $b['enabled'] <=> $a['enabled'];
                            });
                            foreach ($features as $feature):
                            ?>
                            <div class="feature-item <?= $feature['enabled'] ? '' : 'disabled' ?>">
                                <iconify-icon icon="<?= $feature['enabled'] ? 'solar:check-circle-bold' : 'solar:close-circle-bold' ?>" class="<?= $feature['enabled'] ? 'feature-icon' : 'feature-icon-disabled' ?>"></iconify-icon>
                                <span><?= $feature['label'] ?></span>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <?php if (!empty($plan['description'])): ?>
                        <div class="plan-description"><?= htmlspecialchars($plan['description']) ?></div>
                        <?php endif; ?>

                        <div class="plan-subscribers">
                            <iconify-icon icon="solar:users-group-rounded-bold"></iconify-icon>
                            <?= $plan['active_subscriptions'] ?? 0 ?> assinantes ativos
                        </div>

                        <div class="plan-actions">
                            <a href="plan-edit.php?id=<?= htmlspecialchars($plan['id']) ?>" class="btn btn-secondary btn-sm">
                                <iconify-icon icon="solar:pen-bold"></iconify-icon>
                                Editar
                            </a>
                            <button onclick="deletePlan('<?= htmlspecialchars($plan['id']) ?>', '<?= htmlspecialchars($plan['name']) ?>', <?= $plan['active_subscriptions'] ?? 0 ?>)" class="btn btn-danger btn-sm">
                                <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
                            </button>
                        </div>
                    </div>
                    <?php endforeach; ?>

                    <?php if (empty($plans)): ?>
                    <div class="empty-state">
                        <iconify-icon icon="solar:tag-price-bold" class="empty-icon"></iconify-icon>
                        <p>Nenhum plano cadastrado</p>
                        <a href="plan-edit.php" class="btn btn-primary">Criar primeiro plano</a>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </main>
    </div>

    <div id="deleteModal" class="modal">
        <div class="modal-overlay" onclick="closeDeleteModal()"></div>
        <div class="modal-content modal-sm">
            <div class="modal-header">
                <h3>Confirmar Exclusão</h3>
                <button onclick="closeDeleteModal()" class="modal-close">
                    <iconify-icon icon="solar:close-circle-bold"></iconify-icon>
                </button>
            </div>
            <div class="modal-body">
                <div class="delete-warning">
                    <iconify-icon icon="solar:danger-triangle-bold" class="warning-icon"></iconify-icon>
                    <p>Tem certeza que deseja excluir o plano <strong id="deletePlanName"></strong>?</p>
                    <p class="warning-text">Esta ação não pode ser desfeita.</p>
                </div>
            </div>
            <div class="modal-footer">
                <button onclick="closeDeleteModal()" class="btn btn-secondary">Cancelar</button>
                <form id="deleteForm" method="POST" style="display:inline;">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="plan_id" id="deletePlanId">
                    <button type="submit" class="btn btn-danger">
                        <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
                        Excluir
                    </button>
                </form>
            </div>
        </div>
    </div>

    <style>
    .content-area { padding: 1.5rem 2rem; }
    .page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem; }
    .page-header h2 { font-size: 1.75rem; font-weight: 700; margin: 0 0 0.25rem 0; }
    .page-header p { color: var(--text-muted); margin: 0; }
    .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-success { background: rgba(34, 197, 94, 0.1); border: 1px solid rgba(34, 197, 94, 0.3); color: #22C55E; }
    .alert-error { background: rgba(239, 68, 68, 0.1); border: 1px solid rgba(239, 68, 68, 0.3); color: #EF4444; }
    .plans-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 1.5rem; }
    .plan-card { background: var(--bg-panel); border: 1px solid var(--border-light); border-radius: var(--radius-lg); padding: 1.5rem; position: relative; transition: transform 0.2s, box-shadow 0.2s; }
    .plan-card:hover { transform: translateY(-4px); box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2); }
    .plan-card.inactive { opacity: 0.6; }
    .plan-badge { position: absolute; padding: 4px 12px; border-radius: 4px; font-size: 0.75rem; font-weight: 600; text-transform: uppercase; }
    .plan-badge.popular { top: -10px; right: 20px; background: var(--gold); color: #1a1a2e; }
    .plan-badge.inactive-badge { top: 10px; left: 10px; background: var(--text-muted); color: white; }
    .plan-badge.trial-badge { top: 10px; right: 10px; background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; display: flex; align-items: center; gap: 4px; }
    .plan-badge.trial-badge iconify-icon { font-size: 0.9rem; }
    .plan-header { text-align: center; margin-bottom: 1.5rem; padding-bottom: 1.5rem; border-bottom: 1px solid var(--border-light); }
    .plan-id { font-size: 0.75rem; color: var(--text-muted); font-family: monospace; background: var(--bg-input); padding: 2px 8px; border-radius: 4px; }
    .plan-name { font-size: 1.5rem; font-weight: 700; margin: 0.75rem 0; color: var(--text-primary); }
    .plan-price { font-size: 2.5rem; font-weight: 700; color: var(--gold); }
    .price-period { font-size: 1rem; color: var(--text-muted); font-weight: 400; }
    .plan-price-yearly { font-size: 0.9rem; color: var(--text-muted); margin-top: 0.25rem; }
    .plan-features { margin-bottom: 1.5rem; }
    .feature-item { display: flex; align-items: center; gap: 0.75rem; margin-bottom: 0.75rem; color: var(--text-primary); }
    .feature-icon { color: #22C55E; font-size: 1.1rem; }
    .feature-icon-disabled { color: #EF4444; font-size: 1.1rem; }
    .feature-item.disabled { opacity: 0.6; }
    .feature-item.disabled span { text-decoration: line-through; }
    .plan-description { font-size: 0.85rem; color: var(--text-muted); text-align: center; margin-bottom: 1rem; padding: 0.75rem; background: var(--bg-input); border-radius: var(--radius-md); }
    .plan-subscribers { display: flex; align-items: center; justify-content: center; gap: 0.5rem; color: var(--text-muted); font-size: 0.85rem; margin-bottom: 1.5rem; }
    .plan-actions { display: flex; justify-content: center; gap: 0.75rem; }
    .empty-state { grid-column: 1 / -1; text-align: center; padding: 4rem 2rem; background: var(--bg-panel); border: 1px solid var(--border-light); border-radius: var(--radius-lg); }
    .empty-icon { font-size: 4rem; color: var(--text-muted); margin-bottom: 1rem; display: block; }
    .empty-state p { color: var(--text-muted); margin-bottom: 1.5rem; }
    .btn { display: inline-flex; align-items: center; gap: 0.5rem; padding: 0.75rem 1.25rem; border-radius: var(--radius-md); font-size: 0.9rem; font-weight: 600; cursor: pointer; transition: all 0.2s; border: none; text-decoration: none; }
    .btn-sm { padding: 0.5rem 1rem; font-size: 0.85rem; }
    .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); }
    .btn-danger { background: rgba(239, 68, 68, 0.15); color: #EF4444; border: 1px solid rgba(239, 68, 68, 0.3); }
    .btn-danger:hover { background: #EF4444; color: white; }
    .modal { position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 1000; display: none; align-items: center; justify-content: center; }
    .modal.active { display: flex; }
    .modal-overlay { position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.7); backdrop-filter: blur(4px); }
    .modal-content { position: relative; background: var(--bg-panel); border: 1px solid var(--border-light); border-radius: var(--radius-lg); width: 90%; max-width: 400px; animation: modalIn 0.3s ease; }
    @keyframes modalIn { from { opacity: 0; transform: scale(0.95) translateY(-20px); } to { opacity: 1; transform: scale(1) translateY(0); } }
    .modal-header { display: flex; justify-content: space-between; align-items: center; padding: 1.25rem 1.5rem; border-bottom: 1px solid var(--border-light); }
    .modal-header h3 { font-size: 1.25rem; font-weight: 700; margin: 0; color: var(--text-primary); }
    .modal-close { background: none; border: none; color: var(--text-muted); font-size: 1.5rem; cursor: pointer; padding: 0; line-height: 1; transition: color 0.2s; }
    .modal-close:hover { color: #EF4444; }
    .modal-body { padding: 1.5rem; }
    .modal-footer { display: flex; justify-content: flex-end; gap: 0.75rem; padding: 1rem 1.5rem; border-top: 1px solid var(--border-light); background: var(--bg-input); }
    .delete-warning { text-align: center; }
    .warning-icon { font-size: 3rem; color: #EF4444; margin-bottom: 1rem; display: block; }
    .delete-warning p { margin: 0.5rem 0; color: var(--text-primary); }
    .warning-text { color: var(--text-muted) !important; font-size: 0.9rem; }
    @media (max-width: 768px) { .content-area { padding: 1rem; } .page-header { flex-direction: column; gap: 1rem; text-align: center; } .plans-grid { grid-template-columns: 1fr; } }
    </style>

    <script>
    function deletePlan(id, name, subscribers) {
        if (subscribers > 0) {
            alert('Não é possível excluir um plano com assinantes ativos.');
            return;
        }
        document.getElementById('deletePlanId').value = id;
        document.getElementById('deletePlanName').textContent = name;
        document.getElementById('deleteModal').classList.add('active');
    }
    function closeDeleteModal() {
        document.getElementById('deleteModal').classList.remove('active');
    }
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') closeDeleteModal();
    });
    </script>
<?php include __DIR__ . '/../includes/footer.php'; ?>
