<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

$json_file = __DIR__ . '/dados_planos.json';

// Tenta carregar os dados de forma resiliente
if (file_exists($json_file)) {
    $dados_brutos = file_get_contents($json_file);
    $dados = json_decode($dados_brutos, true);
}

// Fallback Automático caso o JSON suma por acidente para evitar Tela Branca
if (!isset($dados) || !is_array($dados)) {
    $dados = [
        "seu_whatsapp" => "5571997244148",
        "planos" => [
            "premium" => ["nome" => "Premium", "preco" => "45,00", "macs" => "1 MAC", "popular" => false, "recursos" => ["PLANO PREMIUM INICIAL"]],
            "master" => ["nome" => "Master", "preco" => "75,00", "macs" => "5 MACs", "popular" => true, "recursos" => ["PLANO SUPER MASTER"]],
            "ultra-master" => ["nome" => "Ultra Master", "preco" => "120,00", "macs" => "Ilimitados MACs", "popular" => false, "recursos" => ["PLANO ULTRA MASTER COMPLETO"]]
        ]
    ];
}

$planos = $dados['planos'];
$whatsapp_limpo = preg_replace('/[^0-9]/', '', $dados['seu_whatsapp']);
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Upgrade de Plano - IBO Revenda</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
        body { background-color: #090d1a; color: #ffffff; display: flex; justify-content: center; align-items: flex-start; min-height: 100vh; padding: 20px; }
        .container { background-color: #ffffff; color: #1e293b; width: 100%; max-width: 100%; border-radius: 16px; padding: 30px; box-shadow: 0 10px 25px rgba(0, 0, 0, 0.3); }
        .header-title { font-size: 1.25rem; font-weight: 600; color: #0f172a; margin-bottom: 5px; }
        .header-subtitle { font-size: 0.875rem; color: #64748b; margin-bottom: 25px; }
        .tabs-container { display: flex; justify-content: center; background-color: #f1f5f9; padding: 6px; border-radius: 30px; max-width: 400px; margin: 0 auto 30px auto; border: 1px solid #e2e8f0; }
        .tab-btn { flex: 1; background: none; border: none; padding: 10px 15px; font-size: 0.85rem; font-weight: 600; color: #334155; cursor: pointer; border-radius: 20px; transition: all 0.3s ease; }
        .tab-btn.active { background-color: #0f172a; color: #ffffff; box-shadow: 0 4px 10px rgba(15, 23, 42, 0.2); }
        .plan-content { display: none; }
        .plan-content.active { display: block; animation: fadeIn 0.4s ease; }
        .plan-card { border: 1px solid #cbd5e1; border-radius: 12px; padding: 25px; position: relative; background-color: #ffffff; width: 100%; }
        .badge-popular { position: absolute; top: 0; right: 0; background-color: #0f172a; color: #ffffff; font-size: 0.75rem; font-weight: bold; padding: 6px 16px; border-top-right-radius: 11px; border-bottom-left-radius: 8px; }
        .plan-name { font-size: 1.3rem; font-weight: 700; color: #0f172a; margin-bottom: 4px; }
        .plan-macs { display: inline-block; font-size: 0.85rem; font-weight: 600; color: #0284c7; background-color: #e0f2fe; padding: 4px 10px; border-radius: 6px; margin-bottom: 12px; }
        .plan-price { font-size: 1.75rem; font-weight: 700; color: #0f172a; margin-bottom: 20px; }
        .plan-price span { font-size: 0.875rem; font-weight: 400; color: #64748b; }
        .features-list { list-style: none; margin-bottom: 25px; }
        .features-list li { display: flex; align-items: flex-start; font-size: 0.9rem; color: #334155; margin-bottom: 12px; line-height: 1.4; }
        .icon-check { color: #22c55e; font-weight: bold; margin-right: 10px; flex-shrink: 0; }
        .icon-diamond { color: #0284c7; margin-right: 10px; flex-shrink: 0; }
        .btn-select { width: 100%; background-color: #f8fafc; color: #1e293b; border: 1px solid #cbd5e1; padding: 12px; border-radius: 8px; font-size: 0.9rem; font-weight: 600; cursor: pointer; transition: background 0.2s; margin-bottom: 20px; }
        .btn-select:hover { background-color: #f1f5f9; }
        .btn-upgrade { background-color: #00796b; color: #ffffff; border: none; padding: 12px 24px; border-radius: 8px; font-size: 0.95rem; font-weight: 600; cursor: pointer; transition: background 0.2s; text-decoration: none; display: inline-block; }
        .btn-upgrade:hover { background-color: #004d40; }
        @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
    </style>
</head>
<body>

    <div class="container">
        <h2 class="header-title">Upgrade no Plano</h2>
        <p class="header-subtitle">Fazer Upgrade no meu plano atual.</p>

        <div class="tabs-container">
            <?php $first = true; foreach ($planos as $id => $plano): ?>
                <button class="tab-btn <?php echo $first ? 'active' : ''; ?>" onclick="switchPlan('<?php echo htmlspecialchars($id); ?>')">
                    <?php echo htmlspecialchars($plano['nome']); ?>
                </button>
            <?php $first = false; endforeach; ?>
        </div>

        <?php $first = true; foreach ($planos as $id => $plano): ?>
        <div id="<?php echo htmlspecialchars($id); ?>" class="plan-content <?php echo $first ? 'active' : ''; ?>">
            <div class="plan-card">
                <?php if (isset($plano['popular']) && $plano['popular']): ?>
                    <div class="badge-popular">Mais Popular</div>
                <?php endif; ?>
                
                <div class="plan-name"><?php echo htmlspecialchars($plano['nome']); ?></div>
                <div class="plan-macs">Permite: <?php echo htmlspecialchars($plano['macs']); ?></div>
                <div class="plan-price">R$<?php echo htmlspecialchars($plano['preco']); ?><span>/mês</span></div>
                
                <ul class="features-list">
                    <?php if(isset($plano['recursos']) && is_array($plano['recursos'])): ?>
                        <?php foreach ($plano['recursos'] as $recurso): ?>
                            <li><span class="icon-check">✓</span> <span class="icon-diamond">♦</span> <?php echo htmlspecialchars($recurso); ?></li>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </ul>

                <button class="btn-select" onclick="confirmSelection('<?php echo htmlspecialchars(addslashes($plano['nome'])); ?>')">Selecionar Plano</button>
            </div>
        </div>
        <?php $first = false; endforeach; ?>

        <div style="margin-top: 25px;">
            <button class="btn-upgrade" id="btn-final" onclick="executeUpgrade()">Fazer Upgrade</button>
        </div>
    </div>

    <script>
        let planoSelecionado = "<?php echo htmlspecialchars(addslashes(reset($planos)['nome'])); ?>";
        const whatsappNumero = "<?php echo htmlspecialchars($whatsapp_limpo); ?>";

        function switchPlan(planId) {
            document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
            document.querySelectorAll('.plan-content').forEach(content => content.classList.remove('active'));
            if(event && event.currentTarget) event.currentTarget.classList.add('active');
            
            const activeContent = document.getElementById(planId);
            if(activeContent) {
                activeContent.classList.add('active');
                planoSelecionado = activeContent.querySelector('.plan-name').innerText;
            }
        }

        function confirmSelection(nomePlano) {
            planoSelecionado = nomePlano;
            alert("Você selecionou o plano: " + nomePlano + ". Clique em 'Fazer Upgrade' abaixo para contratar.");
        }

        function executeUpgrade() {
            const textoMensagem = encodeURIComponent("Olá! Gostaria de fazer o upgrade para o **Plano " + planoSelecionado + "** no IBO Revenda.");
            const urlWhatsapp = "https://api.whatsapp.com/send?phone=" + whatsappNumero + "&text=" + textoMensagem;
            window.open(urlWhatsapp, '_blank');
        }
    </script>
</body>
</html>