<?php
// clients.php - Completo (Ícones Corrigidos)
session_start();
require_once 'includes/db.php';

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

$current_user_id = $_SESSION['user_id'];
$is_admin = ($current_user_id == 1); 
$meus_creditos = 0;
$resellers_list = [];

try {
    $stmt = $pdo->prepare("SELECT role, credits FROM revendedores WHERE id = ?");
    $stmt->execute([$current_user_id]);
    $user_data = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($user_data) {
        if (!$is_admin && $user_data['role'] === 'admin') $is_admin = true;
        $meus_creditos = $user_data['credits'];
    }

    if ($is_admin) {
        $stmt_res = $pdo->query("SELECT id, username FROM revendedores WHERE id != $current_user_id ORDER BY username ASC");
        $resellers_list = $stmt_res->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Exception $e) {}

// Configurações
$confianca_ativo = 0;
$confianca_dias = 3;
$server_url = "http://".$_SERVER['HTTP_HOST'];

try {
    $c = $pdo->query("SELECT confianca_ativo, confianca_dias, dominio_url FROM configuracoes LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if($c) {
        $confianca_ativo = $c['confianca_ativo'];
        $confianca_dias  = $c['confianca_dias'];
        if(!empty($c['dominio_url'])) $server_url = $c['dominio_url'];
    }
} catch(Exception $e){}

$bouquetMap = [];
try {
    $bq_stmt = $pdo->query("SELECT id, name FROM bouquets");
    while($row = $bq_stmt->fetch(PDO::FETCH_ASSOC)) { $bouquetMap[$row['id']] = $row['name']; }
} catch(Exception $e){}

$filter = $_GET['filter'] ?? 'all';
$reseller_filter = $_GET['reseller'] ?? 'me';
$search = $_GET['search'] ?? '';
$sql_where = " AND is_p2p = 0"; 

if ($filter == 'trial') $sql_where .= " AND is_trial = 1";
elseif ($filter == 'active') $sql_where .= " AND active = 1 AND expire_date > NOW() AND is_trial = 0";
elseif ($filter == 'expired') $sql_where .= " AND expire_date < NOW() AND is_trial = 0";

try {
    $params = [];
    if ($is_admin) {
        $sql = "SELECT * FROM users WHERE 1=1 $sql_where";
        if ($reseller_filter === 'me') { $sql .= " AND revendedor_id = ?"; $params[] = $current_user_id; }
        elseif ($reseller_filter !== 'all' && !empty($reseller_filter)) { $sql .= " AND revendedor_id = ?"; $params[] = $reseller_filter; }
    } else {
        $sql = "SELECT * FROM users WHERE revendedor_id = ? $sql_where";
        $params[] = $current_user_id;
    }
    if (!empty($search)) { $sql .= " AND username LIKE ?"; $params[] = "%$search%"; }
    $sql .= " ORDER BY id DESC";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $users = []; }

$pode_criar = ($is_admin || $meus_creditos >= 1);
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Gerenciar Clientes IPTV</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
    <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; }
        .card { background-color: #232730; border: 1px solid #333; }
        .table { color: #bfbfbf; }
        .table td, .table th { vertical-align: middle; border-top: 1px solid #333; }
        .table-hover tbody tr:hover { background-color: #2c2c2c; }
        .badge-credits { background: #28a745; color: white; padding: 6px 12px; border-radius: 20px; font-weight: bold; }
        .modal-content { background-color: #232730; border: 1px solid #333; color: #fff; }
        .form-control { background-color: #1a1c23; border: 1px solid #444; color: #fff; }
        .form-control:focus { background-color: #1a1c23; color: #fff; border-color: #007bff; }
        #modalShare .modal-dialog { max-width: 96% !important; width: 96% !important; margin: 10px auto; }
        #shareText { background: #111; color: #00ff00; padding: 15px; border-radius: 8px; font-size: 14px; max-height: 60vh; overflow-y: auto; white-space: pre-wrap; font-family: monospace; border: 1px solid #333; }
        .filter-select { background-color: #2c2c2c; color: #fff; border: 1px solid #444; padding: 7px 15px; border-radius: 5px; margin-bottom: 5px; width: 100%; max-width: 300px; cursor: pointer; }
        .filter-select option { background-color: #1e1e1e; color: #fff; }
        .bouquet-list { max-height: 150px; overflow-y: auto; background: #1a1c23; border: 1px solid #444; padding: 10px; border-radius: 5px; }
        .custom-control-label { cursor: pointer; user-select: none; }
        .modal-footer-custom { display: flex; justify-content: flex-end; align-items: center; flex-wrap: wrap; gap: 10px; padding-top: 15px; border-top: 1px solid #333; margin-top: 15px; }
        .modal-footer-custom .btn { white-space: nowrap; }
        @media (max-width: 576px) { .modal-footer-custom { flex-direction: column-reverse; align-items: stretch; } .modal-footer-custom .btn { width: 100%; margin: 5px 0 !important; } }
        /* SIDEBAR CSS */
        @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; }
            .navbar { 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; }
    </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">Clientes IPTV</h4>
                </div>
                <div>
                    <span class="badge-credits mr-2"><i class="fa fa-coins"></i> <?php echo $is_admin ? '8' : $meus_creditos; ?></span>
                    <a href="dashboard.php" class="btn btn-secondary btn-sm d-none d-lg-inline-block">Voltar</a>
                </div>
            </div>
            <div class="container-fluid px-4 pb-5">
                <div class="row mb-3 align-items-end">
                    <div class="col-md-8">
                        <?php if($is_admin): ?>
                        <div class="mb-3 p-3 card" style="border: 1px solid #444;">
                            <label class="text-warning small text-uppercase font-weight-bold mb-2"><i class="fa fa-filter"></i> Filtrar Clientes Por:</label>
                            <select class="filter-select form-control" onchange="window.location.href='?filter=<?php echo $filter; ?>&reseller='+this.value">
                                <option value="me" <?php echo $reseller_filter=='me'?'selected':''; ?>>?? Meus Clientes (Padrão)</option>
                                <option value="all" <?php echo $reseller_filter=='all'?'selected':''; ?>>?? Todos (Geral)</option>
                                <?php if(!empty($resellers_list)): ?>
                                    <option disabled>---------- REVENDAS ----------</option>
                                    <?php foreach($resellers_list as $r): ?>
                                        <option value="<?php echo $r['id']; ?>" <?php echo $reseller_filter==$r['id']?'selected':''; ?>>?? Revenda: <?php echo htmlspecialchars($r['username']); ?></option>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </select>
                        </div>
                        <?php endif; ?>
                        <form class="form-inline d-block search-form" method="GET">
                            <input type="hidden" name="filter" value="<?php echo $filter; ?>">
                            <input type="hidden" name="reseller" value="<?php echo $reseller_filter; ?>">
                            <div class="input-group" style="max-width: 300px;">
                                <input type="text" name="search" class="form-control bg-dark text-white border-secondary" placeholder="Buscar usuário..." value="<?php echo htmlspecialchars($search); ?>">
                                <div class="input-group-append"><button class="btn btn-secondary" type="submit"><i class="fa fa-search"></i></button></div>
                            </div>
                        </form>
                    </div>
                    <div class="col-md-4 text-right mt-3 mt-md-0">
                        <button class="btn btn-warning font-weight-bold mr-2 mb-1" onclick="openTestModal()"><i class="fa fa-bolt"></i> Teste Rápido</button>
                        <button class="btn btn-success font-weight-bold mb-1" onclick="openCreateModal()" <?php echo $pode_criar ? '' : 'disabled style="opacity:0.5"'; ?>><i class="fa fa-user-plus"></i> Novo Cliente</button>
                    </div>
                </div>
                <div class="card shadow">
                    <div class="card-header bg-dark p-0">
                        <ul class="nav nav-tabs border-bottom-0">
                            <?php $p = ($reseller_filter ? "&reseller=$reseller_filter" : "") . ($search ? "&search=$search" : ""); ?>
                            <li class="nav-item"><a class="nav-link <?php echo $filter=='all'?'active bg-secondary text-white':'text-muted'; ?>" href="?filter=all<?php echo $p; ?>">Todos</a></li>
                            <li class="nav-item"><a class="nav-link <?php echo $filter=='active'?'active bg-success text-white':'text-muted'; ?>" href="?filter=active<?php echo $p; ?>">Ativos</a></li>
                            <li class="nav-item"><a class="nav-link <?php echo $filter=='trial'?'active bg-warning text-dark':'text-muted'; ?>" href="?filter=trial<?php echo $p; ?>">Testes</a></li>
                            <li class="nav-item"><a class="nav-link <?php echo $filter=='expired'?'active bg-danger text-white':'text-muted'; ?>" href="?filter=expired<?php echo $p; ?>">Vencidos</a></li>
                        </ul>
                    </div>
                    <div class="table-responsive">
                        <table class="table table-hover mb-0">
                            <thead class="bg-secondary text-white">
                                <tr>
                                    <th class="pl-4">Usuário</th><th>Senha</th><th>Vencimento</th><th>Conexões / Pacotes</th><th>Status</th><th class="text-right pr-4">Ações</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if(count($users) > 0): ?>
                                    <?php foreach($users as $u): 
                                        $date_str = $u['expire_date'] ? date('d/m/Y H:i', strtotime($u['expire_date'])) : '--';
                                        $is_expired = (strtotime($u['expire_date']) < time());
                                        $u_data = htmlspecialchars(json_encode($u), ENT_QUOTES, 'UTF-8');
                                        $my_bouquets_names = [];
                                        try {
                                            $bqs_ids = json_decode($u['bouquets'] ?? '[]', true);
                                            if(is_array($bqs_ids)){
                                                foreach($bqs_ids as $bid){ if(isset($bouquetMap[$bid])) $my_bouquets_names[] = $bouquetMap[$bid]; }
                                            }
                                        } catch(Exception $e){}
                                    ?>
                                    <tr>
                                        <td class="pl-4 font-weight-bold"><?php echo $u['username']; ?></td>
                                        <td><code class="text-info"><?php echo $u['password']; ?></code></td>
                                        <td><?php echo $date_str; ?></td>
                                        <td>
                                            <div class="mb-1"><span class="badge badge-info"><?php echo $u['max_connections']; ?> Telas</span></div>
                                            <?php if(!empty($my_bouquets_names)): ?>
                                                <?php foreach($my_bouquets_names as $bname): ?>
                                                    <span class="badge badge-secondary border border-secondary" style="font-size: 0.75rem; margin-right: 2px; margin-bottom: 2px;"><?php echo htmlspecialchars($bname); ?></span>
                                                <?php endforeach; ?>
                                            <?php else: ?><span class="text-muted small">Sem pacote</span><?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if($u['active'] == 0) echo '<span class="badge badge-danger">Bloqueado</span>';
                                                  elseif($u['is_trial']) echo '<span class="badge badge-warning text-dark">Teste</span>';
                                                  elseif($is_expired) echo '<span class="badge badge-secondary">Vencido</span>';
                                                  else echo '<span class="badge badge-success">Ativo</span>'; ?>
                                        </td>
                                        <td class="text-right pr-4">
                                            <button class="btn btn-sm btn-outline-success mr-1 mb-1" onclick="showShareModal(<?php echo $u['id']; ?>)" title="Compartilhar"><i class="fab fa-whatsapp"></i></button>
                                            <button class="btn btn-sm btn-outline-info mr-1 mb-1" onclick='openEditModal(<?php echo $u_data; ?>)' title="Editar"><i class="fa fa-pen"></i></button>
                                            <?php if($u['active'] == 1): ?>
                                                <button class="btn btn-sm btn-outline-warning mr-1 mb-1" onclick="toggleBlock(<?php echo $u['id']; ?>, 0)" title="Bloquear"><i class="fa fa-ban"></i></button>
                                            <?php else: ?>
                                                <button class="btn btn-sm btn-outline-light mr-1 mb-1" onclick="toggleBlock(<?php echo $u['id']; ?>, 1)" title="Desbloquear"><i class="fa fa-unlock"></i></button>
                                            <?php endif; ?>
                                            <button class="btn btn-sm btn-outline-primary mr-1 mb-1" onclick="openRenewModal(<?php echo $u['id']; ?>, '<?php echo $u['username']; ?>')" title="Renovar"><i class="fa fa-sync-alt"></i></button>
                                            <button class="btn btn-sm btn-outline-danger mb-1" onclick="deleteUser(<?php echo $u['id']; ?>)" title="Apagar"><i class="fa fa-trash"></i></button>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr><td colspan="6" class="text-center py-4 text-muted">Nenhum cliente IPTV encontrado.</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalRenew" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white"><h5 class="modal-title">Renovar Cliente</h5><button type="button" class="close text-white" data-dismiss="modal">×</button></div>
            <div class="modal-body">
                <p class="mb-3" style="font-size: 1.1rem;">Cliente: <b id="renewUser" class="text-warning"></b></p>
                <div class="form-group"><label>Quantos meses?</label><input type="number" id="renewMonths" class="form-control form-control-lg" value="1" min="1"></div>
                <div class="modal-footer-custom">
                    <button class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
                    <?php if($confianca_ativo == 1): ?>
                        <button class="btn btn-outline-info" onclick="processRenew('confianca')"><i class="fa fa-handshake"></i> Confiança (<?php echo $confianca_dias; ?>d)</button>
                    <?php endif; ?>
                    <button class="btn btn-success" onclick="processRenew('normal')"><i class="fa fa-check"></i> RENOVAR</button>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalCreate" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header border-secondary"><h5 class="modal-title" id="createTitle">Novo Cliente IPTV</h5></div>
            <div class="modal-body">
                <form id="formCreate">
                    <input type="hidden" name="action" value="save"> 
                    <input type="hidden" name="id" id="edit_id">
                    
                    <div class="row">
                        <div class="col-6"><div class="form-group"><label>Tipo</label><select name="is_trial" id="createType" class="form-control"><option value="0">Oficial (1 Crédito)</option><option value="1">Teste (Grátis)</option></select></div></div>
                        <div class="col-6"><div class="form-group"><label>Duração</label><select name="duration" id="selDuration" class="form-control"><option value="1">1 Mês</option></select></div></div>
                    </div>
                    <div class="row">
                        <div class="col-6"><div class="form-group"><label>Usuário</label><input type="text" name="username" id="inputUser" class="form-control" required></div></div>
                        <div class="col-6"><div class="form-group"><label>Senha</label><input type="text" name="password" id="inputPass" class="form-control" required></div></div>
                    </div>
                    
                    <div class="form-group"><label>Notas (Opcional)</label><textarea name="notes" id="inputNotes" class="form-control" rows="2"></textarea></div>

                    <div class="form-group"><label>Máximo de Conexões (Telas)</label><input type="number" name="max_connections" id="inputMaxConn" class="form-control" value="1" min="1" required></div>
                    <div class="form-group"><label class="text-warning"><i class="fa fa-box-open"></i> Pacotes (Bouquets)</label><div class="bouquet-list bouquets-container"><small>Carregando...</small></div></div>
                    <button class="btn btn-primary btn-block" id="btnSave">Salvar</button>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalTest" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-warning text-dark"><h5>Gerar Teste IPTV</h5><button type="button" class="close" data-dismiss="modal">×</button></div>
            <div class="modal-body text-center">
                <p>Será criado um teste de <b>3 HORAS</b> com <b>1 TELA</b>.</p>
                <form id="formTest">
                    <input type="hidden" name="action" value="save">
                    <input type="hidden" name="is_trial" value="1">
                    <input type="hidden" name="duration" value="3">
                    <input type="hidden" name="max_connections" value="1"> <input type="hidden" name="username" id="testUser">
                    <input type="hidden" name="password" id="testPass">
                    <div class="form-group text-left"><label class="text-dark font-weight-bold"><i class="fa fa-box-open"></i> Pacotes Liberados</label><div class="bouquet-list bouquets-container" style="background:#fff; border-color:#ccc; color:#000;"><small>Carregando...</small></div></div>
                    <button type="submit" class="btn btn-dark btn-lg btn-block mt-3"><i class="fa fa-magic"></i> GERAR AGORA</button>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalShare" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header border-secondary"><h5 class="modal-title">Dados da Conta</h5><button type="button" class="close text-white" data-dismiss="modal">×</button></div>
            <div class="modal-body" id="shareModalBody">
                <div id="shareText">Carregando...</div>
                <div class="mt-3 text-right">
                    <button type="button" class="btn btn-secondary mr-2" data-dismiss="modal">Fechar</button>
                    <button class="btn btn-outline-light" id="btnCopy" onclick="copyShareText()"><i class="fa fa-copy"></i> Copiar</button>
                    <a href="#" id="btnZap" target="_blank" class="btn btn-success"><i class="fab fa-whatsapp"></i> 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>
    var serverDNS = "<?php echo $server_url; ?>";
    var currentId = 0;

    // ATIVA O BOTÃO "X" NAS NOTIFICAÇÕES TOASTR
    toastr.options = {
        "closeButton": true,
        "progressBar": true,
        "positionClass": "toast-top-right",
        "timeOut": "5000"
    };

    $(document).ready(function() {
        $.post('api/bouquets_api.php', {action: 'list'}, function(data){
            let html = '';
            if(data.length > 0) {
                data.forEach(b => { html += `<div class="custom-control custom-checkbox mb-1"><input type="checkbox" class="custom-control-input" id="bq_${b.id}" name="bouquets[]" value="${b.id}" checked><label class="custom-control-label" for="bq_${b.id}">${b.name}</label></div>`; });
            } else { html = '<div class="text-muted small">Nenhum pacote criado.</div>'; }
            $('.bouquets-container').each(function(){
                if($(this).parents('#modalTest').length) {
                    let htmlTest = html.replace(/id="bq_/g, 'id="bq_t_').replace(/for="bq_/g, 'for="bq_t_');
                    $(this).html(htmlTest);
                } else { $(this).html(html); }
            });
        }, 'json');
    });

    function openCreateModal() { 
        $('#formCreate')[0].reset(); 
        $('#edit_id').val(''); 
        $('#formCreate input[name="action"]').val('save'); 
        $('#createTitle').text('Novo Cliente IPTV'); 
        $('#btnSave').text('Criar Agora'); 
        $('#createType').val(0).trigger('change'); 
        $('#inputMaxConn').val(1); 
        $('.bouquets-container input[type="checkbox"]').prop('checked', true); 
        $('#modalCreate').modal('show'); 
    }

    function openEditModal(user) {
        $('#formCreate')[0].reset(); 
        $('#edit_id').val(user.id); 
        $('#formCreate input[name="action"]').val('update');
        $('#createTitle').text('Editar Cliente: ' + user.username); 
        $('#btnSave').text('Salvar Alterações');
        $('#createType').val(user.is_trial); 
        $('#inputUser').val(user.username); 
        $('#inputPass').val(user.password); 
        $('#inputNotes').val(user.notes || ''); 
        $('#inputMaxConn').val(user.max_connections);
        $('.bouquets-container input[type="checkbox"]').prop('checked', false); 
        let userBouquets = [];
        try { if (typeof user.bouquets === 'string') userBouquets = JSON.parse(user.bouquets); else userBouquets = user.bouquets; } catch(e) {}
        if(userBouquets && userBouquets.length > 0) { userBouquets.forEach(bid => { $('#bq_' + bid).prop('checked', true); }); }
        $('#modalCreate').modal('show');
    }

    function openTestModal() {
        var rndUser = 'teste' + Math.floor(Math.random() * 90000 + 10000); var rndPass = Math.floor(Math.random() * 9000 + 1000);
        $('#testUser').val(rndUser); $('#testPass').val(rndPass); 
        $('#formTest input[name="action"]').val('save');
        $('#modalTest').modal('show');
    }
    function openRenewModal(id, username) { currentId = id; $('#renewUser').text(username); $('#modalRenew').modal('show'); }

    $('#createType').change(function(){
        var t = $(this).val(); var s = $('#selDuration'); s.empty();
        if(t==0){ s.append('<option value="1">1 Mês</option><option value="3">3 Meses</option><option value="6">6 Meses</option>'); }
        else{ s.append('<option value="3">3 Horas</option><option value="6">6 Horas</option><option value="24">24 Horas</option>'); }
    });

    $('#formCreate, #formTest').submit(function(e){
        e.preventDefault();
        
        let formAction = $(this).find('input[name="action"]').val();

        $.post('api/clients_api.php', $(this).serialize(), function(r){
            if(r.status){ 
                toastr.success(r.msg); 
                $('#modalCreate').modal('hide'); 
                $('#modalTest').modal('hide'); 

                if(formAction === 'save' && r.data) {
                    let u = r.data;
                    let txt = `? *DADOS DA SUA CONTA IPTV*\n\n`;
                    txt += `?? *Usuário:* ${u.username}\n`;
                    txt += `?? *Senha:* ${u.password}\n`;
                    txt += `?? *Vencimento:* ${u.expire_view}\n\n`;
                    txt += `-----------------------\n`;
                    txt += `?? *DADOS PARA APLICATIVOS (XC/PLUS):*\n`;
                    txt += `*URL:* ${u.server_url}\n`;
                    txt += `*User:* ${u.username}\n`;
                    txt += `*Pass:* ${u.password}\n`;
                    txt += `-----------------------\n`;
                    txt += `?? *Loja de Aplicativos:* https://lojaapp.xyz\n`;
                    txt += `-----------------------\n`;
                    txt += `?? *LINK M3U COMPLETO:*\n${u.server_url}/get.php?username=${u.username}&password=${u.password}&type=m3u&output=ts\n\n`;
                    txt += `?? *LINK M3U8 (VOD):*\n${u.server_url}/get.php?username=${u.username}&password=${u.password}&type=m3u8&output=ts\n\n`;
                    txt += `?? *LINK SSIPTV:*\n${u.server_url}/get.php?username=${u.username}&password=${u.password}&type=m3u&output=mpegts\n\n`;
                    txt += `Att: TOP IPTV`;

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

                    // Recarrega ao fechar o modal
                    $('#modalShare').on('hidden.bs.modal', function () {
                        location.reload();
                    });

                } else {
                    setTimeout(() => location.reload(), 1000);
                }

            } else { 
                toastr.error(r.msg); 
            }
        }, 'json');
    });

    // === LÓGICA DE RENOVAÇÃO ===
    function processRenew(type) {
        var months = $('#renewMonths').val();
        var action = (type === 'confianca') ? 'renew_confianca' : 'renew';
        if(!confirm('Confirmar renovação?')) return;

        $.post('api/clients_api.php', { action: action, id: currentId, months: months }, function(r){
            if (!r) { alert("Erro de conexão com o servidor."); return; }

            if(r.status){ 
                if(type === 'confianca') {
                    // MENSAGEM CONFIANÇA
                    let u = r.data;
                    let txt = `?? *RENOVAÇÃO DE CONFIANÇA*\n\n`;
                    txt += `Olá! Liberamos um acesso temporário para você não ficar sem assistir.\n\n`;
                    txt += `?? *Usuário:* ${u.username}\n`;
                    txt += `?? *Vencimento:* ${u.expire_view}\n\n`;
                    txt += `?? *Atenção:* Regularize seu pagamento o quanto antes para evitar bloqueio definitivo.\n\n`;
                    txt += `Att: TOP IPTV`;
                    
                    $('#shareText').text(txt);
                    $('#btnZap').attr('href', 'https://api.whatsapp.com/send?text=' + encodeURIComponent(txt));
                    $('#modalRenew').modal('hide');
                    setTimeout(() => { $('#modalShare').modal('show'); }, 500);
                    $('#modalShare').on('hidden.bs.modal', function () { location.reload(); });

                } else {
                    // MENSAGEM RENOVAÇÃO PAGA
                    let u = r.data;
                    let txt = `? *RENOVAÇÃO CONCLUÍDA*\n\n`;
                    txt += `Obrigado! Seu plano foi renovado com sucesso.\n\n`;
                    txt += `?? *Usuário:* ${u.username}\n`;
                    txt += `?? *Novo Vencimento:* ${u.expire_view}\n\n`;
                    txt += `Tenha um excelente entretenimento! ??\n\n`;
                    txt += `Att: TOP IPTV`;

                    $('#shareText').text(txt);
                    $('#btnZap').attr('href', 'https://api.whatsapp.com/send?text=' + encodeURIComponent(txt));
                    $('#modalRenew').modal('hide');
                    setTimeout(() => { $('#modalShare').modal('show'); }, 500);
                    $('#modalShare').on('hidden.bs.modal', function () { location.reload(); });
                }
            } else { 
                alert("? Atenção: " + r.msg);
            }
        }, 'json').fail(function() {
            alert("Erro ao processar.");
        });
    }

    function openShareForRenew(id) {
        $.get('api/clients_api.php?action=get_client&id='+id, function(res){
            if(res.status) {
                let u = res.data;
                let txt = `? *Plano IPTV renovado com sucesso!*\n\n`;
                txt += `?? Usuario: ${u.username}\n`;
                txt += `?? Senha: ${u.password}\n`;
                txt += `?? Vencimento: ${u.expire_view}`;
                
                $('#shareText').text(txt);
                $('#btnZap').attr('href', 'https://api.whatsapp.com/send?text=' + encodeURIComponent(txt));
                $('#modalShare').modal('show');
                
                $('#modalShare').on('hidden.bs.modal', function () { location.reload(); });
            } else {
                location.reload();
            }
        }, 'json');
    }

    function copyShareText() {
        var texto = document.getElementById("shareText").innerText;
        var el = document.createElement('textarea'); el.value = texto; document.getElementById('shareModalBody').appendChild(el); el.select(); 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 showShareModal(id) {
        $('#modalShare').modal('show'); $('#shareText').text('Gerando links...');
        $.get('api/clients_api.php?action=get_client&id='+id, function(r){
            if(r.status) {
                let u = r.data;
                let txt = `? *DADOS DA SUA CONTA IPTV*\n\n`;
                txt += `?? *Usuário:* ${u.username}\n`;
                txt += `?? *Senha:* ${u.password}\n`;
                txt += `?? *Vencimento:* ${u.expire_view}\n\n`;
                txt += `-----------------------\n`;
                txt += `?? *DADOS PARA APLICATIVOS (XC/PLUS):*\n`;
                txt += `*URL:* ${u.server_url}\n`;
                txt += `*User:* ${u.username}\n`;
                txt += `*Pass:* ${u.password}\n`;
                txt += `-----------------------\n`;
                txt += `?? *Loja de Aplicativos:* https://lojaapp.xyz\n`;
                txt += `-----------------------\n`;
                txt += `?? *LINK M3U COMPLETO:*\n${u.server_url}/get.php?username=${u.username}&password=${u.password}&type=m3u&output=ts\n\n`;
                txt += `?? *LINK M3U8 (VOD):*\n${u.server_url}/get.php?username=${u.username}&password=${u.password}&type=m3u8&output=ts\n\n`;
                txt += `?? *LINK SSIPTV:*\n${u.server_url}/get.php?username=${u.username}&password=${u.password}&type=m3u&output=mpegts\n\n`;
                txt += `Att: TOP IPTV`;
                $('#shareText').text(txt);
                $('#btnZap').attr('href', 'https://api.whatsapp.com/send?text=' + encodeURIComponent(txt));
            }
        }, 'json');
    }

    function deleteUser(id) { if(confirm('Excluir cliente?')){ $.post('api/clients_api.php', {action:'delete', id:id}, ()=>location.reload()); } }
    function toggleBlock(id, s) { if(confirm(s==0?'Bloquear?':'Desbloquear?')){ $.post('api/clients_api.php', {action:'toggle_block', id:id, active:s}, ()=>location.reload()); } }
</script>
</body>
</html>