<?php
session_start();
date_default_timezone_set('America/Sao_Paulo');


// ---------- AJAX: MUDAR MODO ----------
if (isset($_POST['ajax_change_mode'])) {
    $_SESSION['isGenerator'] = ($_POST['modo'] === 'gerador');
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['success' => true, 'isGenerator' => $_SESSION['isGenerator']]);
    exit;
}

// ---------- AJAX: SALVAR GATEWAY ----------
if (isset($_POST['ajax_salvar_gateway'])) {
    $_SESSION['amazon_gateway'] = $_POST['modo'] ?? 'zeroauth';
    echo json_encode(['success' => true, 'modo' => $_SESSION['amazon_gateway']]);
    exit;
}

// ---------- VARIÁVEIS ----------
$isGenerator = $_SESSION['isGenerator'] ?? false;
$amazonGateway = $_SESSION['amazon_gateway'] ?? 'zeroauth';
?>


<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>DIMITRI CENTER</title>
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css"/>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet"/>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"/>
    <style>
        :root {
            --bg: #0a0e17; --card: #111827; --text: #e2e8f0; --primary: #0d6efd;
            --primary-dark: #2563eb; --success: #10b981; --danger: #ef4444;
            --border: #1f2937; --shadow: rgba(0,0,0,0.6); --input-bg: #1f2937;
            --input-border: #374151;
        }
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { background: var(--bg); color: var(--text); font-family: 'Inter', sans-serif; min-height: 100vh; display: flex; flex-direction: column; }
        .container { max-width: 1300px; padding: 1.5rem; flex-grow: 1; }
        .card { background: var(--card); border: 1px solid var(--border); border-radius: 16px; box-shadow: 0 8px 32px var(--shadow); transition: all .3s ease; }
        .card:hover { transform: translateY(-6px); box-shadow: 0 16px 40px rgba(13,110,253,.2); }
        .card-body { padding: 2rem; }
        .title { color: var(--primary); font-weight: 700; font-size: 2rem; margin-bottom: 1.5rem; text-shadow: 0 0 10px rgba(13,110,253,.3); letter-spacing: -0.5px; }
        .subtitle { color: #94a3b8; font-size: 1.1rem; margin-bottom: 1.5rem; }
        .form-control, select, textarea {
            background: var(--input-bg); border: 1px solid var(--input-border); color: var(--text);
            border-radius: 12px; padding: .8rem 1rem; font-size: 1rem; transition: .3s;
        }
        .form-control:focus, select:focus, textarea:focus {
            border-color: var(--primary); box-shadow: 0 0 0 3px rgba(13,110,253,.2); outline: none;
        }
        .form-control::placeholder, textarea::placeholder { color: #64748b; }
        select {
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' fill='%2364748b' viewBox='0 0 16 16'%3E%3Cpath d='M7.247 11.14 2.451 5.658C1.885 5.013 2.345 4 3.204 4h9.592a1 1 0 0 1 .753 1.659l-4.796 5.48a1 1 0 0 1-1.506 0z'/%3E%3C/svg%3E");
            background-repeat: no-repeat; background-position: right 1rem center;
        }
        .btn {
            border-radius: 12px; font-weight: 600; padding: .8rem 1.6rem; transition: all .3s ease;
            text-transform: uppercase; font-size: .95rem; box-shadow: 0 4px 15px rgba(0,0,0,.3);
        }
        .btn-primary { background: var(--primary); border: none; }
        .btn-primary:hover { background: var(--primary-dark); transform: translateY(-2px); box-shadow: 0 8px 20px rgba(13,110,253,.4); }
        .btn-success { background: var(--success); border: none; }
        .btn-success:hover { background: #059669; transform: translateY(-2px); }
        .btn-danger { background: var(--danger); border: none; }
        .btn-danger:hover { background: #dc2626; transform: translateY(-2px); }
        .badge { background: #1f2937; color: var(--primary); padding: .5rem 1rem; border-radius: 8px; font-weight: 600; font-size: .9rem; border: 1px solid var(--primary); }
        .list-container { max-height: 380px; overflow-y: auto; padding: 1rem; background: #0f172a; border-radius: 12px; margin-top: 1rem; border: 1px solid var(--border); font-family: 'Courier New', monospace; font-size: .9rem; line-height: 1.7; color: #e2e8f0; }
        .list-container::-webkit-scrollbar { width: 8px; }
        .list-container::-webkit-scrollbar-track { background: #111827; border-radius: 4px; }
        .list-container::-webkit-scrollbar-thumb { background: var(--primary); border-radius: 4px; }
        .gateway-field { display: none; margin-top: 1rem; }
        .gateway-field.show { display: block; animation: fadeIn .4s; }
        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
        @media (max-width: 768px) { .title { font-size: 1.7rem; } .btn { width: 100%; margin-bottom: .5rem; } }
    </style>
</head>
<body>
<!-- 🔥 VERIFICAÇÃO DE ACESSO SIMULTÂNEO (ADICIONE ANTES DE FECHAR </body>) -->
<style>
/* Fundo escuro que cobre tudo */
#simultaneo-overlay {
    position: fixed;
    top: 0; left: 0;
    width: 100%; height: 100%;
    background: rgba(0,0,0,0.75);
    display: none;
    justify-content: center;
    align-items: center;
    z-index: 999999;
}

/* Caixa do aviso */
#simultaneo-box {
    background: #1a1a2e;
    padding: 35px 40px;
    border-radius: 14px;
    max-width: 420px;
    text-align: center;
    color: white;
    box-shadow: 0 0 25px rgba(0,0,0,0.4);
    border: 2px solid #ff4d4d;
    animation: popup .28s ease-out;
    font-family: 'Poppins', sans-serif;
}

/* Título */
#simultaneo-box h2 {
    font-size: 26px;
    margin-bottom: 15px;
    color: #ff4d4d;
}

/* Texto */
#simultaneo-box p {
    font-size: 15px;
    margin-bottom: 25px;
    opacity: 0.9;
    line-height: 1.5;
}

/* Botão */
#simultaneo-btn {
    padding: 12px 30px;
    font-size: 15px;
    font-weight: 600;
    background: #ff4d4d;
    color: white;
    border: none;
    border-radius: 8px;
    cursor: pointer;
    transition: .2s;
}

#simultaneo-btn:hover {
    background: #e63939;
}

/* Animação */
@keyframes popup {
    from { transform: scale(0.8); opacity: 0; }
    to { transform: scale(1); opacity: 1; }
}
</style>


    <div class="container mt-4">
        <div class="row justify-content-center">
            <div class="col-lg-11">
                <!-- CABEÇALHO -->
                <div class="card mb-4">
                    <div class="card-body text-center">
                        <h1 class="title">GG CENTER</h1>
                        <p class="subtitle">VALIDADOR + GERADOR AUTOMÁTICO — Insira apenas a base</p>
                        <textarea class="form-control text-center mb-4" id="lista-input" style="height:150px;" placeholder="Ex: 498431xxxxx|12|2027|456"></textarea>
                        <div class="row g-3">
                            <div class="col-md-6">
                                <select id="modo" class="form-select">
                                    <option value="" disabled <?= !isset($_SESSION['isGenerator']) ? 'selected' : '' ?>>Selecione o modo</option>
                                    <option value="validar" <?= !$isGenerator ? 'selected' : '' ?>>LISTA MANUAL</option>
                                    <option value="gerador" <?= $isGenerator ? 'selected' : '' ?>>Gerador Automático</option>
                                </select>
                            </div>
                            <div class="col-md-6">
                                <select id="modulo" class="form-select">
                                    <option value="" selected disabled>Selecione o GATEWAY</option>
                                    <option value="mod1">GATEWAY ccfull OFFLINE</option>
                                    <option value="mod2">GATEWAY credit gringa OFFLINE</option>
                                    <option value="mod3">GATEWAY BR OFFLINE</option>
                                    <option value="mod4">GATEWAY PARA GRINGA ON</option>
                                </select>
                            </div>
                        </div>
                        <!-- GATEWAY AMAZON -->
                        <div class="gateway-field" id="gateway-field">
                            <label class="form-label text-light">Gateway DEBITO GRINGA</label>
                            <select id="amazonSelect" class="form-select">
                                <option value="" selected disabled>Selecione uma opção</option>
                                <option value="zeroauth">ZERO AUTH (NÃO DEBITA)</option>
                                <option value="debitoeuro">DÉBITO EM EURO</option>
                                <option value="debitousd">DÉBITO EM DÓLAR USD</option>
                                <option value="debitoca">DÉBITO EM DÓLAR CANADENSE</option>
                                <option value="debitojp">DÉBITO EM DÓLAR USD V2 (AMAZON ONE) 1USD</option>
                            </select>
                        </div>
                        <div class="mt-4 d-flex gap-2 justify-content-center">
                            <button class="btn btn-success btn-executar flex-fill">EXECUTAR</button>
                            <button class="btn btn-danger btn-parar flex-fill" disabled>PARAR</button>
                        </div>
                    </div>
                </div>
                <!-- STATUS -->
                <div class="card mb-4">
                    <div class="card-body">
                        <h5 class="title">VÁLIDAS: <span class="badge float-end validas">0</span></h5><hr>
                        <h5 class="title">INVÁLIDAS: <span class="badge float-end invalidas">0</span></h5><hr>
                        <h5 class="title">PROCESSADAS: <span class="badge float-end processadas">0</span></h5><hr>
                        <h5 class="title mb-0">CARREGADAS: <span class="badge float-end carregadas">0</span></h5>
                    </div>
                </div>
                <!-- LISTAS -->
                <div class="row">
                    <div class="col-lg-6">
                        <div class="card mb-4">
                            <div class="card-body">
                                <div class="float-end">
                                    <button class="btn btn-primary btn-sm btn-mostrar-validas">Mostrar</button>
                                    <button class="btn btn-success btn-sm btn-copiar">Copiar</button>
                                    <button class="btn btn-danger btn-sm btn-limpar-validas">Limpar</button>
                                </div>
                                <h4 class="title mb-2">VÁLIDAS</h4>
                                <div class="list-container" id="lista_validas"></div>
                            </div>
                        </div>
                    </div>
                    <div class="col-lg-6">
                        <div class="card mb-4">
                            <div class="card-body">
                                <div class="float-end">
                                    <button class="btn btn-primary btn-sm btn-mostrar-invalidas">Mostrar</button>
                                    <button class="btn btn-danger btn-sm btn-limpar-invalidas">Limpar</button>
                                </div>
                                <h4 class="title mb-2">INVÁLIDAS</h4>
                                <div class="list-container" id="lista_invalidas" style="display:none;"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script>
        class Validador {
            constructor() {
                this.executando = false;
                this.requisicao = null;
                this.validas = 0; this.invalidas = 0; this.processadas = 0;
                this.audio = new Audio('audio.mp3');
                this.isGerador = false;
                this.currentGateway = 'zeroauth';
            }
            init() {
                this.bind();
                this.verificarModulo();
                this.carregarGateway();
            }
            bind() {
                $('#modo').on('change', () => this.mudarModo());
                $('#modulo').on('change', () => this.verificarModulo());
                $('#amazonSelect').on('change', () => {
                    const gateway = $('#amazonSelect').val();
                    if (gateway) {
                        this.currentGateway = gateway;
                        this.salvarGateway();
                    }
                });
                $('.btn-mostrar-validas').on('click', () => this.toggle('#lista_validas', '.btn-mostrar-validas'));
                $('.btn-mostrar-invalidas').on('click', () => this.toggle('#lista_invalidas', '.btn-mostrar-invalidas'));
                $('.btn-limpar-validas').on('click', () => this.limpar('#lista_validas', 'Válidas limpas!'));
                $('.btn-limpar-invalidas').on('click', () => this.limpar('#lista_invalidas', 'Inválidas limpas!'));
                $(`.btn-copiar`).on('click', () => this.copiar());
                $('.btn-executar').on('click', () => this.iniciar());
                $('.btn-parar').on('click', () => this.parar('manual'));
            }
            verificarModulo() {
                const modulo = $('#modulo').val();
                if (modulo === 'mod4') {
                    $('#gateway-field').addClass('show');
                } else {
                    $('#gateway-field').removeClass('show');
                }
                if (this.executando) this.parar('manual');
            }
            salvarGateway() {
                const gateway = $('#amazonSelect').val() || 'zeroauth';
                $.post('', { ajax_salvar_gateway: true, modo: gateway });
                this.currentGateway = gateway;
            }
            carregarGateway() {
                const saved = <?= json_encode($amazonGateway) ?>;
                if (saved && $('#amazonSelect option[value="' + saved + '"]').length) {
                    $('#amazonSelect').val(saved);
                    this.currentGateway = saved;
                } else {
                    $('#amazonSelect').val('zeroauth');
                    this.currentGateway = 'zeroauth';
                }
            }
            mudarModo() {
                const modo = $('#modo').val();
                this.isGerador = modo === 'gerador';
                $.post('', { ajax_change_mode: true, modo })
                    .done(() => this.toast('Modo alterado!', 'success'))
                    .fail(() => this.toast('Erro!', 'error'));
            }
            toggle(lista, botao) {
                $(lista).slideToggle();
                const $btn = $(botao);
                const icone = $btn.find('i').length ? ($btn.find('i').hasClass('fa-eye-slash') ? 'fa-eye' : 'fa-eye-slash') : 'fa-eye';
                $btn.html(`<i class="fa ${icone}"></i> ${$(lista).is(':visible') ? 'Esconder' : 'Mostrar'}`);
            }
            limpar(lista, msg) {
                $(lista).empty();
                this.toast(msg, 'success');
            }
            copiar() {
                navigator.clipboard.writeText($('#lista_validas').text()).then(() => this.toast('Copiado!', 'success'));
            }
            toast(msg, tipo) {
                Swal.fire({ title: msg, icon: tipo, toast: true, position: 'top-end', timer: 3000, showConfirmButton: false });
            }
            validarEntrada(lista, modulo, total) {
                if (!lista.trim()) return this.toast('Lista vazia!', 'error'), false;
                if (!modulo) return this.toast('Selecione um módulo!', 'warning'), false;
                if (modulo === 'mod4' && !$('#amazonSelect').val()) {
                    return this.toast('Selecione uma gateway Amazon!', 'warning'), false;
                }
                if (this.isGerador && total > 1) return this.toast('Apenas 1 linha!', 'warning'), false;
                if (!this.isGerador && total > 99999) return this.toast('Máx 99999 linhas!', 'warning'), false;
                return true;
            }
            getApi(modulo) {
                const apis = { 'mod1': 'api.php', 'mod2': 'api2.php', 'mod3': 'api3.php', 'mod4': 'api4.php' };
                return apis[modulo] || 'api.php';
            }
            iniciar() {
                if (this.executando) return;
                this.executando = true;
                const entrada = $('#lista-input').val().trim();
                const linhas = entrada.split('\n').filter(l => l.trim());
                const total = linhas.length;
                const modulo = $('#modulo').val();
                if (!this.validarEntrada(entrada, modulo, total)) {
                    this.executando = false;
                    return;
                }
                $('#lista-input').val(linhas.join('\n'));
                $('.carregadas').text(total);
                $('.btn-executar').prop('disabled', true);
                $('.btn-parar').prop('disabled', false);
                this.validas = this.invalidas = this.processadas = 0;
                this.atualizarContadores();
                this.toast('Iniciado!', 'success');
                this.processarLinha(linhas, 0, modulo, total);
            }

            // === FUNÇÃO CORRIGIDA: REMOVE LINHA DA TEXTAREA NO MODO MANUAL ===
            processarLinha(linhas, idx, modulo, total) {
                if (!this.executando || (!this.isGerador && idx >= total)) {
                    if (!this.isGerador && idx >= total) this.toast('Finalizado!', 'success');
                    this.finalizar();
                    return;
                }
                if (this.isGerador && idx >= total) idx = 0;

                const linhaAtual = linhas[idx];
                const dados = { lista: linhaAtual };
                if (modulo === 'mod4') {
                    dados.modo = this.currentGateway;
                }

                this.requisicao = $.post(this.getApi(modulo), dados)
                    .done(res => {
                        const isLive = /Aprovada|Live/i.test(res);
                        if (isLive) {
                            $('#lista_validas').append(res + '<br>');
                            this.validas++;
                            this.audio.play().catch(() => {});
                        } else {
                            $('#lista_invalidas').append(res + '<br>');
                            this.invalidas++;
                        }
                        this.processadas++;
                        this.atualizarContadores();

                        // === REMOÇÃO VISUAL NO MODO MANUAL ===
                        if (!this.isGerador) {
                            linhas.shift(); // Remove do array
                            const restantes = linhas.join('\n');
                            const $input = $('#lista-input');
                            $input.val(restantes);

                            // Scroll automático para o final
                            const textarea = $input[0];
                            textarea.scrollTop = textarea.scrollHeight;
                        }
                        // =====================================

                        setTimeout(() => {
                            if (this.executando) {
                                this.processarLinha(linhas, idx + 1, modulo, total);
                            }
                        }, 180);
                    })
                    .fail(() => {
                        this.toast('Erro na API!', 'error');
                        this.parar('erro');
                    });
            }
            // ==============================================================

            atualizarContadores() {
                $('.validas').text(this.validas);
                $('.invalidas').text(this.invalidas);
                $('.processadas').text(this.processadas);
            }
            parar(motivo) {
                if (this.requisicao) this.requisicao.abort();
                this.executando = false;
                $('.btn-executar').prop('disabled', false);
                $('.btn-parar').prop('disabled', true);
                this.toast(motivo === 'manual' ? 'Parado!' : 'Erro!', motivo === 'erro' ? 'error' : 'warning');
            }
            finalizar() {
                this.executando = false;
                $('.btn-executar').prop('disabled', false);
                $('.btn-parar').prop('disabled', true);
            }
        }
        $(() => {
            const validador = new Validador();
            validador.init();
        });
    </script>
</body>
</html>