<?php
include '../configuracao/conexao.php';

// Recebe o termo de busca por descrição
$busca = $_GET['busca'] ?? '';
$busca_limpa = $mysqli->real_escape_string($busca);

// Query filtrando sempre por Ativo='S' e Tipo='C'
$sql = "SELECT trib_cont_descr_nat, trib_cont_cta_debito, trib_cont_cta_credito 
        FROM trib_cont 
        WHERE ativo = 'S' 
        AND trib_cont_tipo_cv = 'C' 
        AND trib_cont_descr_nat LIKE '%$busca_limpa%' 
        ORDER BY trib_cont_descr_nat ASC";

$res = $mysqli->query($sql);
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <style>
        body { background: #d4d0c8; font-family: "Tahoma", sans-serif; font-size: 11px; margin: 10px; }
        .win-table { width: 100%; border-collapse: collapse; background: #fff; border: 2px inset #fff; }
        .win-table th { background: #000080; color: white; text-align: left; padding: 4px; position: sticky; top: 0; }
        .win-table td { border: 1px solid #d4d0c8; padding: 4px; cursor: pointer; }
        .win-table tr:hover { background: #0a246a; color: white; }
        
        /* Barra de busca estilo retro */
        .search-pane { border: 2px inset #fff; padding: 6px; margin-bottom: 8px; display: flex; gap: 5px; align-items: center; }
        input { border: 2px inset #fff; padding: 3px; font-family: "Tahoma"; font-size: 11px; flex: 1; }
        .btn-win { background: #d4d0c8; border: 2px solid; border-color: #fff #808080 #808080 #fff; cursor: pointer; padding: 2px 10px; }
        .btn-win:active { border-color: #808080 #fff #fff #808080; }
    </style>
</head>
<body>

    <form method="GET" class="search-pane">
        <label>Descrição:</label>
        <input type="text" name="busca" value="<?= htmlspecialchars($busca) ?>" autofocus>
        <button type="submit" class="btn-win">Filtrar</button>
    </form>

    <table class="win-table">
        <thead>
            <tr>
                <th>Descrição da Natureza</th>
                <th>Débito</th>
                <th>Crédito</th>
            </tr>
        </thead>
        <tbody>
            <?php if ($res && $res->num_rows > 0): ?>
                <?php while($r = $res->fetch_assoc()): ?>
                <tr onclick="window.opener.definirNatureza('<?= $r['trib_cont_descr_nat'] ?>','<?= $r['trib_cont_cta_debito'] ?>','<?= $r['trib_cont_cta_credito'] ?>'); window.close();">
                    <td><?= htmlspecialchars($r['trib_cont_descr_nat']) ?></td>
                    <td style="text-align:center;"><?= htmlspecialchars($r['trib_cont_cta_debito']) ?></td>
                    <td style="text-align:center;"><?= htmlspecialchars($r['trib_cont_cta_credito']) ?></td>
                </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr><td colspan="3" style="text-align:center; padding:10px;">Nenhuma natureza encontrada.</td></tr>
            <?php endif; ?>
        </tbody>
    </table>

</body>
</html>