<?php
/**
 * MORFO ENGINE - PROCESSAMENTO (10 COLUNAS)
 * Regra: Total Item = Estoque Geral (NF + Pedido + Disponível) * Valor Unitário
 */
require_once("../configuracao/conexao.php"); 

$codIni      = $_POST['cod_ini'] ?? '0';
$codFim      = $_POST['cod_fim'] ?? '999999';
$busca       = $_POST['busca_txt'] ?? '';
$filtroSaldo = $_POST['filtro_saldo'] ?? 'T';

$sql = "SELECT h.reg_h010_cod_item, p.reg_0200_descr_item, h.reg_h010_unid, 
               t.reg_0200_tipo_item_codigo, h.reg_h010_qtd_nf, h.reg_h010_qtd_pedido,
               h.reg_h010_qtd, h.reg_h010_vl_item               
        FROM reg_h010 h
        INNER JOIN reg_0200 p ON h.reg_h010_cod_item = p.reg_0200_cod_item
        LEFT JOIN reg_0200_tipo_item t ON TRIM(p.reg_0200_tipo_item_produt) = TRIM(t.reg_0200_tipo_item_codigo)
        WHERE h.reg_h010_cod_item BETWEEN ? AND ?";

$params = [$codIni, $codFim];
$types  = "ss";

if (!empty($busca)) {
    $sql .= " AND p.reg_0200_descr_item LIKE ?";
    $params[] = "%$busca%";
    $types .= "s";
}

if ($filtroSaldo == 'P') $sql .= " AND h.reg_h010_qtd > 0";
elseif ($filtroSaldo == 'N') $sql .= " AND h.reg_h010_qtd < 0";

$sql .= " ORDER BY h.reg_h010_cod_item ASC";

$stmt = $mysqli->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $q_nf   = (float)$row['reg_h010_qtd_nf'];
        $q_ped  = (float)$row['reg_h010_qtd_pedido'];
        $q_disp = (float)$row['reg_h010_qtd'];
        $v_unit = (float)$row['reg_h010_vl_item'];
        
        // CÁLCULO DO ESTOQUE GERAL (SOMA FÍSICA)
        $est_geral  = $q_nf + $q_ped + $q_disp; 
        
        // NOVO CÁLCULO: TOTAL ITEM BASEADO NO ESTOQUE GERAL
        $total_item = $est_geral * $v_unit;

        $corNf   = ($q_nf > 0) ? "color:red;" : "";
        $corPed  = ($q_ped > 0) ? "color:red;" : "";
        $corDisp = ($q_disp < 0) ? "color:red;" : "color:blue; font-weight:bold;";

        echo "<tr>";
        echo "<td>{$row['reg_h010_cod_item']}</td>";
        echo "<td>" . mb_strtoupper($row['reg_0200_descr_item']) . "</td>";
        echo "<td align='center'>{$row['reg_h010_unid']}</td>";
        echo "<td align='center'>" . ($row['reg_0200_tipo_item_codigo'] ?? '--') . "</td>";
        echo "<td align='right' style='{$corNf}'>" . number_format($q_nf, 3, ',', '.') . "</td>";
        echo "<td align='right' style='{$corPed}'>" . number_format($q_ped, 3, ',', '.') . "</td>";
        echo "<td align='right' style='{$corDisp}'>" . number_format($q_disp, 3, ',', '.') . "</td>";
        
        // ESTOQUE GERAL
        echo "<td align='right' style='font-weight:bold; background:#dcdcdc;'>" . number_format($est_geral, 3, ',', '.') . "</td>";
        
        echo "<td align='right'>R$ " . number_format($v_unit, 2, ',', '.') . "</td>";
        
        // TOTAL BASEADO NO ESTOQUE GERAL
        echo "<td align='right' style='background:#d4d0c8; font-weight:bold;'>R$ " . number_format($total_item, 2, ',', '.') . "</td>";
        echo "</tr>";
    }
} else {
    echo "<tr><td colspan='10' align='center' style='padding:40px;'>Nenhum registro encontrado.</td></tr>";
}
?>