<?php
// resellers.php - Visualização Corrigida (Nome do Criador)
header('Content-Type: text/html; charset=utf-8');
session_start();
require_once 'includes/db.php';

if (!isset($_SESSION['logged_in_fxtream'])) { header('Location: index.php'); exit; }

$is_admin = (($_SESSION['role'] ?? '') === 'admin');
$user_id = $_SESSION['user_id'];
$user_name = $_SESSION['username'];

// Busca créditos
$user_credits = "∞";
if (!$is_admin) {
    $stmt = $pdo->prepare("SELECT credits FROM revendedores WHERE id = ?");
    $stmt->execute([$user_id]);
    $user_credits = $stmt->fetchColumn();
    if($user_credits === false) $user_credits = 0;
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Gerenciar Revendas</title>
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
    
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/style.css">
    <link rel="stylesheet" href="https://vendedorp2p.com/views/_css/dark-theme.css">
    
    <style>
        body { background-color: #1a1c23; color: #fff; overflow-x: hidden; font-family: 'Segoe UI', sans-serif; }
        .card { background-color: #232730; border: 1px solid #333; }
        .table { color: #ddd; }
        .table td, .table th { vertical-align: middle; border-top: 1px solid #333; }
        .form-control { background-color: #1a1c23; border: 1px solid #444; color: white; }
        .form-control:focus { background-color: #1a1c23; color: white; border-color: #007bff; }
        
        #shareText { background: #111; color: #00ff00; padding: 15px; border-radius: 8px; font-size: 13px; white-space: pre-wrap; font-family: monospace; border: 1px solid #444; }

        @media (min-width: 992px) {
            #sidebar { display: block !important; width: 240px; position: fixed; top: 0; left: 0; height: 100vh; z-index: 1000; overflow-y: auto; }
            .right-column { margin-left: 240px; width: calc(100% - 240px); padding: 0; }
            .btn-voltar-mobile { display: none; }
        }
        @media (max-width: 991px) {
            #sidebar { display: none !important; }
            .right-column { margin-left: 0 !important; width: 100% !important; padding: 0; }
            .btn-voltar-mobile { display: inline-block; margin-right: 10px; color: #fff; font-size: 1.2rem; }
        }
        
        .page-header { padding: 15px 20px; border-bottom: 1px solid #333; margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; background-color: #1a1c23; }
        .modal-content { background-color: #232730; border: 1px solid #444; }
    </style>
</head>
<body>

<div class="container-fluid p-0">
    <div class="row no-gutters">
        
        <?php include 'includes/sidebar.php'; ?>

        <div class="right-column">

            <div class="page-header sticky-top">
                <div class="d-flex align-items-center">
                    <a href="dashboard.php" class="btn-voltar-mobile"><i class="fa fa-arrow-left"></i></a>
                    <h4 class="mb-0 font-weight-bold text-white"><i class="fa fa-users text-info mr-2"></i> Revendas</h4>
                </div>
                <div class="d-flex align-items-center">
                    <span class="badge badge-success px-3 py-2 border border-success mr-3 d-none d-sm-inline-block">Créditos: <?php echo $user_credits; ?></span>
                    <div class="dropdown">
                        <a class="nav-link dropdown-toggle text-white font-weight-bold p-0 d-flex align-items-center" href="#" data-toggle="dropdown">
                            <span class="mr-2 d-none d-sm-inline"><?php echo htmlspecialchars($user_name); ?></span>
                            <img src="https://ui-avatars.com/api/?name=<?php echo urlencode($user_name); ?>&background=0D8ABC&color=fff&rounded=true" width="35" height="35">
                        </a>
                        <div class="dropdown-menu dropdown-menu-right bg-dark border-secondary">
                            <a class="dropdown-item text-white" href="logout.php"><i class="fa fa-power-off mr-2 text-danger"></i> Sair</a>
                        </div>
                    </div>
                </div>
            </div>

            <div class="container-fluid px-4 pb-5">
                
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h5 class="m-0 text-muted"><?php echo $is_admin ? 'Todas as Revendas' : 'Meus Revendedores'; ?></h5>
                    <button class="btn btn-success font-weight-bold shadow-sm" onclick="openModal()">
                        <i class="fa fa-plus-circle"></i> <span class="d-none d-sm-inline">Nova Revenda</span>
                    </button>
                </div>

                <div class="card shadow">
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-hover mb-0">
                                <thead class="bg-secondary text-white">
                                    <tr>
                                        <th class="pl-4">Login</th>
                                        <th>Email</th>
                                        <th class="text-center">Créditos</th>
                                        <th class="text-center">Status</th>
                                        <?php if($is_admin): ?><th class="text-center">Criado Por</th><?php endif; ?>
                                        <th class="text-right pr-4">Ações</th>
                                    </tr>
                                </thead>
                                <tbody id="resellerTable">
                                    <tr><td colspan="6" class="text-center py-5"><i class="fa fa-circle-notch fa-spin fa-3x text-muted"></i></td></tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="resModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content shadow-lg">
            <div class="modal-header border-secondary">
                <h5 class="modal-title font-weight-bold" id="modalTitle">Nova Revenda</h5>
                <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="editId">
                <div class="form-group">
                    <label>Login</label>
                    <input type="text" class="form-control" id="resUser" required>
                </div>
                <div class="form-group">
                    <label>Email</label>
                    <input type="email" class="form-control" id="resEmail">
                </div>
                <div class="form-group">
                    <label>Senha <small class="text-muted" id="passHelp">(Obrigatório)</small></label>
                    <input type="text" class="form-control" id="resPass">
                </div>
                <div class="form-group" id="groupCreditsInitial">
                    <label>Créditos Iniciais</label>
                    <input type="number" class="form-control" id="resCredits" value="0">
                </div>
            </div>
            <div class="modal-footer border-secondary">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
                <button type="button" class="btn btn-primary font-weight-bold px-4" onclick="saveReseller()">Salvar</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="creditModal" tabindex="-1">
    <div class="modal-dialog modal-sm modal-dialog-centered">
        <div class="modal-content border-warning shadow-lg">
            <div class="modal-header border-secondary bg-warning text-dark">
                <h5 class="modal-title font-weight-bold"><i class="fa fa-coins"></i> Saldo</h5>
                <button type="button" class="close text-dark" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="creditTargetId">
                <p class="text-center mb-3">Revenda: <b id="creditTargetName" class="text-warning">...</b></p>
                <div class="form-group">
                    <label>Ação</label>
                    <select class="form-control" id="creditType">
                        <option value="add">Adicionar (+)</option>
                        <option value="remove">Remover (-)</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Quantidade</label>
                    <input type="number" class="form-control font-weight-bold text-center" id="creditAmount" value="1" min="1" style="font-size: 1.5em;">
                </div>
            </div>
            <div class="modal-footer border-secondary">
                <button type="button" class="btn btn-block btn-warning font-weight-bold" onclick="processCredits()">CONFIRMAR</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalShare" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content border-info shadow-lg">
            <div class="modal-header border-secondary bg-info text-white">
                <h5 class="modal-title font-weight-bold"><i class="fab fa-whatsapp"></i> Enviar Mensagem</h5>
                <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body" id="shareModalBody">
                <div id="shareText">Carregando...</div>
                <div class="mt-3 text-right">
                    <button class="btn btn-outline-light mr-2" id="btnCopy" onclick="copyShareText()"><i class="fa fa-copy"></i> Copiar</button>
                    <a href="#" id="btnZap" target="_blank" class="btn btn-success font-weight-bold"><i class="fab fa-whatsapp"></i> Enviar WhatsApp</a>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>

<script>
    // PASSA AS VARIÁVEIS PHP PARA O JAVASCRIPT
    var currentUserId = <?php echo $user_id; ?>;
    var currentUserName = "<?php echo htmlspecialchars($user_name); ?>";

    $(document).ready(function() { loadResellers(); });

    function loadResellers() {
        $.post('api/resellers_api.php', { action: 'list' }, function(data) {
            let html = '';
            if(!data || data.length === 0) html = '<tr><td colspan="6" class="text-center text-muted py-5"><h5>Nenhum revendedor encontrado.</h5></td></tr>';
            else {
                data.forEach(r => {
                    let statusBadge = r.active == 1 ? '<span class="badge badge-success px-2">Ativo</span>' : '<span class="badge badge-danger px-2">Inativo</span>';
                    
                    // --- LÓGICA CORRIGIDA E BLINDADA PARA O NOME ---
                    let creatorLabel = '';

                    if (r.parent_name) {
                        // Se a API mandou o nome, usa ele
                        creatorLabel = r.parent_name;
                    } else {
                        // Se não mandou, vamos adivinhar pelo ID
                        if (r.parent_id == 0 || r.parent_id == null) {
                            creatorLabel = 'Admin';
                        } else if (r.parent_id == currentUserId) {
                            creatorLabel = currentUserName; // Mostra o nome de quem tá logado se for ele
                        } else if (r.parent_id == 1) {
                            creatorLabel = 'Admin'; // Admin geralmente é ID 1
                        } else {
                            creatorLabel = 'ID ' + r.parent_id;
                        }
                    }

                    // Monta o HTML do badge
                    let creator = `<span class="badge badge-info">${creatorLabel}</span>`;
                    if (creatorLabel === 'Admin') creator = '<span class="badge badge-warning text-dark">Admin</span>';
                    // ---------------------------------------------------

                    let adminCol = '<?php echo $is_admin ? "1" : "0"; ?>' == '1' ? `<td class="text-center">${creator}</td>` : '';
                    
                    html += `<tr>
                        <td class="font-weight-bold pl-4">${r.username}</td>
                        <td class="text-muted small">${r.email||'-'}</td>
                        <td class="text-center"><span class="badge badge-light border px-3 py-1" style="font-size:1em; color:#000;">${r.credits}</span></td>
                        <td class="text-center">${statusBadge}</td>
                        ${adminCol}
                        <td class="text-right pr-4">
                            <button class="btn btn-sm btn-success mr-1" onclick="openCreditModal(${r.id}, '${r.username}')" title="Gerenciar Créditos"><i class="fa fa-dollar-sign"></i></button>
                            <button class="btn btn-sm btn-info mr-1" onclick="editReseller(${r.id}, '${r.username}', '${r.email}')" title="Editar"><i class="fa fa-pen"></i></button>
                            <button class="btn btn-sm btn-danger" onclick="delReseller(${r.id})" title="Excluir"><i class="fa fa-trash"></i></button>
                        </td>
                    </tr>`;
                });
            }
            $('#resellerTable').html(html);
        }, 'json');
    }

    function openModal() {
        $('#editId').val(''); $('#resUser').val(''); $('#resEmail').val(''); $('#resPass').val(''); $('#resCredits').val('0');
        $('#modalTitle').text('Nova Revenda'); $('#groupCreditsInitial').show(); $('#passHelp').text('(Obrigatório)');
        $('#resModal').modal('show');
    }

    function editReseller(id, user, email) {
        $('#editId').val(id); $('#resUser').val(user); $('#resEmail').val(email && email != 'null' ? email : ''); $('#resPass').val('');
        $('#modalTitle').text('Editar Revenda'); $('#groupCreditsInitial').hide(); $('#passHelp').text('(Opcional)');
        $('#resModal').modal('show');
    }

    function saveReseller() {
        if(!$('#resUser').val()) { toastr.warning('Digite o login.'); return; }
        
        let isNew = !$('#editId').val();

        $.post('api/resellers_api.php', {
            action: 'save',
            id: $('#editId').val(),
            username: $('#resUser').val(),
            email: $('#resEmail').val(),
            password: $('#resPass').val(),
            credits: $('#resCredits').val()
        }, function(res) {
            if(res.status) {
                toastr.success(res.msg);
                $('#resModal').modal('hide');
                loadResellers();
                
                if(isNew && res.new_reseller) {
                    let nr = res.new_reseller;
                    let txt = `Seja bem-vindo(a) à Top IPTV! 🚀\n\n`;
                    txt += `Seguem seus dados de acesso ao painel de revenda:\n\n`;
                    txt += `🔗 Link do Painel: ${nr.url}\n`;
                    txt += `👤 Usuário: ${nr.username}\n`;
                    txt += `🔑 Senha: ${nr.password}\n\n`;
                    txt += `Sua conta foi iniciada com ${nr.credits} crédito(s).`;
                    openShareModal(txt);
                }
            } else { toastr.error(res.msg); }
        }, 'json');
    }

    function openCreditModal(id, name) { $('#creditTargetId').val(id); $('#creditTargetName').text(name); $('#creditAmount').val(1); $('#creditModal').modal('show'); }

    function processCredits() {
        let type = $('#creditType').val();
        $.post('api/resellers_api.php', {
            action: 'manage_credits',
            id: $('#creditTargetId').val(),
            type: type,
            amount: $('#creditAmount').val()
        }, function(res){
            if(res.status) {
                toastr.success(res.msg);
                $('#creditModal').modal('hide');
                loadResellers();
                
                if(type == 'add' && res.credit_info) {
                    let ci = res.credit_info;
                    let txt = `✅ *Operação de Créditos Concluída!*\n\n`;
                    txt += `Olá, ${ci.username}!\n`;
                    txt += `Foi adicionado(s) *${ci.amount} credito* em sua conta.`;
                    openShareModal(txt);
                }
            } else { toastr.error(res.msg); }
        }, 'json');
    }

    function openShareModal(text) {
        $('#shareText').text(text);
        $('#btnZap').attr('href', 'https://api.whatsapp.com/send?text=' + encodeURIComponent(text));
        $('#modalShare').modal('show');
    }

    function copyShareText() {
        var texto = document.getElementById("shareText").innerText;
        var el = document.createElement('textarea');
        el.value = texto;
        document.getElementById('shareModalBody').appendChild(el);
        el.select();
        el.setSelectionRange(0, 99999);
        document.execCommand('copy');
        document.getElementById('shareModalBody').removeChild(el);
        
        var btn = document.getElementById("btnCopy");
        var original = btn.innerHTML;
        btn.innerHTML = '<i class="fa fa-check"></i> Copiado!';
        btn.classList.remove('btn-outline-light'); btn.classList.add('btn-success');
        setTimeout(function(){ btn.innerHTML = original; btn.classList.remove('btn-success'); btn.classList.add('btn-outline-light'); }, 2000);
    }

    function delReseller(id) {
        if(confirm('Tem certeza?')) {
            $.post('api/resellers_api.php', { action: 'delete', id: id }, function(res) {
                if(res.status) { toastr.success('Apagado.'); loadResellers(); } else { toastr.error(res.msg); }
            }, 'json');
        }
    }
</script>
</body>
</html>