<?php
/**
 * Página de Perfil do Cliente - conta.php (Versão Final Corrigida)
 */

error_reporting(E_ALL);
ini_set('display_errors', 0);

$idParceiro = isset($_GET['id']) ? (string)$_GET['id'] : '';
$base_path = __DIR__ . '/data/';
$parceiros_file = $base_path . 'parceiros.json';
$clientes_file  = $base_path . 'clientes.json';
$recargas_file  = $base_path . 'recargas.json';

function load_json_data($file) {
    if (!file_exists($file)) return [];
    $content = file_get_contents($file);
    return json_decode($content, true) ?: [];
}

function save_json_data($file, $data) {
    if (!is_dir(dirname($file))) {
        mkdir(dirname($file), 0755, true);
    }
    file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}

$parceiros = load_json_data($parceiros_file);
$parceiro = null;
foreach($parceiros as $p){
    if((string)($p['id'] ?? '') === $idParceiro){
        $parceiro = $p;
        break;
    }
}

if(!$parceiro) {
    $parceiro = ['nome' => 'Loja Parceira', 'cor_primaria' => '#2563eb', 'token' => ''];
}

// API Interna
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');
    $clientes = load_json_data($clientes_file);

    if ($_POST['action'] === 'editar_perfil') {
        $idCliente = $_POST['id_cliente'] ?? '';
        foreach ($clientes as &$c) {
            if ($c['id'] === $idCliente) {
                $c['nome'] = $_POST['nome'] ?? $c['nome'];
                $c['email'] = $_POST['email'] ?? $c['email'];
                if(!empty($_POST['senha'])) $c['senha'] = $_POST['senha'];
                $c['whatsapp'] = $_POST['whatsapp'] ?? $c['whatsapp'];
                save_json_data($clientes_file, $clientes);
                echo json_encode(['success' => true, 'cliente' => $c]);
                exit;
            }
        }
        echo json_encode(['success' => false, 'message' => 'Cliente não encontrado.']);
        exit;
    }

    if ($_POST['action'] === 'gerar_recarga') {
        $idCliente = $_POST['id_cliente'] ?? '';
        $valor = (float)($_POST['valor'] ?? 0);
        if ($valor < 1) { echo json_encode(['success' => false, 'message' => 'Valor mínimo R$ 1,00.']); exit; }

        $recargas = load_json_data($recargas_file);
        $recId = "rec" . date('YmdHis') . rand(100, 999);
        
        $novaRecarga = [
            "id" => $recId,
            "id_parceiro" => $idParceiro,
            "id_cliente" => $idCliente,
            "valor" => $valor,
            "status" => "pendente",
            "data" => date('c')
        ];
        $recargas[] = $novaRecarga;
        save_json_data($recargas_file, $recargas);

        $protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https" : "http";
        $host = $_SERVER['HTTP_HOST'];
        $webhookUrl = "$protocol://$host/webhook.php";

        $ch = curl_init('https://api.pushinpay.com.br/api/pix/cashIn');
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
            "value" => (int)round($valor * 100),
            "webhook_url" => $webhookUrl,
            "external_id" => $recId
        ]));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . ($parceiro['token'] ?? ''),
            'Accept: application/json',
            'Content-Type: application/json'
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);
        
        $pixData = json_decode($response, true);
        echo json_encode(['success' => true, 'rec_id' => $recId, 'pix' => $pixData]);
        exit;
    }

    if ($_POST['action'] === 'verificar_recarga') {
        $recId = $_POST['rec_id'];
        $recargas = load_json_data($recargas_file);
        foreach ($recargas as $r) {
            if ($r['id'] === $recId) {
                echo json_encode(['status' => $r['status']]);
                exit;
            }
        }
        echo json_encode(['status' => 'nao_encontrado']);
        exit;
    }

    if ($_POST['action'] === 'cancelar_recarga') {
        $recId = $_POST['rec_id'];
        $recargas = load_json_data($recargas_file);
        foreach ($recargas as &$r) {
            if ($r['id'] === $recId && $r['status'] === 'pendente') {
                $r['status'] = 'cancelado';
                save_json_data($recargas_file, $recargas);
                echo json_encode(['success' => true]);
                exit;
            }
        }
        echo json_encode(['success' => false]);
        exit;
    }

    if ($_POST['action'] === 'get_cliente') {
        $idCliente = $_POST['id_cliente'];
        foreach ($clientes as $c) {
            if ($c['id'] === $idCliente) {
                echo json_encode(['success' => true, 'cliente' => $c]);
                exit;
            }
        }
        echo json_encode(['success' => false]);
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Minha Conta | <?= htmlspecialchars($parceiro['nome']) ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800;900&display=swap" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://unpkg.com/@phosphor-icons/web"></script>
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: { primary: '<?= $parceiro['cor_primaria'] ?? "#2563eb" ?>' },
                    fontFamily: { sans: ['Inter', 'sans-serif'] }
                }
            }
        }
    </script>
    <style>
        :root { --p-color: <?= $parceiro['cor_primaria'] ?? "#2563eb" ?>; }
        body { background-color: #f8fafc; color: #1e293b; }
        .btn-primary { background-color: var(--p-color); color: #fff !important; transition: all 0.3s; }
        .btn-primary:hover { opacity: 0.9; transform: translateY(-1px); }
        .card-dash { background: #fff; border: 1px solid #e2e8f0; border-radius: 24px; transition: all 0.3s; }
        .card-dash:hover { border-color: var(--p-color); transform: translateY(-2px); }
        .input-profile { width: 100%; padding: 12px; border-radius: 10px; border: 1px solid #e2e8f0; outline: none; font-size: 14px; }
        .input-profile:focus { border-color: var(--p-color); }
        .pix-container { background: #fff; border-radius: 16px; padding: 20px; text-align: center; }
        .copy-box { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 10px; font-family: monospace; font-size: 11px; word-break: break-all; margin: 15px 0; }
    </style>
</head>
<body class="min-h-screen flex flex-col">

<?php include 'includes/menu.php'; ?>

<main class="max-w-5xl mx-auto px-4 py-12 w-full">
    <div id="authCheck" class="hidden">
        <div class="bg-white rounded-3xl shadow-sm border border-slate-100 p-16 text-center">
            <i class="ph ph-lock-key text-6xl text-slate-200 mb-6"></i>
            <h2 class="text-2xl font-black text-slate-800 mb-2 uppercase">Acesso Restrito</h2>
            <p class="text-slate-500 text-sm mb-8">Faça login para gerenciar sua conta.</p>
            <a href="carrinho.php?id=<?= $idParceiro ?>" class="btn-primary px-10 py-4 rounded-2xl font-bold text-xs uppercase tracking-widest inline-block">Entrar na Conta</a>
        </div>
    </div>

    <div id="contentView" class="hidden space-y-10">
        <div class="flex flex-col md:flex-row md:items-end justify-between gap-6">
            <div>
                <h1 class="text-4xl font-black text-slate-900 tracking-tighter uppercase italic leading-none">Minha Conta</h1>
                <p class="text-slate-500 text-sm mt-2">Olá, <span id="welcomeNome" class="font-bold text-primary"></span>! Gerencie seu perfil e adicione saldo.</p>
            </div>
            <button onclick="logout()" class="text-[10px] font-black text-red-500 border border-red-100 px-4 py-2 rounded-xl hover:bg-red-50 transition-all uppercase tracking-widest">Sair da Conta</button>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-12 gap-6">
            <div class="md:col-span-5 space-y-6">
                <div class="bg-slate-900 p-8 rounded-[32px] shadow-2xl shadow-slate-200 text-white relative overflow-hidden flex flex-col justify-between min-h-[200px]">
                    <div class="relative z-10">
                        <p class="text-[10px] font-black uppercase opacity-50 tracking-widest mb-1">Saldo Disponível</p>
                        <h2 id="displaySaldo" class="text-4xl font-black tracking-tighter">R$ 0,00</h2>
                    </div>
                    <i class="ph ph-wallet absolute -right-6 -bottom-6 text-9xl opacity-5"></i>
                </div>
                <div class="card-dash p-6">
                    <h3 class="font-black text-slate-800 mb-4 flex items-center gap-2 text-xs uppercase tracking-wider">
                        <i class="ph-bold ph-plus-circle text-primary text-lg"></i> Adicionar Saldo (Pix)
                    </h3>
                    <div class="space-y-4">
                        <div class="relative">
                            <span class="absolute left-4 top-1/2 -translate-y-1/2 text-slate-400 font-black text-sm">R$</span>
                            <input type="number" id="valorRecarga" class="input-profile pl-12 font-bold" placeholder="0,00" step="0.01">
                        </div>
                        <button onclick="gerarRecarga()" class="btn-primary w-full py-4 rounded-2xl font-black text-[10px] uppercase tracking-widest">
                            Gerar Pix Agora
                        </button>
                    </div>
                </div>
            </div>
            <div class="md:col-span-7 grid grid-cols-1 sm:grid-cols-2 gap-6">
                <a href="downloads.php?id=<?= $idParceiro ?>" class="card-dash p-8 flex flex-col justify-between min-h-[200px] group">
                    <div class="w-14 h-14 bg-slate-50 rounded-2xl flex items-center justify-center text-slate-400 group-hover:text-primary transition-colors">
                        <i class="ph ph-download-simple text-3xl"></i>
                    </div>
                    <div>
                        <h3 class="text-xl font-black text-slate-800 uppercase tracking-tighter">Meus Downloads</h3>
                        <p class="text-xs text-slate-400 mt-1">Acesse seus produtos adquiridos.</p>
                    </div>
                </a>
                <a href="pagamentos.php?id=<?= $idParceiro ?>" class="card-dash p-8 flex flex-col justify-between min-h-[200px] group">
                    <div class="w-14 h-14 bg-slate-50 rounded-2xl flex items-center justify-center text-slate-400 group-hover:text-primary transition-colors">
                        <i class="ph ph-receipt text-3xl"></i>
                    </div>
                    <div>
                        <h3 class="text-xl font-black text-slate-800 uppercase tracking-tighter">Pagamentos</h3>
                        <p class="text-xs text-slate-400 mt-1">Histórico de transações.</p>
                    </div>
                </a>
            </div>
        </div>

        <div class="bg-white border border-slate-100 rounded-[32px] p-8 md:p-12">
            <h3 class="font-black text-slate-800 mb-10 flex items-center gap-3 text-sm uppercase tracking-widest">
                <i class="ph-bold ph-user-gear text-primary text-xl"></i> Configurações de Perfil
            </h3>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-8 mb-10">
                <div class="space-y-2">
                    <label class="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-1">Nome Completo</label>
                    <input type="text" id="editNome" class="input-profile" placeholder="Seu nome">
                </div>
                <div class="space-y-2">
                    <label class="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-1">E-mail</label>
                    <input type="email" id="editEmail" class="input-profile" placeholder="seu@email.com">
                </div>
                <div class="space-y-2">
                    <label class="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-1">WhatsApp</label>
                    <input type="text" id="editWhatsapp" class="input-profile" placeholder="(00) 00000-0000">
                </div>
                <div class="space-y-2">
                    <label class="text-[10px] font-black text-slate-400 uppercase tracking-widest ml-1">Nova Senha (deixe em branco para manter)</label>
                    <input type="password" id="editSenha" class="input-profile" placeholder="********">
                </div>
            </div>
            <div class="flex justify-end">
                <button onclick="salvarPerfil()" class="btn-primary px-12 py-4 rounded-2xl font-black text-[10px] uppercase tracking-widest shadow-xl shadow-primary/20">
                    Salvar Alterações
                </button>
            </div>
        </div>
    </div>
</main>

<script>
    const idParceiro = '<?= $idParceiro ?>';
    let clienteLogado = JSON.parse(localStorage.getItem('cliente_logado_' + idParceiro));

    function checkAuth() {
        if (!clienteLogado) {
            document.getElementById('authCheck').classList.remove('hidden');
            document.getElementById('contentView').classList.add('hidden');
        } else {
            document.getElementById('authCheck').classList.add('hidden');
            document.getElementById('contentView').classList.remove('hidden');
            loadClienteData();
        }
    }

    function loadClienteData() {
        const formData = new FormData();
        formData.append('action', 'get_cliente');
        formData.append('id_cliente', clienteLogado.id);
        fetch('conta.php?id=' + idParceiro, { method: 'POST', body: formData }).then(r => r.json()).then(data => {
            if (data.success) {
                clienteLogado = data.cliente;
                localStorage.setItem('cliente_logado_' + idParceiro, JSON.stringify(clienteLogado));
                document.getElementById('welcomeNome').innerText = clienteLogado.nome;
                document.getElementById('displaySaldo').innerText = `R$ ${parseFloat(clienteLogado.saldo).toLocaleString('pt-BR', {minimumFractionDigits: 2})}`;
                document.getElementById('editNome').value = clienteLogado.nome;
                document.getElementById('editEmail').value = clienteLogado.email;
                document.getElementById('editWhatsapp').value = clienteLogado.whatsapp || '';
            }
        });
    }

    function salvarPerfil() {
        const formData = new FormData();
        formData.append('action', 'editar_perfil');
        formData.append('id_cliente', clienteLogado.id);
        formData.append('nome', document.getElementById('editNome').value);
        formData.append('email', document.getElementById('editEmail').value);
        formData.append('whatsapp', document.getElementById('editWhatsapp').value);
        formData.append('senha', document.getElementById('editSenha').value);
        Swal.fire({ title: 'Salvando...', allowOutsideClick: false, didOpen: () => Swal.showLoading() });
        fetch('conta.php?id=' + idParceiro, { method: 'POST', body: formData }).then(r => r.json()).then(data => {
            Swal.close();
            if (data.success) {
                clienteLogado = data.cliente;
                localStorage.setItem('cliente_logado_' + idParceiro, JSON.stringify(clienteLogado));
                Swal.fire('Sucesso', 'Perfil atualizado com sucesso!', 'success');
                document.getElementById('welcomeNome').innerText = clienteLogado.nome;
            } else { Swal.fire('Erro', data.message, 'error'); }
        });
    }

    function gerarRecarga() {
        const valor = document.getElementById('valorRecarga').value;
        if (!valor || valor < 1) return Swal.fire('Erro', 'Valor mínimo R$ 1,00', 'error');
        const formData = new FormData();
        formData.append('action', 'gerar_recarga');
        formData.append('id_cliente', clienteLogado.id);
        formData.append('valor', valor);
        Swal.fire({ title: 'Gerando Pix...', allowOutsideClick: false, didOpen: () => Swal.showLoading() });
        fetch('conta.php?id=' + idParceiro, { method: 'POST', body: formData }).then(r => r.json()).then(data => {
            Swal.close();
            if (data.success) { showPixModal(data.pix, data.rec_id); }
            else { Swal.fire('Erro', data.message, 'error'); }
        });
    }

    function showPixModal(pix, recId) {
        if (!pix || !pix.qr_code_base64) return Swal.fire('Erro', 'Erro ao gerar Pix', 'error');
        let base64Data = pix.qr_code_base64.replace(/^data:image\/[a-z]+;base64,/, "").replace(/\s/g, "");
        Swal.fire({
            title: 'Pagamento via Pix',
            html: `
                <div class="pix-container">
                    <div class="bg-white p-2 inline-block rounded-xl border border-slate-100 mb-4">
                        <img src="data:image/png;base64,${base64Data}" class="mx-auto w-48 h-48" style="display: block;">
                    </div>
                    <p class="text-xs text-slate-500 mb-2">Copie o código abaixo para pagar:</p>
                    <div class="copy-box" id="pixCode">${pix.qr_code}</div>
                    <div class="grid grid-cols-1 gap-2">
                        <button onclick="copyPix()" class="btn-primary px-6 py-3 rounded-lg text-xs font-bold uppercase">COPIAR CÓDIGO</button>
                        <button onclick="cancelarRecarga('${recId}')" class="bg-slate-100 text-slate-500 px-6 py-3 rounded-lg text-[10px] font-bold uppercase">CANCELAR RECARGA</button>
                    </div>
                    <div class="mt-6 flex items-center justify-center gap-2 text-primary font-bold animate-pulse">
                        <i class="ph ph-clock"></i> <span class="text-xs uppercase">Aguardando pagamento...</span>
                    </div>
                </div>
            `,
            showConfirmButton: false,
            allowOutsideClick: false
        });
        const interval = setInterval(() => {
            const checkData = new FormData();
            checkData.append('action', 'verificar_recarga');
            checkData.append('rec_id', recId);
            
            fetch('conta.php?id=' + idParceiro, { method: 'POST', body: checkData })
            .then(r => r.json())
            .then(data => {
                if (data.status === 'pago') {
                    clearInterval(interval);
                    Swal.close();
                    setTimeout(() => {
                        Swal.fire({ 
                            title: 'SALDO ADICIONADO!', 
                            text: 'Sua recarga foi confirmada com sucesso.', 
                            icon: 'success', 
                            confirmButtonText: 'OK' 
                        }).then(() => { loadClienteData(); });
                    }, 500);
                }
            });
        }, 3000);
        window.recInterval = interval;
    }

    function cancelarRecarga(recId) {
        const formData = new FormData();
        formData.append('action', 'cancelar_recarga');
        formData.append('rec_id', recId);
        fetch('conta.php?id=' + idParceiro, { method: 'POST', body: formData }).then(r => r.json()).then(data => {
            if (data.success) {
                if(window.recInterval) clearInterval(window.recInterval);
                Swal.fire('Cancelado', 'Sua recarga foi cancelada.', 'info');
            }
        });
    }

    window.copyPix = () => {
        const text = document.getElementById('pixCode').innerText;
        const el = document.createElement('textarea');
        el.value = text; document.body.appendChild(el); el.select(); document.execCommand('copy'); document.body.removeChild(el);
        Swal.showValidationMessage('Código copiado!');
        setTimeout(() => { Swal.resetValidationMessage(); }, 2000);
    };

    function logout() { localStorage.removeItem('cliente_logado_' + idParceiro); window.location.reload(); }
    checkAuth();
</script>
</body>
</html>
