<?php
require_once 'conexao.php';

$msg = "";
$msg_tipo = "";
$texto_zap = "";

// --- 1. FUNÇÃO DE LIMPEZA AGRESSIVA (CORRIGE O BUG VISUAL) ---
function limpar($dado) {
    if (!$dado) return "";
    
    // Tenta decodificar caracteres estranhos como \u00e1
    $d = json_decode('"'.$dado.'"');
    if($d) $dado = $d;

    // Remove tags HTML
    $dado = strip_tags($dado);
    
    // Remove barras e quebras de linha
    $dado = str_replace(['\\', "\r", "\n", "\t"], ' ', $dado);

    // SE FOR MUITO LONGO, CORTA (Evita que textos de config quebrem a tela)
    if (strlen($dado) > 25) {
        return substr($dado, 0, 25) . "...";
    }
    
    return $dado;
}

// --- 2. DATA BLINDADA ---
function dataISO($data) {
    if (!$data) return date('Y-m-d');
    $data = trim($data);
    // Se for timestamp
    if (is_numeric($data) && strlen($data) > 8) return date('Y-m-d', $data);
    // Se for data BR
    if (strpos($data, '/') !== false) {
        $d = DateTime::createFromFormat('d/m/Y', substr($data, 0, 10));
        return $d ? $d->format('Y-m-d') : date('Y-m-d');
    }
    return substr($data, 0, 10);
}

// 3. PROCESSAMENTO
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $acao = $_POST['acao'];
        $id_user = $_POST['id_user'] ?? 0;

        if ($acao === 'criar') {
            $connUser->prepare("INSERT INTO usuario (CadUser, nome, usuario, senha, conexao, data_premio, bloqueado, data_cadastro) VALUES (?,?,?,?,?,?,'nao',NOW())")
                     ->execute(['Admin', $_POST['nome'], $_POST['usuario'], $_POST['senha'], $_POST['conexao'], $_POST['vencimento']]);
            $msg = "Criado!"; $msg_tipo = "success";
        }

        if ($acao === 'editar') {
            $connUser->prepare("UPDATE usuario SET nome=?, usuario=?, senha=?, conexao=?, data_premio=? WHERE id=?")
                     ->execute([$_POST['nome'], $_POST['usuario'], $_POST['senha'], $_POST['conexao'], $_POST['vencimento_edit'], $id_user]);
            
            $data_formatada = date('d/m/Y', strtotime($_POST['vencimento_edit']));
            $texto_zap = "*Dados Atualizados!*\n\n👤 User: {$_POST['usuario']}\n🔑 Senha: {$_POST['senha']}\n📆 Vence: $data_formatada";
            $msg = "Atualizado!"; $msg_tipo = "primary";
        }

        if ($acao === 'renovar') {
            $tipo = $_POST['tipo_renovacao'];
            $atual = $connUser->query("SELECT data_premio, usuario, senha FROM usuario WHERE id=$id_user")->fetch();
            $base = dataISO($atual['data_premio']);
            $hoje = date('Y-m-d');
            
            $inicio = ($base < $hoje) ? $hoje : $base;

            if ($tipo == 'manual') {
                $nova = $_POST['nova_data_manual'];
            } else {
                $meses = (int)$_POST['qtd_meses'];
                $nova = date('Y-m-d', strtotime("+$meses months", strtotime($inicio)));
            }

            $connUser->prepare("UPDATE usuario SET data_premio=?, bloqueado='nao' WHERE id=?")->execute([$nova, $id_user]);
            
            $exibir = date('d/m/Y', strtotime($nova));
            $texto_zap = "*Renovado com Sucesso!*\n\n👤 User: {$atual['usuario']}\n🔑 Senha: {$atual['senha']}\n📆 Vence: $exibir";
            $msg = "Renovado até $exibir"; $msg_tipo = "success";
        }

        if ($acao === 'bloquear_toggle') {
            $novo = ($_POST['status_atual'] == 'sim') ? 'nao' : 'sim';
            $connUser->prepare("UPDATE usuario SET bloqueado=? WHERE id=?")->execute([$novo, $id_user]);
            $msg = ($novo=='sim') ? "Bloqueado!" : "Desbloqueado!"; $msg_tipo = ($novo=='sim')?"warning":"info";
        }

        if ($acao === 'excluir') {
            $connUser->prepare("DELETE FROM usuario WHERE id=?")->execute([$id_user]);
            $msg = "Deletado."; $msg_tipo = "danger";
        }
    } catch (Exception $e) { $msg = "Erro: ".$e->getMessage(); $msg_tipo = "danger"; }
}

// 4. FILTROS E BUSCA (CORRIGIDO PARAMETROS)
$termo = $_GET['busca'] ?? '';
$filtro_rev = $_GET['revenda'] ?? '';
$filtro_status = $_GET['status'] ?? '';
$limite = $_GET['limite'] ?? 50;

$sql = "SELECT * FROM usuario WHERE 1=1";
$params = [];

// CORREÇÃO AQUI: Usamos :t1 e :t2
if ($termo) {
    $sql .= " AND (nome LIKE :t1 OR usuario LIKE :t2)";
    $params[':t1'] = "%$termo%";
    $params[':t2'] = "%$termo%";
}
if ($filtro_rev) {
    $sql .= " AND CadUser = :rev";
    $params[':rev'] = $filtro_rev;
}
if ($filtro_status == 'bloqueados') {
    $sql .= " AND bloqueado = 'sim'";
}

$sql .= " ORDER BY id DESC LIMIT " . (int)$limite;

try {
    $stmt = $connUser->prepare($sql);
    $stmt->execute($params);
    $usuarios = $stmt->fetchAll();
} catch(Exception $e) {
    die("Erro na busca: " . $e->getMessage());
}

$revendedores = $connUser->query("SELECT DISTINCT CadUser FROM usuario WHERE CadUser != ''")->fetchAll(PDO::FETCH_COLUMN);
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Clientes</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        body { background: #151521; color: #fff; font-family: sans-serif; padding-bottom: 80px; }
        .sidebar { width: 260px; height: 100vh; position: fixed; top: 0; left: 0; background: #1e1e2d; padding: 20px; z-index: 1000; transition: 0.3s; border-right: 1px solid #333; }
        .main-content { margin-left: 260px; padding: 20px; transition: 0.3s; }
        .table-dark { background: #1e1e2d; --bs-table-bg: #1e1e2d; color: #fff; }
        .table-dark td { border-color: #333; vertical-align: middle; }
        .form-control, .form-select { background: #2b2b40; border: 1px solid #444; color: #fff; }
        .form-control:focus { border-color: #7367f0; color: #fff; }
        .btn-renov { width: 100%; margin-bottom: 5px; border: 1px solid #555; color: #fff; }
        .btn-renov:hover { background: #7367f0; border-color: #7367f0; }
        
        @media (max-width: 768px) {
            .sidebar { transform: translateX(-100%); } .sidebar.show { transform: translateX(0); }
            .main-content { margin-left: 0; }
        }
        .overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 999; }
        .overlay.show { display: block; }
    </style>
</head>
<body>

<div class="overlay" id="overlay" onclick="toggleMenu()"></div>

<div class="modal fade" id="modalZap" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content bg-dark border-success">
            <div class="modal-header border-bottom-0"><h5 class="modal-title text-success w-100 text-center"><i class="fas fa-check-circle"></i> Sucesso!</h5></div>
            <div class="modal-body">
                <textarea id="textoZapArea" class="form-control" rows="5" style="background:#111; color:#0f0; font-family:monospace;"><?= $texto_zap ?></textarea>
            </div>
            <div class="modal-footer border-top-0 justify-content-center">
                <button onclick="copiarTexto()" class="btn btn-outline-light"><i class="fas fa-copy"></i> Copiar</button>
                <button onclick="enviarZap()" class="btn btn-success"><i class="fab fa-whatsapp"></i> Enviar</button>
                <button data-bs-dismiss="modal" class="btn btn-secondary">Fechar</button>
            </div>
        </div>
    </div>
</div>

<nav class="sidebar" id="sidebar">
    <h4 class="mb-4 fw-bold"><i class="fas fa-tv text-primary"></i> Painel v3.0</h4>
    <div class="nav flex-column gap-2">
        <a href="index.php" class="btn btn-dark text-start border-0"><i class="fas fa-home me-2"></i> Dashboard</a>
        <a href="clientes.php" class="btn btn-primary text-start border-0"><i class="fas fa-users me-2"></i> Clientes</a>
        <a href="criar_cliente.php" class="btn btn-dark text-start border-0"><i class="fas fa-user-plus me-2"></i> Novo</a>
    </div>
</nav>

<main class="main-content">
    <button class="btn btn-dark d-md-none mb-3" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>

    <?php if($msg): ?>
        <div class="alert alert-<?= $msg_tipo ?> alert-dismissible fade show"><?= $msg ?><button class="btn-close" data-bs-dismiss="alert"></button></div>
    <?php endif; ?>

    <div class="card bg-dark border-secondary mb-4">
        <div class="card-body p-3">
            <form method="GET" class="row g-2 align-items-end">
                <div class="col-md-3 col-12">
                    <label class="text-muted small">Buscar</label>
                    <input type="text" name="busca" class="form-control form-control-sm" placeholder="Nome ou Usuário" value="<?= htmlspecialchars($termo) ?>">
                </div>
                <div class="col-md-2 col-6">
                    <label class="text-muted small">Status</label>
                    <select name="status" class="form-select form-select-sm" onchange="this.form.submit()">
                        <option value="">Todos</option>
                        <option value="ativos" <?= $filtro_status == 'ativos' ? 'selected' : '' ?>>Ativos (Online)</option>
                        <option value="vencidos" <?= $filtro_status == 'vencidos' ? 'selected' : '' ?>>Vencidos</option>
                        <option value="bloqueados" <?= $filtro_status == 'bloqueados' ? 'selected' : '' ?>>Bloqueados</option>
                    </select>
                </div>
                <div class="col-md-3 col-6">
                    <label class="text-muted small">Revenda</label>
                    <select name="revenda" class="form-select form-select-sm" onchange="this.form.submit()">
                        <option value="">Todas</option>
                        <?php foreach($revendedores as $rev): ?>
                            <option value="<?= $rev ?>" <?= $filtro_rev == $rev ? 'selected' : '' ?>><?= $rev ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2 col-6">
                    <label class="text-muted small">Qtd</label>
                    <select name="limite" class="form-select form-select-sm" onchange="this.form.submit()">
                        <?php foreach([10,50,100,500,1000] as $l): ?>
                            <option value="<?= $l ?>" <?= $limite == $l ? 'selected' : '' ?>><?= $l ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2 col-6">
                    <button class="btn btn-outline-light btn-sm w-100">Filtrar</button>
                </div>
            </form>
        </div>
    </div>

    <div class="card bg-dark border-secondary">
        <div class="table-responsive">
            <table class="table table-dark table-hover mb-0">
                <thead>
                    <tr class="text-muted small text-uppercase">
                        <th>Cliente</th>
                        <th>Vencimento</th>
                        <th>Status</th>
                        <th class="text-end">Ações</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(count($usuarios) > 0): ?>
                        <?php foreach($usuarios as $u): 
                            $nomeLimpo = limpar($u['nome']);
                            
                            // SE O NOME LIMPO FICOU VAZIO OU AINDA TEM CARA DE CONFIG, IGNORA ESSE REGISTRO
                            if (strlen($nomeLimpo) < 2 && strlen($u['usuario']) < 2) continue;
                            
                            $dataISO = dataISO($u['data_premio']);
                            $hoje = date('Y-m-d');
                            $vencido = ($dataISO < $hoje);
                            $bloqueado = ($u['bloqueado'] == 'sim');

                            // FILTRAGEM VISUAL (PHP)
                            if ($filtro_status == 'ativos' && ($vencido || $bloqueado)) continue;
                            if ($filtro_status == 'vencidos' && (!$vencido || $bloqueado)) continue;

                            if ($bloqueado) { $bg="bg-danger"; $st="Bloqueado"; }
                            elseif ($vencido) { $bg="bg-warning text-dark"; $st="Vencido"; }
                            else { $bg="bg-success"; $st="Ativo"; }
                        ?>
                        <tr>
                            <td>
                                <div class="fw-bold"><?= $nomeLimpo ?></div>
                                <small class="text-secondary"><?= limpar($u['usuario']) ?> <span class="badge bg-secondary opacity-50"><?= limpar($u['CadUser']) ?></span></small>
                            </td>
                            <td><b><?= date('d/m/Y', strtotime($dataISO)) ?></b></td>
                            <td><span class="badge <?= $bg ?>"><?= $st ?></span></td>
                            <td class="text-end">
                                <button onclick="abrirRenovar(<?= $u['id'] ?>, '<?= $nomeLimpo ?>')" class="btn btn-sm btn-success rounded-circle"><i class="fas fa-calendar-plus"></i></button>
                                <button onclick='abrirEditar(<?= json_encode($u) ?>)' class="btn btn-sm btn-primary rounded-circle"><i class="fas fa-pen"></i></button>
                                <form method="POST" class="d-inline">
                                    <input type="hidden" name="acao" value="bloquear_toggle">
                                    <input type="hidden" name="id_user" value="<?= $u['id'] ?>">
                                    <input type="hidden" name="status_atual" value="<?= $u['bloqueado'] ?>">
                                    <button class="btn btn-sm <?= $bloqueado?'btn-secondary':'btn-warning' ?> rounded-circle"><i class="fas <?= $bloqueado?'fa-lock-open':'fa-lock' ?>"></i></button>
                                </form>
                                <button onclick="confirmarExclusao(<?= $u['id'] ?>)" class="btn btn-sm btn-danger rounded-circle"><i class="fas fa-trash"></i></button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr><td colspan="4" class="text-center py-4 text-muted">Nenhum encontrado.</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</main>

<div class="modal fade" id="modalEditar" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content bg-dark border-secondary">
            <div class="modal-header border-secondary"><h5 class="modal-title">Editar</h5><button class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
            <form method="POST">
                <input type="hidden" name="acao" value="editar">
                <input type="hidden" name="id_user" id="edit_id">
                <div class="modal-body">
                    <div class="mb-2"><label>Nome</label><input type="text" name="nome" id="edit_nome" class="form-control"></div>
                    <div class="row g-2">
                        <div class="col-6"><label>Usuário</label><input type="text" name="usuario" id="edit_user" class="form-control"></div>
                        <div class="col-6"><label>Senha</label><input type="text" name="senha" id="edit_pass" class="form-control"></div>
                    </div>
                    <div class="mt-2"><label class="text-warning">Vencimento</label><input type="date" name="vencimento_edit" id="edit_venc" class="form-control"></div>
                    <div class="mt-2"><label>Conexões</label><input type="number" name="conexao" id="edit_con" class="form-control"></div>
                </div>
                <div class="modal-footer border-secondary"><button class="btn btn-primary w-100">Salvar</button></div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="modalRenovar" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content bg-dark border-secondary">
            <div class="modal-header border-secondary"><h5 class="modal-title">Renovar <span id="renov_nome" class="text-primary"></span></h5><button class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
            <form method="POST">
                <input type="hidden" name="acao" value="renovar">
                <input type="hidden" name="id_user" id="renov_id">
                <input type="hidden" name="tipo_renovacao" id="tipo_renovacao" value="meses">
                <input type="hidden" name="qtd_meses" id="qtd_meses" value="1">
                <div class="modal-body">
                    <div class="row g-2">
                        <div class="col-6"><button type="button" class="btn btn-renov" onclick="setRenov('meses', 1)">+1 Mês</button></div>
                        <div class="col-6"><button type="button" class="btn btn-renov" onclick="setRenov('meses', 3)">+3 Meses</button></div>
                        <div class="col-6"><button type="button" class="btn btn-renov" onclick="setRenov('meses', 6)">+6 Meses</button></div>
                        <div class="col-6"><button type="button" class="btn btn-renov" onclick="setRenov('meses', 12)">+1 Ano</button></div>
                    </div>
                    <a data-bs-toggle="collapse" href="#areaManual" class="d-block mt-3 text-muted small text-decoration-none">Opção manual &darr;</a>
                    <div class="collapse mt-2" id="areaManual">
                        <input type="date" name="nova_data_manual" id="data_manual" class="form-control" onchange="setRenov('manual',0)">
                    </div>
                </div>
                <button type="submit" id="btnSubmitRenov" class="d-none"></button>
            </form>
        </div>
    </div>
</div>

<form id="formExcluir" method="POST"><input type="hidden" name="acao" value="excluir"><input type="hidden" name="id_user" id="delete_id"></form>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    function toggleMenu() { document.getElementById('sidebar').classList.toggle('show'); document.getElementById('overlay').classList.toggle('show'); }
    function formatInput(s) { if(!s)return''; if(!isNaN(s)&&s.length>8){return new Date(s*1000).toISOString().split('T')[0];} if(s.includes('/')){let p=s.split('/');if(p.length>=3)return p[2]+'-'+p[1]+'-'+p[0];} return s.substring(0,10); }

    function abrirEditar(u) {
        document.getElementById('edit_id').value = u.id;
        document.getElementById('edit_nome').value = u.nome.replace(/<[^>]*>?/gm, ''); 
        document.getElementById('edit_user').value = u.usuario;
        document.getElementById('edit_pass').value = u.senha;
        document.getElementById('edit_con').value = u.conexao;
        document.getElementById('edit_venc').value = formatInput(u.data_premio);
        new bootstrap.Modal(document.getElementById('modalEditar')).show();
    }

    function abrirRenovar(id, nome) {
        document.getElementById('renov_id').value = id;
        document.getElementById('renov_nome').innerText = nome.replace(/<[^>]*>?/gm, '');
        new bootstrap.Modal(document.getElementById('modalRenovar')).show();
    }

    function setRenov(tipo, valor) {
        document.getElementById('tipo_renovacao').value = tipo;
        if(tipo === 'meses') { document.getElementById('qtd_meses').value = valor; document.getElementById('btnSubmitRenov').click(); }
    }

    function confirmarExclusao(id) {
        if(confirm('Tem certeza?')) { document.getElementById('delete_id').value = id; document.getElementById('formExcluir').submit(); }
    }

    window.onload = function() {
        let texto = `<?= $texto_zap ?>`;
        if(texto.trim() !== "") new bootstrap.Modal(document.getElementById('modalZap')).show();
    }
    function copiarTexto() { document.getElementById("textoZapArea").select(); document.execCommand("copy"); alert("Copiado!"); }
    function enviarZap() { window.open("https://api.whatsapp.com/send?text=" + encodeURIComponent(document.getElementById("textoZapArea").value), '_blank'); }
</script>
</body>
</html>
