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

$tabela_origem  = $_GET['tabela'] ?? '';
$campo_retorno  = $_GET['campo']  ?? ''; 
$target         = $_GET['target'] ?? ''; 
$pesquisa       = $_GET['pesquisa'] ?? '';

// Sanitização básica
$tabela_origem  = preg_replace('/[^a-zA-Z0-9_]/', '', $tabela_origem);
$campo_retorno  = preg_replace('/[^a-zA-Z0-9_]/', '', $campo_retorno);
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Busca Rápida</title>
    <style>
        body { background-color: #c0c0c0; font-family: "Tahoma", sans-serif; font-size: 11px; margin: 0; padding: 10px; }
        .win-window { border: 2px solid; border-color: #fff #808080 #808080 #fff; height: 380px; display: flex; flex-direction: column; box-shadow: 1px 1px 0 0 #000; }
        .win-title { background: #000080; color: white; padding: 3px 6px; font-weight: bold; display: flex; justify-content: space-between; }
        .win-content { padding: 10px; flex: 1; overflow: auto; background: #dfdfdf; display: flex; flex-direction: column; }
        .win-input { border: 2px solid; border-color: #808080 #fff #fff #808080; padding: 3px; background: #fff; font-size: 11px; }
        .win-btn { background: #c0c0c0; border: 2px solid; border-color: #fff #808080 #808080 #fff; padding: 4px 12px; cursor: pointer; font-size: 11px; }
        .win-table-container { flex: 1; overflow-y: auto; background: #fff; border: 2px solid; border-color: #808080 #fff #fff #808080; margin-top: 10px; }
        .win-table { width: 100%; border-collapse: collapse; }
        .win-table th { background: #c0c0c0; border: 1px solid #808080; padding: 4px; text-align: left; position: sticky; top: 0; font-size: 10px; text-transform: uppercase; }
        .win-table td { border: 1px solid #dfdfdf; padding: 4px; cursor: pointer; }
        .win-table tr:hover td { background: #000080; color: #fff; }
    </style>
    <script>
        function selecionar(id, desc) {
            if (window.opener && !window.opener.closed) {
                const d = window.opener.document.getElementById('display_<?php echo $target; ?>');
                const v = window.opener.document.getElementById('value_<?php echo $target; ?>');
                if(d) d.value = desc;
                if(v) v.value = id;
            }
            window.close();
        }
    </script>
</head>
<body>

<div class="win-window">
    <div class="win-title">
        <span>Pesquisar em <?php echo htmlspecialchars($tabela_origem); ?></span>
        <span>[X]</span>
    </div>
    
    <div class="win-content">
        <form method="GET" style="display: flex; gap: 5px; margin-bottom: 5px;">
            <input type="hidden" name="tabela" value="<?php echo $tabela_origem; ?>">
            <input type="hidden" name="campo" value="<?php echo $campo_retorno; ?>">
            <input type="hidden" name="target" value="<?php echo $target; ?>">
            <input type="text" name="pesquisa" class="win-input" style="flex:1" 
                   placeholder="Localizar..." value="<?php echo htmlspecialchars($pesquisa); ?>" autofocus>
            <button type="submit" class="win-btn">Procurar</button>
        </form>

        <div class="win-table-container">
            <table class="win-table">
                <thead>
                    <tr>
                        <?php
                        // Busca os nomes técnicos das colunas configuradas
                        $sql_t = "SELECT tabela_campo_1, tabela_campo_2, tabela_campo_3 FROM tabela WHERE tabela_nome = '$tabela_origem' LIMIT 1";
                        $res_t = $mysqli->query($sql_t);
                        $reg_t = $res_t->fetch_assoc();

                        // Define as colunas para o cabeçalho cinza e para a consulta
                        $campos_view = array_filter([
                            $reg_t['tabela_campo_1'], 
                            $reg_t['tabela_campo_2'], 
                            $reg_t['tabela_campo_3']
                        ]);

                        foreach ($campos_view as $coluna) {
                            echo "<th>" . htmlspecialchars($coluna) . "</th>";
                        }
                        ?>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    if ($tabela_origem && !empty($campos_view)) {
                        // Garante que o campo de retorno e o código estejam na query
                        $colunas_sql = implode(", ", array_unique(array_merge($campos_view, ['codigo', $campo_retorno])));
                        $sql = "SELECT $colunas_sql FROM `$tabela_origem` WHERE 1=1 ";

                        if (!empty($pesquisa)) {
                            $p = $mysqli->real_escape_string($pesquisa);
                            $filtros = [];
                            foreach ($campos_view as $cv) {
                                $filtros[] = "`$cv` LIKE '%$p%'";
                            }
                            $sql .= " AND (" . implode(" OR ", $filtros) . ")";
                        }

                        $sql .= " LIMIT 50";
                        $res = $mysqli->query($sql);

                        if ($res && $res->num_rows > 0) {
                            while ($r = $res->fetch_assoc()) {
                                $val_desc = addslashes($r[$campo_retorno]);
                                echo "<tr onclick=\"selecionar('{$r['codigo']}', '$val_desc')\">";
                                foreach ($campos_view as $cv) {
                                    echo "<td>" . htmlspecialchars($r[$cv]) . "</td>";
                                }
                                echo "</tr>";
                            }
                        } else {
                            echo "<tr><td colspan='".count($campos_view)."' style='text-align:center; padding:20px;'>Nenhum registro encontrado.</td></tr>";
                        }
                    }
                    ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

</body>
</html>