<?php  session_start();
if (!isset($_SESSION['id'])) { header("Location: ../index/index.php"); exit(); }
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Localizar Item</title>
    <style>
        body { background: #c0c0c0; 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: #d4d0c8; border: 1px solid #808080; padding: 4px; text-align: left; }
        .win-table td { border: 1px solid #f0f0f0; padding: 4px; cursor: pointer; }
        .win-table tr:hover td { background: #000080; color: #fff; }
        input { width: 100%; padding: 4px; border: 2px inset #fff; margin-bottom: 8px; }
    </style>
</head>
<body>
    <input type="text" id="txtProd" placeholder="Pesquisar..." onkeyup="pesquisar()">
    
    <table class="win-table" id="resProd">
        <thead>
            <tr>
                <th>Código</th>
                <th>Descrição</th>
                <th>Marca</th>
                <th>Unid</th>
                <th>Preço</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>

    <script>
        const urlParams = new URLSearchParams(window.location.search);
        const targetId = urlParams.get('target');

        function pesquisar() {
            let q = document.getElementById('txtProd').value;
            if(q.length < 2) return;

            fetch('busca_veiculo_motor.php?q=' + q)
            .then(res => res.json())
            .then(data => {
                let html = '';
                data.forEach(item => {
                    // Passamos todos os dados técnicos no clique
                    html += `<tr onclick="selecionar('${item.reg_0200_cod_item}', '${item.reg_0200_descr_item}', '${item.reg_0200_preco}', '${item.reg_0200_unid_inv}', '${item.reg_0200_grupo}', '${item.reg_0200_tipo_item_produt}')">
                                <td>${item.reg_0200_cod_item}</td>
                                <td>${item.reg_0200_descr_item}</td>
                                <td>${item.reg_0200_grupo}</td>
                                <td>${item.reg_0200_unid_inv}</td>
                                <td>${item.reg_0200_preco}</td>
                             </tr>`;
                });
                document.querySelector('#resProd tbody').innerHTML = html;
            });
        }

        function selecionar(codigo, descr) {
            const win = window.opener;
            // Preenche os campos padrão
            win.document.getElementById('val_ped_cab_cod_veiculo').value = codigo;
            win.document.getElementById('val_ped_cab_desc_veiculo').value = descr;
            // Preenche os novos campos técnicos
             
            window.close();
        }
    </script>
</body>
</html>