<?php
require_once '../app/Controllers/sessions.php';
require_once '../app/Controllers/security_access.php';
require_once '../app/models/user.php';
require '../app/Controllers/updateProfile.php';
require_once '../app/Controllers/controller_investments.php';

?>
<!DOCTYPE html>
<html lang="en" class="dark">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Meu Perfil - <?= htmlspecialchars($stmtConfigsPlatformResult["name_platform"]) ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="./assets/css/build/tailwind.css" />
    <link href="https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/boxicons@2.1.4/css/boxicons.min.css" rel="stylesheet">

    <style>
        .spinner-ring {
            display: inline-block;
            width: 80px;
            height: 80px;
            border: 6px solid transparent;
            border-top-color: <?= htmlspecialchars($stmtConfigsPlatformResult["color_primary"]) ?>;
            /* azul Tailwind blue-600 */
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }

        button:hover,
        a:hover {
            opacity: .9;
        }

        @keyframes slideUp {
            from {
                transform: translateY(100%);
                opacity: 0;
            }

            to {
                transform: translateY(0);
                opacity: 1;
            }
        }

        .animate-slideUp {
            animation: slideUp 0.3s ease-out;
        }

        input:focus {
            border: 1px solid <?= htmlspecialchars($stmtConfigsPlatformResult["color_primary"]) ?>;
            outline: none;
        }

        button:hover {
            opacity: .9;
        }
    </style>
</head>

<body class="bg-gray-100 dark:bg-[#09090A] text-gray-900 dark:text-white font-poppins max-w-[600px] mx-auto">
    <?php include 'partials/menu-bottom.php'; ?>
    <div id="loading" class="fixed inset-0 flex items-center justify-center bg-white dark:bg-[#121214] z-50">
        <div class="spinner-ring"></div>
    </div>

    <?php if ($toastMessage) : ?>
        <?php if ($toastType === 'success') : ?>
            <div style="z-index:999"
                id="toast"
                class="fixed bottom-4 right-4 z-50 bg-green-600 text-white px-4 py-3 rounded-lg shadow-lg animate-slide-in flex items-center gap-2 w-[90%] max-w-sm">
                <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" />
                </svg>
                <span><?= htmlspecialchars($toastMessage) ?></span>
            </div>
        <?php elseif ($toastType === 'error') : ?>
            <div style="background-color: red;z-index:999"
                id="toast"
                class="fixed bottom-4 right-4 bg-red-600 text-white px-4 py-3 rounded-lg shadow-lg animate-slide-in flex items-center gap-2 w-[90%] max-w-sm">
                <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
                </svg>
                <span><?= htmlspecialchars($toastMessage) ?></span>
            </div>
        <?php endif; ?>
    <?php endif; ?>

    <header class="p-4 flex justify-between items-center shadow bg-white dark:bg-[#121214]">
        <h1 class="text-2xl font-bold">Stocks<span class="text-blue-500" style="color: <?= htmlspecialchars($stmtConfigsPlatformResult["color_primary"]) ?>;">Mission</span></h1>
        <a href="payment.php" class="text-sm border px-3 py-1 rounded dark:border-white border-gray-800 font-bold">
            R$ <?= htmlspecialchars(number_format($user['balance'], 2, ',', '.')) ?>
        </a>
    </header>

    <main class="p-6 bg-white dark:bg-[#09090A] min-h-screen">
        <section class="text-center my-6">
            <h2 class="text-3xl font-bold mb-1">Meu Perfil</h2>
            <p class="text-gray-600 dark:text-gray-400 text-sm">Gerencie suas informações de conta com segurança</p>
        </section>

        <section class="flex flex-col items-center justify-center mb-8">
            <div class="relative w-32 h-32 mb-4">
                <img id="profile-img-preview" src="<?= htmlspecialchars(($user['avatar'] === null ? 'https://www.diariodeinvestimentos.com.br/wp-content/uploads/2021/06/Qual-o-seu-perfil-de-investidor-e-as-aplicacoes-mais-adequadas-a-ele.jpg' : $archive . $user['avatar'])) ?>" alt="Foto de Perfil"
                    class="w-32 h-32 rounded-full object-cover border-4 border-blue-500" style="border: 4px solid <?= htmlspecialchars($stmtConfigsPlatformResult["color_primary"]) ?>;">
                <label style="background-color: <?= htmlspecialchars($stmtConfigsPlatformResult["color_primary"]) ?>;" for="profile-img"
                    class="absolute bottom-0 right-0 bg-blue-600 p-1 rounded-full cursor-pointer hover:bg-blue-700 transition">
                    <svg class="w-5 h-5 text-white" fill="currentColor" viewBox="0 0 20 20">
                        <path
                            d="M4 3a2 2 0 00-2 2v2h2V5h2V3H4zm10 0v2h2v2h2V5a2 2 0 00-2-2h-2zm2 12h-2v2h2a2 2 0 002-2v-2h-2v2zm-12 0H2v-2H0v2a2 2 0 002 2h2v-2z" />
                        <path fill-rule="evenodd"
                            d="M5 6a1 1 0 00-1 1v2H2v5h5l3 3 3-3h5V9h-2V7a1 1 0 00-1-1H5zm5 7a2 2 0 110-4 2 2 0 010 4z"
                            clip-rule="evenodd" />
                    </svg>
                </label>
                <form method="POST" enctype="multipart/form-data" id="form-upload">
                    <input name="profile-img" type="file" id="profile-img" accept="image/*" class="hidden" onchange="enviarAutomaticamente(this)">

                </form>
            </div>
            <p class="text-sm text-gray-500 dark:text-gray-400">Clique na imagem para alterar sua foto de perfil</p>
        </section>

        <div class="bg-white dark:bg-[#121214] mb-6 p-4 rounded-lg shadow space-y-3">
            <h2 class="text-lg font-bold mb-2 text-gray-800 dark:text-white">Ações Rápidas</h2>

            <ul class="space-y-3">

                <?php foreach ($stmtResultTransaction as $transaction) : ?>
                    <div class="bg-white dark:bg-[#1A1A1A] border border-gray-200 dark:border-gray-800 rounded-xl p-5 shadow hover:shadow-lg transition">
                        <div class="flex justify-between items-center mb-3">
                            <div>
                                <h2 class="text-xl font-semibold text-gray-800 dark:text-white">💰 R$ 50,00</h2>
                                <p class="text-sm text-gray-500 dark:text-gray-400">ID: 6857764f1573c03d8b9271d0</p>
                            </div>
                            <div class="flex items-center gap-2 px-3 py-1 rounded-full bg-yellow-500/10 text-yellow-400 font-medium text-sm animate-pulse">
                                ⏳ Aguardando
                            </div>
                        </div>
                        <div class="text-sm text-gray-600 dark:text-gray-300 space-y-1">
                            <p>📱 <strong>Telefone:</strong> (48) 99126-0529</p>
                            <p>📅 <strong>Data:</strong> 22/06/2025 00:19</p>
                        </div>
                        <div class="mt-4">
                            <a href="#" class="inline-flex items-center text-[#005E60] hover:underline text-sm">
                                🔗 Ver QR Code Pix
                            </a>
                        </div>
                    </div>

                <?php endforeach; ?>


                <!-- Saque -->
                <li>
                    <button onclick="abrirModalSaque()" class="flex w-full items-center gap-3 bg-gray-100 dark:bg-[#1E1E1E] hover:bg-gray-200 dark:hover:bg-[#2a2a2e] p-3 rounded-lg transition">
                        <i class='bx bx-wallet text-2xl text-green-500'></i>
                        <span class="font-semibold text-gray-800 dark:text-white">Saque</span>
                    </button>
                </li>

                <!-- Depósito -->
                <li>
                    <a href="payment.php" class="flex items-center gap-3 bg-gray-100 dark:bg-[#1E1E1E] hover:bg-gray-200 dark:hover:bg-[#2a2a2e] p-3 rounded-lg transition">
                        <i class='bx bx-credit-card text-2xl text-yellow-500'></i>
                        <span class="font-semibold text-gray-800 dark:text-white">Depósito</span>
                    </a>
                </li>

                <!-- Convidar -->
                <li>
                    <a href="team.php" class="flex items-center gap-3 bg-gray-100 dark:bg-[#1E1E1E] hover:bg-gray-200 dark:hover:bg-[#2a2a2e] p-3 rounded-lg transition">
                        <i class='bx bx-user-plus text-2xl text-purple-500'></i>
                        <span class="font-semibold text-gray-800 dark:text-white">Convidar Amigos</span>
                    </a>
                </li>
            </ul>
        </div>

        <div class="bg-white dark:bg-[#121214] p-4 rounded-lg shadow space-y-4">
            <div class="flex justify-between">
                <span class="text-gray-500 dark:text-gray-400">Telefone:</span>
                <strong class="text-right"><?= htmlspecialchars($user['phone']) ?></strong>
            </div>
            <div class="flex justify-between">
                <span class="text-gray-500 dark:text-gray-400">Nome:</span>
                <strong class="text-right">Não Definido.</strong>
            </div>
            <div class="flex justify-between">
                <span class="text-gray-500 dark:text-gray-400">E-mail:</span>
                <strong class="text-right">Não Definido.</strong>
            </div>
            <div class="flex justify-between">
                <span class="text-gray-500 dark:text-gray-400">CPF:</span>
                <strong class="text-right">Não Definido.</strong>
            </div>
            <div class="text-center pt-2">
                <button style="opacity: .5;background-color: <?= htmlspecialchars($stmtConfigsPlatformResult["color_primary"]) ?>" class="bg-blue-600 text-white px-4 py-2 text-sm rounded">Editar Dados</button>
            </div>
        </div>

        <div class="mt-8 bg-white dark:bg-[#121214] p-4 rounded-lg shadow">
            <h3 class="text-lg font-semibold mb-4">Alterar Senha</h3>
            <form method="POST" class="space-y-3">
                <div>
                    <label class="block text-sm mb-1" for="senha-atual">Senha Atual</label>
                    <input placeholder="Digite sua senha atual" minlength="6" name="actual_pass" type="password" id="senha-atual"
                        class="w-full p-2 rounded bg-gray-100 dark:bg-[#1E1E1E] border border-gray-300 dark:border-gray-600" />
                </div>
                <div>
                    <label class="block text-sm mb-1" for="nova-senha">Nova Senha</label>
                    <input placeholder="Digite sua nova senha" minlength="6" name="new_pass" type="password" id="nova-senha"
                        class="w-full p-2 rounded bg-gray-100 dark:bg-[#1E1E1E] border border-gray-300 dark:border-gray-600" />
                </div>
                <div>
                    <label class="block text-sm mb-1" for="confirmar-senha">Confirmar Nova Senha</label>
                    <input placeholder="Confirme sua nova senha" minlength="6" name="confirm_new_pass" type="password" id="confirmar-senha"
                        class="w-full p-2 rounded bg-gray-100 dark:bg-[#1E1E1E] border border-gray-300 dark:border-gray-600" />
                </div>
                <button name="alter_pass" type="submit" class="mt-3 w-full bg-blue-600 text-white py-2 rounded hover:bg-blue-700" style="background-color: <?= htmlspecialchars($stmtConfigsPlatformResult["color_primary"]) ?>;">Salvar
                    Nova Senha</button>
            </form>
        </div>

        <!-- MODAL -->
        <div id="modal-saque" class="fixed inset-0 z-50 hidden bg-black/50 backdrop-blur-sm flex items-end justify-center">
            <form method="POST"
                class="w-full max-w-[600px] bg-white dark:bg-[#121214] text-gray-900 dark:text-white rounded-t-2xl p-6 animate-slideUp">

                <div class="flex justify-between items-center mb-4">
                    <h2 class="text-lg font-bold">Solicitar Saque</h2>
                    <button type="button" onclick="fecharModalSaque()" class="text-gray-500 hover:text-red-500">
                        <i class="bx bx-x text-2xl"></i>
                    </button>
                </div>

                <div class="mb-4">
                    <label for="cpf" class="block text-sm mb-1">Chave CPF (PIX)</label>
                    <input id="cpf" name="cpf_withdrawal" type="text" required maxlength="14"
                        placeholder="000.000.000-00"
                        class="w-full p-2 border border-gray-300 dark:border-gray-600 rounded bg-gray-100 dark:bg-[#121214] text-gray-800 dark:text-white"
                        oninput="formatarCPF(this)">
                </div>

                <div class="mb-4">
                    <label for="valor" class="block text-sm mb-1">Valor a sacar</label>
                    <input id="valor" name="value_withdrawal" type="text" required
                        placeholder="R$ 0,00"
                        class="w-full p-2 border border-gray-300 dark:border-gray-600 rounded bg-gray-100 dark:bg-[#121214] text-gray-800 dark:text-white"
                        oninput="formatarMoeda(this)">
                </div>
                <p id="taxaInfo" class="text-sm mt-1 text-gray-600 dark:text-gray-400">Taxa (10%): R$ 0,00</p>


                <button name="send_withdrawal" style="background-color: <?= htmlspecialchars($stmtConfigsPlatformResult["color_primary"]) ?>;" type="submit" onclick="fecharModalSaque()"
                    class="w-full bg-green-600 hover:bg-green-700 text-white py-2 rounded font-semibold transition">
                    Solicitar Saque
                </button>
            </form>
        </div>

        <footer class="p-4 text-center text-sm text-gray-400 dark:text-gray-600 bg-white dark:bg-[#09090A]">
            © 2025 InvestPro. Todos os direitos reservados.
        </footer>

        <script>
            if (localStorage.getItem('theme') === 'dark') {
                document.documentElement.classList.add('dark');
            }

            function toggleDark() {
                const html = document.documentElement;
                html.classList.toggle('dark');
                localStorage.setItem('theme', html.classList.contains('dark') ? 'dark' : 'light');
            }

            function previewImage(event) {
                const reader = new FileReader();
                reader.onload = function() {
                    const output = document.getElementById('profile-img-preview');
                    output.src = reader.result;
                };
                if (event.target.files[0]) {
                    reader.readAsDataURL(event.target.files[0]);
                }
            }

            function enviarAutomaticamente(input) {
                const file = input.files[0];
                if (file) {
                    document.getElementById('form-upload').submit();
                }
            }

            const toast = document.getElementById("toast");

            if (toast) {
                toast.classList.add("opacity-0");
                toast.style.transition = "opacity 0.4s ease";

                setTimeout(() => {
                    toast.classList.remove("opacity-0");
                    toast.classList.add("opacity-100");
                }, 100);

                setTimeout(() => {
                    toast.classList.add("opacity-0");
                    setTimeout(() => toast.remove(), 400);
                }, 5000);
            }

            window.addEventListener('load', () => {
                document.getElementById('loading').style.display = 'none';
                document.getElementById('main-content').classList.remove('hidden');
            });

            function abrirModalSaque() {
                document.getElementById("modal-saque").classList.remove("hidden");
            }

            function fecharModalSaque() {
                document.getElementById("modal-saque").classList.add("hidden");
            }

            function formatarCPF(input) {
                let value = input.value.replace(/\D/g, '');
                if (value.length > 11) value = value.slice(0, 11);
                value = value.replace(/(\d{3})(\d)/, "$1.$2");
                value = value.replace(/(\d{3})(\d)/, "$1.$2");
                value = value.replace(/(\d{3})(\d{1,2})$/, "$1-$2");
                input.value = value;
            }

            function formatarMoeda(input) {
                let raw = input.value.replace(/\D/g, '');
                let valor = (parseInt(raw, 10) / 100).toFixed(2);

                // Formata com vírgula e pontos
                let formatado = valor.replace(".", ",").replace(/\B(?=(\d{3})+(?!\d))/g, ".");
                input.value = 'R$ ' + formatado;

                // Calcula a taxa
                let taxa = (valor * 0.10).toFixed(2);
                let taxaFormatada = taxa.replace(".", ",").replace(/\B(?=(\d{3})+(?!\d))/g, ".");

                // Atualiza o parágrafo com a taxa
                document.getElementById("taxaInfo").innerText = `Taxa (10%): R$ ${taxaFormatada}`;
            }

            document.querySelector("form").addEventListener("submit", function() {
                let input = document.querySelector("[name='value_visible']");
                let valor = input.value.replace(/\D/g, '');
                valor = (parseInt(valor, 10) / 100).toFixed(2);
                document.getElementById("value_withdrawal").value = valor; // envia como 1234.56
            });
        </script>

</body>

</html>