<?php
/**
 * Página de Assinatura - MontaLoja SaaS
 */
require_once __DIR__ . '/../includes/config.php';

$pdo = getDB();
$userId = $_SESSION['user_id'] ?? null;
$storeId = $_SESSION['store_id'] ?? null;

if (!$userId || !$storeId) {
    header('Location: /pages/login.php');
    exit;
}

$userStmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$userStmt->execute([$userId]);
$user = $userStmt->fetch(PDO::FETCH_ASSOC);

$storeStmt = $pdo->prepare("SELECT s.*, p.name as plan_name, p.price_monthly, p.price_yearly, 
    p.max_products, p.max_orders_per_month, p.max_staff_users, 
    p.whatsapp_integration, p.custom_domain, p.control_panel, 
    p.full_reports, p.dedicated_support, p.features as plan_features, p.description as plan_description
    FROM stores s 
    LEFT JOIN plans p ON s.plan_id = p.id 
    WHERE s.id = ?");
$storeStmt->execute([$storeId]);
$store = $storeStmt->fetch(PDO::FETCH_ASSOC);

// Verificar se é owner/admin
$isOwner = ($user['role'] === 'owner' || $user['role'] === 'admin');
if (!$isOwner) {
    header('Location: /dashboard.php');
    exit;
}

// Processar callback de pagamento e ativar plano
require_once __DIR__ . '/../includes/handle-payment-callback.php';

// Buscar todos os planos ativos do banco de dados
$plansStmt = $pdo->prepare("SELECT * FROM plans WHERE is_active = 1 ORDER BY sort_order ASC, price_monthly ASC");
$plansStmt->execute();
$dbPlans = $plansStmt->fetchAll(PDO::FETCH_ASSOC);

// Plano atual da loja
$currentPlanId = $store['plan_id'] ?? 'free';
$currentPlanName = $store['plan_name'] ?? 'Grátis';
$currentPlanPrice = $store['price_monthly'] ?? 0;

// Ícones para os planos
$planIcons = [
    'free' => 'solar:gift-bold',
    'starter' => 'solar:rocket-bold',
    'pro' => 'solar:crown-bold',
    'professional' => 'solar:crown-bold',
    'enterprise' => 'solar:buildings-bold'
];

// Função para formatar as features - retorna array com nome e status (ativo/inativo)
function formatFeatures($plan) {
    $features = [];
    
    // Produtos
    $maxProducts = $plan['max_products'];
    if ($maxProducts === null || $maxProducts == -1 || $maxProducts > 9999) {
        $features[] = ['name' => 'Produtos ilimitados', 'active' => true];
    } elseif ($maxProducts > 0) {
        $features[] = ['name' => $maxProducts . ' produtos', 'active' => true];
    } else {
        $features[] = ['name' => 'Produtos limitados', 'active' => false];
    }
    
    // Usuários
    $maxUsers = $plan['max_staff_users'];
    if ($maxUsers === null || $maxUsers == -1 || $maxUsers > 9999) {
        $features[] = ['name' => 'Usuários ilimitados', 'active' => true];
    } elseif ($maxUsers > 0) {
        $features[] = ['name' => $maxUsers . ' usuários', 'active' => true];
    } else {
        $features[] = ['name' => '1 usuário', 'active' => true];
    }
    
    // Pedidos
    $maxOrders = $plan['max_orders_per_month'];
    if ($maxOrders === null || $maxOrders == -1 || $maxOrders > 9999) {
        $features[] = ['name' => 'Pedidos ilimitados', 'active' => true];
    } elseif ($maxOrders > 0) {
        $features[] = ['name' => $maxOrders . ' pedidos/mês', 'active' => true];
    } else {
        $features[] = ['name' => 'Pedidos limitados', 'active' => false];
    }
    
    // Painel de Controle
    $features[] = ['name' => 'Painel de Controle', 'active' => !empty($plan['control_panel'])];
    
    // Relatórios Completos
    $features[] = ['name' => 'Relatórios Completos', 'active' => !empty($plan['full_reports'])];
    
    // Suporte Dedicado
    $features[] = ['name' => 'Suporte Dedicado', 'active' => !empty($plan['dedicated_support'])];
    
    // Integração WhatsApp
    $features[] = ['name' => 'Integração WhatsApp', 'active' => !empty($plan['whatsapp_integration'])];
    
    // Domínio Personalizado
    $features[] = ['name' => 'Domínio Personalizado', 'active' => !empty($plan['custom_domain'])];
    
    // Ordenar: ativos primeiro, inativos (X) por último
    usort($features, function($a, $b) {
        return $b['active'] - $a['active'];
    });

    return $features;
}

$pageTitle = 'Assinatura';
include __DIR__ . '/../includes/dashboard-header.php';
include __DIR__ . '/../includes/dashboard-styles.php';
?>

<style>
.current-plan-card {
    margin-bottom: 2rem;
    background: linear-gradient(135deg, rgba(37, 99, 235, 0.1), rgba(37, 99, 235, 0.05));
    border: 2px solid var(--primary);
    border-radius: 16px;
    padding: 1.5rem;
}
.current-plan-inner {
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 1rem;
}
.current-plan-info .plan-label {
    color: var(--text-muted);
    font-size: 0.85rem;
    margin-bottom: 0.25rem;
}
.current-plan-info .plan-name {
    font-size: 1.5rem;
    font-weight: 700;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}
.current-plan-info .plan-status {
    display: inline-flex;
    align-items: center;
    gap: 0.35rem;
    margin-top: 0.5rem;
    padding: 0.35rem 0.75rem;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 600;
}
.current-plan-info .plan-status.active {
    background: rgba(34, 197, 94, 0.15);
    color: #22C55E;
}
.current-plan-info .plan-status.trial {
    background: rgba(245, 158, 11, 0.15);
    color: #F59E0B;
}
.current-plan-price .price-value {
    font-size: 2rem;
    font-weight: 700;
    color: var(--primary);
}
.current-plan-price .price-period {
    font-size: 0.9rem;
    color: var(--text-muted);
}
.plans-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: 1.5rem;
    margin-bottom: 2rem;
}
.plan-card {
    position: relative;
    background: var(--bg-card);
    border: 1px solid var(--border);
    border-radius: 16px;
    padding: 1.5rem;
    transition: all 0.3s ease;
}
.plan-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}
.plan-card.current {
    border: 2px solid var(--success);
    background: linear-gradient(135deg, rgba(34, 197, 94, 0.05), rgba(34, 197, 94, 0.02));
}
.plan-card.popular {
    border: 2px solid var(--primary);
}
.plan-current-badge, .plan-popular-badge {
    position: absolute;
    top: -12px;
    left: 50%;
    transform: translateX(-50%);
    padding: 0.25rem 1rem;
    border-radius: 20px;
    font-size: 0.75rem;
    font-weight: 700;
    white-space: nowrap;
}
.plan-current-badge {
    background: var(--success);
    color: #fff;
}
.plan-popular-badge {
    background: var(--primary);
    color: #000;
}
.plan-trial-badge {
    position: absolute;
    top: -10px;
    right: 10px;
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: white;
    font-size: 0.7rem;
    font-weight: 600;
    padding: 4px 10px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    gap: 4px;
    box-shadow: 0 2px 8px rgba(16, 185, 129, 0.3);
    z-index: 5;
}
.plan-trial-badge iconify-icon {
    font-size: 0.85rem;
}
.plan-header {
    text-align: center;
    margin-bottom: 1.5rem;
}
.plan-icon {
    font-size: 2.5rem;
    color: var(--primary);
}
.plan-title {
    font-size: 1.25rem;
    margin: 0.75rem 0 0.25rem;
}
.plan-price {
    font-size: 2rem;
    font-weight: 700;
}
.plan-period {
    font-size: 0.9rem;
    color: var(--text-muted);
}
.plan-features {
    list-style: none;
    padding: 0;
    margin: 0 0 1.5rem;
}
.plan-feature-item {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.5rem 0;
    border-bottom: 1px solid var(--border);
    font-size: 0.9rem;
}
.plan-feature-item:last-child {
    border-bottom: none;
}
.plan-feature-item iconify-icon {
    flex-shrink: 0;
    font-size: 1.1rem;
}
.plan-feature-item.active iconify-icon {
    color: #22C55E;
}
.plan-feature-item.inactive {
    opacity: 0.5;
}
.plan-feature-item.inactive iconify-icon {
    color: #EF4444;
}
.faq-section {
    margin-top: 2rem;
}
.faq-grid {
    display: grid;
    gap: 1rem;
}
.faq-item {
    padding: 1rem;
    background: var(--bg-darker);
    border-radius: 8px;
}
.faq-question {
    font-weight: 600;
    margin-bottom: 0.5rem;
}
.faq-answer {
    color: var(--text-muted);
    font-size: 0.9rem;
}
.support-section {
    text-align: center;
    margin-top: 2rem;
    padding: 2rem;
    background: var(--bg-card);
    border: 1px solid var(--border);
    border-radius: 12px;
}
</style>

<main class="main-content">
    <?php if (!empty($paymentMessage)): ?>
    <div class="alert" style="display: flex; align-items: center; gap: 0.75rem; padding: 1rem 1.5rem; margin-bottom: 1.5rem; border-radius: 12px; <?= $paymentMessageType === 'success' ? 'background: rgba(34, 197, 94, 0.1); border: 1px solid rgba(34, 197, 94, 0.3); color: #16a34a;' : ($paymentMessageType === 'error' ? 'background: rgba(239, 68, 68, 0.1); border: 1px solid rgba(239, 68, 68, 0.3); color: #dc2626;' : 'background: rgba(245, 158, 11, 0.1); border: 1px solid rgba(245, 158, 11, 0.3); color: #d97706;') ?>">
        <iconify-icon icon="<?= $paymentMessageType === 'success' ? 'solar:check-circle-bold' : ($paymentMessageType === 'error' ? 'solar:danger-triangle-bold' : 'solar:clock-circle-bold') ?>" style="font-size: 1.5rem;"></iconify-icon>
        <span><?= htmlspecialchars($paymentMessage) ?></span>
    </div>
    <?php endif; ?>
    <div class="page-header">
        <h1><iconify-icon icon="solar:card-bold"></iconify-icon> Assinatura</h1>
        <p>Gerencie seu plano e faturamento</p>
    </div>

    <!-- Plano Atual -->
    <div class="card current-plan-card">
        <div class="current-plan-inner">
            <div class="current-plan-info">
                <div class="plan-label">Plano Atual</div>
                <div class="plan-name">
                    <iconify-icon icon="<?php echo $planIcons[$currentPlanId] ?? 'solar:star-bold'; ?>" style="color: var(--primary);"></iconify-icon>
                    <?php echo htmlspecialchars($currentPlanName); ?>
                </div>
                <div class="plan-status <?php echo $store['status'] === 'active' ? 'active' : 'trial'; ?>">
                    <iconify-icon icon="<?php echo $store['status'] === 'active' ? 'solar:check-circle-bold' : 'solar:clock-circle-bold'; ?>"></iconify-icon>
                    <?php echo $store['status'] === 'active' ? 'Ativo' : 'Período de Teste'; ?>
                </div>
            </div>
            <div class="current-plan-price">
                <span class="price-value">
                    <?php echo $currentPlanPrice > 0 ? 'R$ ' . number_format($currentPlanPrice, 2, ',', '.') : 'Grátis'; ?>
                </span>
                <?php if ($currentPlanPrice > 0): ?>
                <span class="price-period">/mês</span>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Planos Disponíveis -->
    <h2 style="font-size: 1.25rem; margin-bottom: 1.5rem;">
        <iconify-icon icon="solar:tag-price-bold" style="color: var(--primary);"></iconify-icon>
        Planos Disponíveis
    </h2>
    <div class="plans-grid">
        <?php foreach ($dbPlans as $plan): 
            $isCurrent = ($plan['id'] === $currentPlanId);
            $isPopular = !empty($plan['is_featured']);
            $features = formatFeatures($plan);
            $icon = $planIcons[$plan['id']] ?? 'solar:star-bold';
        ?>
        <div class="plan-card <?php echo $isPopular ? 'popular' : ''; ?> <?php echo $isCurrent ? 'current' : ''; ?>">
            <?php if ($isCurrent): ?>
            <div class="plan-current-badge">
                <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                PLANO ATUAL
            </div>
            <?php elseif ($isPopular): ?>
            <div class="plan-popular-badge">
                <iconify-icon icon="solar:star-bold"></iconify-icon>
                MAIS POPULAR
            </div>
            <?php endif; ?>
            <?php if ($plan['has_trial'] ?? false): ?>
            <div class="plan-trial-badge">
                <iconify-icon icon="solar:clock-circle-bold"></iconify-icon>
                <?php echo $plan['trial_days']; ?> dias grátis
            </div>
            <?php endif; ?>

            <div class="plan-header">
                <iconify-icon icon="<?php echo $icon; ?>" class="plan-icon"></iconify-icon>
                <h3 class="plan-title"><?php echo htmlspecialchars($plan['name']); ?></h3>
                <div class="plan-price">
                    <?php if ($plan['price_monthly'] > 0): ?>
                    R$ <?php echo number_format($plan['price_monthly'], 2, ',', '.'); ?>
                    <span class="plan-period">/mês</span>
                    <?php else: ?>
                    Grátis
                    <?php endif; ?>
                </div>
            </div>

            <ul class="plan-features">
                <?php foreach ($features as $feature): ?>
                <li class="plan-feature-item <?php echo $feature['active'] ? 'active' : 'inactive'; ?>">
                    <iconify-icon icon="<?php echo $feature['active'] ? 'solar:check-circle-bold' : 'solar:close-circle-bold'; ?>"></iconify-icon>
                    <?php echo htmlspecialchars($feature['name']); ?>
                </li>
                <?php endforeach; ?>
            </ul>

            <?php if ($isCurrent): ?>
            <button class="btn btn-secondary" style="width: 100%;" disabled>
                <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                Plano Atual
            </button>
            <?php elseif ($plan['price_monthly'] > $currentPlanPrice): ?>
            <button class="btn btn-primary" style="width: 100%;" onclick="openCheckout('<?= $plan['id'] ?>', '<?= htmlspecialchars($plan['name']) ?>', <?= $plan['price_monthly'] ?>)">
                <iconify-icon icon="solar:arrow-up-bold"></iconify-icon>
                Fazer Upgrade
            </button>
            <?php else: ?>
            <button class="btn btn-secondary" style="width: 100%;" onclick="openCheckout('<?= $plan['id'] ?>', '<?= htmlspecialchars($plan['name']) ?>', <?= $plan['price_monthly'] ?>)">
                Selecionar
            </button>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>
    </div>

    <!-- FAQ -->
    <div class="card faq-section">
        <h2 style="font-size: 1.1rem; margin-bottom: 1.5rem; display: flex; align-items: center; gap: 0.5rem;">
            <iconify-icon icon="solar:question-circle-bold"></iconify-icon>
            Perguntas Frequentes
        </h2>
        <div class="faq-grid">
            <div class="faq-item">
                <div class="faq-question">Posso cancelar a qualquer momento?</div>
                <div class="faq-answer">Sim! Você pode cancelar sua assinatura a qualquer momento sem taxas adicionais.</div>
            </div>
            <div class="faq-item">
                <div class="faq-question">Como funciona o período de teste?</div>
                <div class="faq-answer">Todos os planos pagos têm 7 dias de teste grátis. Você só será cobrado após esse período.</div>
            </div>
            <div class="faq-item">
                <div class="faq-question">Quais formas de pagamento são aceitas?</div>
                <div class="faq-answer">Aceitamos cartão de crédito, boleto bancário e PIX.</div>
            </div>
            <div class="faq-item">
                <div class="faq-question">Posso fazer upgrade ou downgrade?</div>
                <div class="faq-answer">Sim! Você pode alterar seu plano a qualquer momento. O valor será ajustado proporcionalmente.</div>
            </div>
        </div>
    </div>

    <!-- Suporte -->
    <div class="support-section">
        <iconify-icon icon="solar:headphones-round-bold" style="font-size: 2.5rem; color: var(--primary);"></iconify-icon>
        <h3 style="margin: 1rem 0 0.5rem;">Precisa de ajuda?</h3>
        <p style="color: var(--text-muted); margin-bottom: 1rem;">Nossa equipe está pronta para ajudar você a escolher o melhor plano.</p>
        <a href="https://wa.me/5527996322138" target="_blank" class="btn btn-primary">
            <iconify-icon icon="mdi:whatsapp"></iconify-icon>
            Falar com Suporte
        </a>
    </div>
</main>

<?php include __DIR__ . '/../includes/payment-modal.php'; ?>

<?php include __DIR__ . '/../includes/dashboard-footer.php'; ?>
