<?php  session_start();
if (!isset($_SESSION['id'])) { header("Location: ../index/index.php"); exit(); }
?>
<?php
/**
 * ARQUIVO: busca_nf.php
 * Atualizado para suportar o campo nf_itens_nat_oper
 */
include '../configuracao/conexao.php';

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

// 1. Captura dos filtros via GET
$busca = $_GET['q'] ?? '';
$statusFiltro = $_GET['status'] ?? ''; 
$tipoFiltro = $_GET['tipo'] ?? '';   
$searchTerms = "%" . $busca . "%";

// 2. Construção da Query Dinâmica
$sql = "SELECT c.*, p.reg_0150_nome 
        FROM ped_cab c
        LEFT JOIN reg_0150 p ON c.ped_cab_cod_part = p.reg_0150_cod_part
        WHERE (c.codigo LIKE ? OR c.ped_cab_nome LIKE ? OR p.reg_0150_nome LIKE ?)";

if ($statusFiltro !== '') {
    $sql .= " AND c.ped_cab_status = '" . $mysqli->real_escape_string($statusFiltro) . "'";
}

if ($tipoFiltro !== '') {
    $sql .= " AND c.ped_cab_c_v = '" . $mysqli->real_escape_string($tipoFiltro) . "'";
}

$sql .= " GROUP BY c.codigo ORDER BY c.codigo DESC LIMIT 30";

$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 Notas Fiscais</title>
    <style>
        body { background: #d4d0c8; font-family: "Tahoma", sans-serif; font-size: 11px; margin: 10px; }
        .barra-busca { 
            background: #c0c0c0; 
            padding: 8px; 
            border: 2px solid; 
            border-color: #fff #808080 #808080 #fff; 
            margin-bottom: 15px; 
        }
        .form-row { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
        .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"], select { border: 2px inset #fff; padding: 2px; background: #fff; }
        .total-destaque { color: #ffff00; margin-left: 15px; font-weight: bold; }
        .status-badge { padding: 1px 4px; border: 1px solid #808080; background: #ffff00; color: #000; font-weight: bold; }
    </style>
</head>
<body>

    <div class="barra-busca">
        <form method="GET" class="form-row">
            <label>Localizar:</label>
            <input type="text" name="q" value="<?= htmlspecialchars($busca) ?>" placeholder="Nome, código ou participante..." style="width: 180px;">
            
            <label>Tipo:</label>
            <select name="tipo">
                <option value="">[ TODOS ]</option>
                <option value="S" <?= $tipoFiltro == 'S' ? 'selected' : '' ?>>SAÍDA</option>
                <option value="E" <?= $tipoFiltro == 'E' ? 'selected' : '' ?>>ENTRADA</option>
            </select>

            <label>Status:</label>
            <select name="status">
                <option value="">[ TODOS ]</option>
                <option value="p" <?= $statusFiltro == 'p' ? 'selected' : '' ?>>P - Pendente</option>
                <option value="f" <?= $statusFiltro == 'f' ? 'selected' : '' ?>>F - Fechada</option>
                <option value="m" <?= $statusFiltro == 'm' ? 'selected' : '' ?>>M - Emitida</option>
            </select>

            <button type="submit" style="padding: 2px 15px; cursor: pointer; font-weight: bold;">Pesquisar</button>
        </form>
    </div>

    <?php while ($ped = $result->fetch_assoc()): 
        $id_ped = $ped['codigo'];
        // Busca itens incluindo a natureza da operação
        $res_itens = $mysqli->query("SELECT * FROM ped_itens WHERE ped_itens_ped_cab = '$id_ped'");
        $itens = [];
        while($it = $res_itens->fetch_assoc()) { 
            // Mapeia os nomes das colunas do banco para os nomes esperados pelo JS no index.php
            $itens[] = [
                'ped_itens_cod_item'   => $it['ped_itens_cod_item'],
                'ped_itens_descr_item' => $it['ped_itens_descr_item'],
                'ped_itens_marca_item' => $it['ped_itens_marca_item'],
                'ped_itens_unid'       => $it['ped_itens_unid'],
                'ped_itens_tipo_item'  => $it['ped_itens_tipo_item'],
 
                'item_qtd'            => $it['ped_itens_qtd_item'],
                'item_vl'             => $it['ped_itens_vl_item'],
                'item_desc'           => $it['ped_itens_desc_item_vl'],
                'item_tot'            => $it['ped_itens_tot_item']
				// MAPEAMENTO DOS IMPOSTO
            ]; 
        }
    ?>
        <div class="orc-card">
            <div class="orc-header">
                <div>
                    ped: <?= $id_ped ?> - <?= htmlspecialchars($ped['ped_cab_nome'] ?? '') ?> -
                    <strong>TIPO:</strong> <?= ($ped['ped_cab_c_v'] == 'S') ? 'SAÍDA' : 'ENTRADA' ?>
                    <span class="total-destaque">TOTAL: R$ <?= number_format($ped['ped_cab_tot_ped'], 2, ',', '.') ?></span>
                </div>
                <div><small><?= date('d/m/Y', strtotime($ped['ped_cab_dt_emi'])) ?></small></div>
            </div>
            
            <div class="orc-body">
                <div>
                    <strong>Status:</strong> 
                    <span class="status-badge"><?= strtoupper($ped['ped_cab_status']) ?></span>
                    <span style="margin-left:10px;"><strong>Participante:</strong> <?= htmlspecialchars($ped['reg_0150_nome'] ?? 'Não ipedormado') ?></span>
                </div>
                <div>
                    <a class="btn-select" onclick='selecionarped(<?= json_encode(["cabecalho" => $ped, "itens" => $itens]) ?>)'>[ SELECIONAR ]</a>
                 

<?php if (strtoupper($ped['ped_cab_status']) == 'P'): ?>
                <a class="btn-delete" onclick="confirmarExclusao(<?= $id_ped ?>)">[ APAGAR ]</a>
            <?php endif; ?>
                </div>
            </div>

            <table class="table-itens">
                <thead>
                    <tr>
                        <th width="60">Cód. Item</th>
                        <th>Descrição do Produto/Serviço</th>
                 
                        <th width="50">Qtd</th>
                        <th width="90">Vl. Unit</th>
                        <th width="90">Total</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($itens as $it): ?>
                    <tr>
                        <td><?= $it['ped_itens_cod_item'] ?></td>
                        <td><?= htmlspecialchars($it['ped_itens_descr_item']) ?></td>
                        
                        <td><?= number_format($it['item_qtd'], 2, ',', '.') ?></td>
                        <td><?= number_format($it['item_vl'], 2, ',', '.') ?></td>
                        <td style="font-weight: bold; background: #f9f9f9;"><?= number_format($it['item_tot'], 2, ',', '.') ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endwhile; ?>

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

        function confirmarExclusao(id) {
            if (confirm("Tem certeza que deseja apagar o registro nº " + id + "?")) {
                window.location.href = 'processar_ped.php?acao=excluir&id=' + id;
            }
        }
    </script>
</body>
</html>