<?php
/**
 * ARQUIVO: pesquisa_orcamento.php
 */
include '../configuracao/conexao.php';

if (!isset($mysqli) || $mysqli->connect_error) {
    die("Erro de conexão.");
}

$busca = $_GET['q'] ?? '';
$searchTerms = "%" . $busca . "%";

// Query com GROUP BY para evitar duplicidade e garantir integridade dos dados
// SQL CORRIGIDO: Filtra por Status 'A' e usa GROUP BY para evitar duplicados
$sql = "SELECT c.*, p.reg_0150_nome 
        FROM nf_cab c
        LEFT JOIN reg_0150 p ON c.nf_cab_cod_part = p.reg_0150_cod_part
        LEFT JOIN nf_itens i ON c.codigo = i.nf_itens_nf_cab
        WHERE (c.nf_cab_status = 'p') 
          AND (c.codigo LIKE ? OR c.nf_cab_nome LIKE ? OR p.reg_0150_nome LIKE ?)
        GROUP BY c.codigo
        ORDER BY c.codigo DESC LIMIT 20";

$stmt = $mysqli->prepare($sql);
$stmt->bind_param("sss", $searchTerms, $searchTerms, $searchTerms);
$stmt->execute();
$result = $stmt->get_result();
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Pesquisar Orçamentos</title>
    <style>
        body { background: #d4d0c8; font-family: "Tahoma", sans-serif; font-size: 11px; margin: 10px; }
        .orc-card { background: #c0c0c0; border: 2px solid; border-color: #fff #808080 #808080 #fff; margin-bottom: 15px; padding: 2px; }
        .orc-header { background: #000080; color: #fff; padding: 4px; font-weight: bold; display: flex; justify-content: space-between; align-items: center; }
        .orc-body { padding: 5px; display: flex; justify-content: space-between; align-items: center; background: #d4d0c8; border-bottom: 1px solid #808080; }
        .table-itens { width: 100%; border-collapse: collapse; background: #fff; font-size: 10px; }
        .table-itens th { background: #d4d0c8; border: 1px solid #808080; text-align: left; padding: 2px; }
        .table-itens td { border: 1px solid #f0f0f0; padding: 2px; }
        .btn-select { color: #000080; cursor: pointer; text-decoration: underline; font-weight: bold; margin-right: 10px; }
        .btn-delete { color: #800000; cursor: pointer; text-decoration: underline; }
        input[type="text"] { border: 2px inset #fff; padding: 3px; background: #fff; width: 200px; }
        .total-destaque { color: #ffff00; margin-left: 15px; font-weight: bold; }
    </style>
</head>
<body>

    <div style="margin-bottom: 10px;">
        <form method="GET">
            Localizar: <input type="text" name="q" value="<?= htmlspecialchars($busca) ?>" autofocus>
            <button type="submit" style="padding: 2px 10px; cursor: pointer;">OK</button>
        </form>
    </div>

    <?php while ($nf = $result->fetch_assoc()): 
        $id_nf = $nf['codigo'];
        // Busca os itens para listar no card e calcular a soma dos totais se necessário
        $res_itens = $mysqli->query("SELECT * FROM nf_itens WHERE nf_itens_nf_cab = '$id_nf'");
        $itens = [];
        while($it = $res_itens->fetch_assoc()) { $itens[] = $it; }
    ?>
        <div class="orc-card">
            <div class="orc-header">
                <div>
                    ORDEM: <?= $id_nf ?> - <?= htmlspecialchars($nf['nf_cab_nome']) ?>-
					
					<strong>Tipo:</strong> 

					
					
					 <?= ($nf['nf_cab_c_v'] == 'S') ? 'SAÍDA' : 'ENTRADA' ?>
                    <span class="total-destaque">TOTAL: R$ <?= number_format($nf['nf_cab_tot_nf'], 2, ',', '.') ?></span>
                </div>
                <div><small><?= date('d/m/Y', strtotime($nf['nf_cab_dt_emi'])) ?></small></div>
            </div>
            
            <div class="orc-body">
                <div><strong>Status:</strong> <?= $nf['nf_cab_status'] ?></div>
                <div>
                    <a class="btn-select" onclick='selecionarnf(<?= json_encode(["cabecalho" => $nf, "itens" => $itens]) ?>)'>[ SELECIONAR ]</a>
                    <a class="btn-delete" onclick="confirmarExclusao(<?= $id_nf ?>)">[ APAGAR ]</a>
                </div>
            </div>

            <table class="table-itens">
                <thead>
                    <tr>
                        <th width="50">Código</th>
                        <th>Descrição Item</th>
                        <th width="40">Qtd</th>
                        <th width="80">Vl. Unit</th>
                        <th width="80">Total Item</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($itens as $it): ?>
                    <tr>
                        <td><?= $it['nf_itens_cod_item'] ?></td>
                        <td><?= htmlspecialchars($it['nf_itens_descr_item']) ?></td>
                        <td><?= number_format($it['nf_itens_qtd_item'], 2, ',', '.') ?></td>
                        <td><?= number_format($it['nf_itens_vl_item'], 2, ',', '.') ?></td>
                        <td style="font-weight: bold; background: #f9f9f9;"><?= number_format($it['nf_itens_tot_item'], 2, ',', '.') ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endwhile; ?>

    <script>
        function selecionarnf(dados) {
            if (window.opener && !window.opener.closed) {
                window.opener.carregarDadosDoBanco(dados);
                window.close();
            }
        }

        function confirmarExclusao(id) {
            if (confirm("Deseja apagar o orçamento " + id + "?")) {
                window.location.href = 'processar_nf.php?acao=excluir&id=' + id;
            }
        }
    </script>
</body>
</html>