<?php
/**
 * ARQUIVO: busca_faturamento.php
 * Finalidade: Pesquisa com filtros adicionais (Datas e Status) e JOIN triplo.
 */
include '../configuracao/conexao.php';

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

// 1. Captura de Filtros
$busca       = $_GET['q'] ?? '';
$data_inicio = $_GET['dt_ini'] ?? '';
$data_fim    = $_GET['dt_fim'] ?? '';
$status_filtro = $_GET['st'] ?? '';

$searchTerms = "%" . $busca . "%";

// 2. Construção dinâmica da Query
$sql = "SELECT 
            c.codigo, 
            c.data, 
            c.reg_c140_num_tit, 
            c.reg_c140_vl_tit, 
            c.reg_c140_desc_tit,
            c.reg_c140_ind_emit,
            c.reg_c140_qtd_parc,
            c.reg_c140_ind_tit,
            c.reg_c140_status,
			c.reg_c140_nat_oper,
            p.reg_0150_nome 
        FROM reg_c140 c
        LEFT JOIN reg_c141 i ON c.codigo = i.reg_c141_c140_origem
        LEFT JOIN reg_0150 p ON i.reg_c141_cod_part = p.reg_0150_cod_part
        WHERE (c.codigo LIKE ? OR c.reg_c140_num_tit LIKE ? OR p.reg_0150_nome LIKE ?)";

// Adiciona filtros se preenchidos
if ($data_inicio) $sql .= " AND c.data >= '$data_inicio'";
if ($data_fim)    $sql .= " AND c.data <= '$data_fim'";
if ($status_filtro) $sql .= " AND c.reg_c140_status = '$status_filtro'";

$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 Faturamento - Morfo Engine</title>
    <style>
        body { background: #d4d0c8; font-family: "Tahoma", sans-serif; font-size: 11px; margin: 10px; }
        .fat-card { background: #c0c0c0; border: 2px solid; border-color: #fff #808080 #808080 #fff; margin-bottom: 15px; padding: 2px; }
        .fat-header { background: #000080; color: #fff; padding: 4px; font-weight: bold; display: flex; justify-content: space-between; }
        .table-itens { width: 100%; border-collapse: collapse; background: #fff; font-size: 10px; }
        .table-itens th { background: #d4d0c8; border: 1px solid #808080; padding: 2px; }
        .table-itens td { border: 1px solid #f0f0f0; padding: 2px; }
        .btn-select { color: #ffff00; cursor: pointer; text-decoration: underline; font-weight: bold; }
        
        /* Estilo Win2000 para os novos filtros */
        input[type="text"], input[type="date"], select { 
            border: 2px inset #fff; padding: 2px; background: #fff; font-family: "Tahoma"; font-size: 11px;
        }
        .filter-bar { 
            margin-bottom: 15px; background: #c0c0c0; padding: 8px; 
            border: 2px solid; border-color: #fff #808080 #808080 #fff;
            display: flex; gap: 10px; align-items: center; flex-wrap: wrap;
        }
    </style>
</head>
<body>

    <div class="filter-bar">
        <form method="GET" style="display: flex; gap: 10px; align-items: center; flex-wrap: wrap;">
            <div>
                <strong>Localizar:</strong> 
                <input type="text" name="q" value="<?= htmlspecialchars($busca) ?>" placeholder="Nº ou Nome..." style="width:150px">
            </div>
            
            <div>
                <strong>Período:</strong>
                <input type="date" name="dt_ini" value="<?= $data_inicio ?>"> a 
                <input type="date" name="dt_fim" value="<?= $data_fim ?>">
            </div>

            <div>
                <strong>Status:</strong>
                <select name="st">
                    <option value="">Todos</option>
                    <option value="P" <?= $status_filtro == 'P' ? 'selected' : '' ?>>Pendente (P)</option>
                    <option value="A" <?= $status_filtro == 'A' ? 'selected' : '' ?>>Aberto (A)</option>
                    <option value="F" <?= $status_filtro == 'F' ? 'selected' : '' ?>>Finalizado (F)</option>
                </select>
            </div>

            <button type="submit" style="padding: 2px 10px; font-weight: bold; cursor: pointer; background: #d4d0c8; border: 2px solid; border-color: #fff #808080 #808080 #fff;">FILTRAR</button>
            <button type="button" onclick="window.location.href='busca_faturamento.php'" style="padding: 2px 10px; cursor: pointer; background: #d4d0c8; border: 2px solid; border-color: #fff #808080 #808080 #fff;">LIMPAR</button>
        </form>
    </div>

    <?php while ($fat = $result->fetch_assoc()): 
        $id_fat = $fat['codigo'];
        $res_itens = $mysqli->query("SELECT * FROM reg_c141 WHERE reg_c141_c140_origem = '$id_fat'");
        $itens = [];
        while($it = $res_itens->fetch_assoc()) { $itens[] = $it; }
    ?>
        <div class="fat-card">
            <div class="fat-header">
                <div>
                    ID: <?= $id_fat ?> | DOC: <?= htmlspecialchars($fat['reg_c140_num_tit']) ?> | 
                    <span style="color: #00ff00;">PARTICIPANTE: <?= htmlspecialchars($fat['reg_0150_nome'] ?? 'NÃO ENCONTRADO') ?></span>
                    | <span style="background:#fff; color:#000; padding: 0 4px;">Status: <?= $fat['reg_c140_status'] ?></span>
                </div>
                <a class="btn-select" onclick='selecionarFaturamento(<?= json_encode(["faturamento" => $fat, "parcelas" => $itens]) ?>)'>[ SELECIONAR ]</a>
            </div>
            
            <table class="table-itens">
                <thead>
                    <tr>
                        <th width="40">Parc.</th>
                        <th width="80">Vencimento</th>
                        <th width="100">Valor</th>
                        <th width="60">Status</th>
                        <th>Meio</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($itens as $it): 
                        $st = $it['reg_c141_status'] ?? 'A';
                        $corSt = ($st == 'F') ? 'green' : (($st == 'P') ? 'red' : 'blue');
                    ?>
                    <tr>
                        <td align="center"><?= $it['reg_c141_num_parc'] ?></td>
                        <td align="center"><?= date('d/m/Y', strtotime($it['reg_c141_dt_vcto'])) ?></td>
                        <td align="right" style="font-weight: bold;">R$ <?= number_format((float)$it['reg_c141_vl_parc'], 2, ',', '.') ?></td>
                        <td align="center" style="color: <?= $corSt ?>; font-weight: bold;"><?= $st ?></td>
                        <td>BOLETO</td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endwhile; ?>

    <script>
        function selecionarFaturamento(dados) {
            if (window.opener && !window.opener.closed) {
                window.opener.carregarDadosDoBanco(dados);
                window.close();
            }
        }
    </script>
</body>
</html>