unit frm_PedidosPendientesLogistica;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
  Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls,
  Vcl.Buttons, Vcl.Grids, Vcl.DBGrids, Vcl.ComCtrls, Data.DB, FireDAC.Comp.Client,
  FireDAC.Stan.Param, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.DatS,
  FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet, uAppTheme, System.UITypes,
  Winapi.ShellAPI, System.IOUtils, System.Math, System.Generics.Collections,
  frxClass, frxDBSet, frm_PrintOptions, uFormatosImpresionService,
  FireDAC.Stan.Error, FireDAC.Phys.Intf, FireDAC.Stan.Async;

type
  TfrmPedidosPendientesLogistica = class(TForm)
    pnlHeader: TPanel;
    lblTitle: TLabel;
    lblSubtitle: TLabel;
    pnlKpiContainer: TPanel;
    pnlKpiArticulos: TPanel;
    lblKpiArticulosVal: TLabel;
    lblKpiArticulosLbl: TLabel;
    pnlKpiUnidades: TPanel;
    lblKpiUnidadesVal: TLabel;
    lblKpiUnidadesLbl: TLabel;
    pnlKpiBultos: TPanel;
    lblKpiBultosVal: TLabel;
    lblKpiBultosLbl: TLabel;
    pnlKpiPedidos: TPanel;
    lblKpiPedidosVal: TLabel;
    lblKpiPedidosLbl: TLabel;
    pnlKpiMasas: TPanel;
    lblKpiMasasVal: TLabel;
    lblKpiMasasLbl: TLabel;

    pnlFilters: TPanel;
    lblModoVista: TLabel;
    cbbModoVista: TComboBox;
    lblEmpresa: TLabel;
    cbbEmpresa: TComboBox;
    lblFechaEntrega: TLabel;
    cbbFechaEntrega: TComboBox;
    lblEstado: TLabel;
    cbbEstado: TComboBox;
    chkFiltrarFecha: TCheckBox;
    dtpDesde: TDateTimePicker;
    dtpHasta: TDateTimePicker;
    lblBuscar: TLabel;
    edtBuscar: TEdit;
    btnRefrescar: TBitBtn;
    btnExportar: TBitBtn;
    btnImprimir: TBitBtn;
    btnAjustarCuartos: TBitBtn;

    pnlBody: TPanel;
    pnlMaster: TPanel;
    pnlMasterHeader: TPanel;
    lblMasterTitle: TLabel;
    dbgProductos: TDBGrid;
    splDetail: TSplitter;

    pnlDetail: TPanel;
    pnlDetailHeader: TPanel;
    lblDetailTitle: TLabel;
    pcDetalle: TPageControl;
    tsDetallePedidos: TTabSheet;
    dbgDetallePedidos: TDBGrid;
    tsTotalesProductos: TTabSheet;
    pnlTotalesSummary: TPanel;
    lblTotalesSummaryText: TLabel;
    dbgTotalesProductos: TDBGrid;
    tsIngredientesMasas: TTabSheet;
    dbgIngredientesMasas: TDBGrid;

    pnlFooter: TPanel;
    btnAbrirPedido: TBitBtn;
    btnPrepararPedido: TBitBtn;
    btnCerrar: TBitBtn;

    qProductos: TFDQuery;
    dsProductos: TDataSource;
    qDetallePedidos: TFDQuery;
    dsDetallePedidos: TDataSource;
    qTotalesProductos: TFDQuery;
    dsTotalesProductos: TDataSource;
    saveDlgExport: TSaveDialog;
    frxDBProductos: TfrxDBDataset;
    frxDBTotales: TfrxDBDataset;
    qIngredientesMasas: TFDQuery;
    dsIngredientesMasas: TDataSource;
    frxDBIngredientes: TfrxDBDataset;

    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure cbbModoVistaChange(Sender: TObject);
    procedure cbbEmpresaChange(Sender: TObject);
    procedure cbbFechaEntregaChange(Sender: TObject);
    procedure cbbEstadoChange(Sender: TObject);
    procedure chkFiltrarFechaClick(Sender: TObject);
    procedure dtpDesdeChange(Sender: TObject);
    procedure dtpHastaChange(Sender: TObject);
    procedure edtBuscarChange(Sender: TObject);
    procedure btnRefrescarClick(Sender: TObject);
    procedure btnExportarClick(Sender: TObject);
    procedure btnAbrirPedidoClick(Sender: TObject);
    procedure btnPrepararPedidoClick(Sender: TObject);
    procedure btnImprimirClick(Sender: TObject);
    procedure btnAjustarCuartosClick(Sender: TObject);
    procedure btnCerrarClick(Sender: TObject);
    procedure qProductosAfterScroll(DataSet: TDataSet);
    procedure dbgProductosDrawColumnCell(Sender: TObject; const Rect: TRect;
      DataCol: Integer; Column: TColumn; State: TGridDrawState);
    procedure dbgProductosDblClick(Sender: TObject);
    procedure dbgDetallePedidosDrawColumnCell(Sender: TObject; const Rect: TRect;
      DataCol: Integer; Column: TColumn; State: TGridDrawState);
    procedure dbgDetallePedidosDblClick(Sender: TObject);
    procedure dbgTotalesProductosDrawColumnCell(Sender: TObject; const Rect: TRect;
      DataCol: Integer; Column: TColumn; State: TGridDrawState);
    procedure dbgIngredientesMasasDrawColumnCell(Sender: TObject; const Rect: TRect;
      DataCol: Integer; Column: TColumn; State: TGridDrawState);
    procedure FormResize(Sender: TObject);
    procedure pcDetalleChange(Sender: TObject);
  private
    FInitialEmpresaId: Integer;
    FLoadingFilters: Boolean;
    FAjustarCuartos: Boolean;
    FTotFabricar: Double;
    FTotMasas: Double;
    FTotPendientesPedidos: Double;
    FTotStockAlmacen: Double;
    function FormatearMasasStr(AMasas: Double): string;
    function GetSqlExprMasas(const ADeficitExpr: string): string;
    function GetSqlSubqueryRecetaCanonica: string;
    function CalcGridFlexWidth(AGrid: TDBGrid; AFixedSum, AMinFlexWidth: Integer; AWeight: Double = 1.0): Integer;
    procedure CargarModosVista;
    procedure CargarEmpresas;
    procedure CargarFechasEntrega;
    procedure CargarEstados;
    procedure SetupGrids;
    procedure RefrescarMaster;
    procedure RefrescarDetalle;
    procedure RefrescarTotalesProductos;
    procedure CargarIngredientesMasas;
    procedure ActualizarKPIs;
    function GetSelectedEmpresaId: Integer;
    function GetSelectedFechaEntregaVal: Integer;
    function GetActivePedidoId: string;
  public
    class procedure MostrarResumen(AOwner: TComponent; AEmpresaId: Integer = 0);
  end;

var
  frmPedidosPendientesLogistica: TfrmPedidosPendientesLogistica;

implementation

uses
  dmg_Main, frm_PedidosEditor, frm_PreparacionPedidoEditor,
  frm_PlanificacionMasasProduccion;

{$R *.dfm}

class procedure TfrmPedidosPendientesLogistica.MostrarResumen(AOwner: TComponent; AEmpresaId: Integer);
var
  LFrm: TfrmPedidosPendientesLogistica;
begin
  LFrm := TfrmPedidosPendientesLogistica.Create(AOwner);
  try
    LFrm.WindowState := wsMaximized;
    LFrm.FInitialEmpresaId := AEmpresaId;
    LFrm.ShowModal;
  finally
    LFrm.Free;
  end;
end;

function TfrmPedidosPendientesLogistica.CalcGridFlexWidth(AGrid: TDBGrid; AFixedSum, AMinFlexWidth: Integer; AWeight: Double = 1.0): Integer;
var
  LAvail, LRem: Integer;
begin
  Result := AMinFlexWidth;
  if not Assigned(AGrid) then Exit;
  LAvail := AGrid.ClientWidth;
  if dgIndicator in AGrid.Options then
    Dec(LAvail, 16);
  Dec(LAvail, 24); // vertical scrollbar + margin
  if LAvail > AFixedSum then
  begin
    LRem := LAvail - AFixedSum;
    Result := Max(AMinFlexWidth, Trunc(LRem * AWeight));
  end;
end;

procedure TfrmPedidosPendientesLogistica.FormResize(Sender: TObject);
begin
  if Visible and (not FLoadingFilters) then
    SetupGrids;
end;

procedure TfrmPedidosPendientesLogistica.pcDetalleChange(Sender: TObject);
begin
  if Visible and (not FLoadingFilters) then
    SetupGrids;
end;

procedure TfrmPedidosPendientesLogistica.FormCreate(Sender: TObject);
begin
  qProductos.Connection := dmgMain.dbConn;
  qDetallePedidos.Connection := dmgMain.dbConn;
  qTotalesProductos.Connection := dmgMain.dbConn;
  qIngredientesMasas.Connection := dmgMain.dbConn;
  frxDBProductos.DataSet := qProductos;
  frxDBTotales.DataSet := qTotalesProductos;
  frxDBIngredientes.DataSet := qIngredientesMasas;
  dtpDesde.Date := Date;
  dtpHasta.Date := Date + 7;
end;

procedure TfrmPedidosPendientesLogistica.FormDestroy(Sender: TObject);
begin
  qProductos.Close;
  qDetallePedidos.Close;
  qTotalesProductos.Close;
  qIngredientesMasas.Close;
end;

procedure TfrmPedidosPendientesLogistica.FormShow(Sender: TObject);
begin
  WindowState := wsMaximized;
  if pnlBody.ClientHeight > 550 then
    pnlDetail.Height := (pnlBody.ClientHeight * 38) div 100;

  FLoadingFilters := True;
  try
    TAppTheme.ApplyToForm(Self);
    CargarModosVista;
    CargarEmpresas;
    CargarEstados;
    CargarFechasEntrega;
    SetupGrids;
    btnAjustarCuartos.Hint := 'Planificar masas por receta a cuartos (+1/4) y generar lotes / stock envasado pendiente';
    btnAjustarCuartos.ShowHint := True;
  finally
    FLoadingFilters := False;
  end;
  RefrescarMaster;
end;

procedure TfrmPedidosPendientesLogistica.CargarModosVista;
begin
  cbbModoVista.Items.Clear;
  cbbModoVista.Items.Add('Por F. Entrega y Producto');
  cbbModoVista.Items.Add('Por Pedido / Orden Entrega');
  cbbModoVista.Items.Add('Consolidado Global Producto');
  cbbModoVista.ItemIndex := 0;
end;

procedure TfrmPedidosPendientesLogistica.CargarEmpresas;
var
  Qry: TFDQuery;
  I: Integer;
  LTargetEmpId: Integer;
begin
  cbbEmpresa.Items.Clear;
  cbbEmpresa.Items.AddObject('-- Todas las Empresas --', TObject(IntPtr(0)));

  Qry := TFDQuery.Create(nil);
  try
    Qry.Connection := dmgMain.dbConn;
    Qry.SQL.Text := 'SELECT id, nombre FROM ge_empresas WHERE activo = 1 ORDER BY nombre';
    Qry.Open;
    while not Qry.Eof do
    begin
      cbbEmpresa.Items.AddObject(
        Qry.FieldByName('nombre').AsString,
        TObject(IntPtr(Qry.FieldByName('id').AsInteger))
      );
      Qry.Next;
    end;
  finally
    Qry.Free;
  end;

  LTargetEmpId := FInitialEmpresaId;
  if LTargetEmpId <= 0 then
    LTargetEmpId := StrToIntDef(dmgMain.CurrentCompanyId, 1);

  cbbEmpresa.ItemIndex := 0;
  for I := 1 to cbbEmpresa.Items.Count - 1 do
  begin
    if Integer(IntPtr(cbbEmpresa.Items.Objects[I])) = LTargetEmpId then
    begin
      cbbEmpresa.ItemIndex := I;
      Break;
    end;
  end;
end;

procedure TfrmPedidosPendientesLogistica.CargarFechasEntrega;
var
  Qry: TFDQuery;
  LSql: string;
  LEmpId: Integer;
  LDate: TDateTime;
  LCount: Integer;
  LDateStr: string;
begin
  cbbFechaEntrega.Items.BeginUpdate;
  try
    cbbFechaEntrega.Items.Clear;
    cbbFechaEntrega.Items.AddObject('-- Todas las Fechas / Órdenes --', TObject(IntPtr(0)));

    LEmpId := GetSelectedEmpresaId;
    Qry := TFDQuery.Create(nil);
    try
      Qry.Connection := dmgMain.dbConn;
      LSql :=
        'SELECT DATE(p.fecha_entrega) AS f_ent, COUNT(DISTINCT p.id) AS num_pedidos ' +
        'FROM ge_pedidos p ' +
        'JOIN ge_pedidos_lineas pl ON pl.id_pedido = p.id ' +
        'WHERE p.estado IN (''PENDIENTE'', ''EN PREPARACION'', ''PROCESADO'') ';

      if LEmpId > 0 then
        LSql := LSql + 'AND p.empresa_id = :emp ';

      LSql := LSql +
        'GROUP BY DATE(p.fecha_entrega) ' +
        'ORDER BY f_ent ASC';

      Qry.SQL.Text := LSql;
      if LEmpId > 0 then
        Qry.ParamByName('emp').AsInteger := LEmpId;

      Qry.Open;
      while not Qry.Eof do
      begin
        if Qry.FieldByName('f_ent').IsNull then
        begin
          LCount := Qry.FieldByName('num_pedidos').AsInteger;
          cbbFechaEntrega.Items.AddObject(
            Format('Sin fecha asignada (%d ped.)', [LCount]),
            TObject(IntPtr(-1))
          );
        end
        else
        begin
          LDate := Qry.FieldByName('f_ent').AsDateTime;
          LCount := Qry.FieldByName('num_pedidos').AsInteger;
          LDateStr := FormatDateTime('dd/mm/yyyy', LDate) + Format(' (%d ped.)', [LCount]);
          cbbFechaEntrega.Items.AddObject(
            LDateStr,
            TObject(IntPtr(Trunc(LDate)))
          );
        end;
        Qry.Next;
      end;
    finally
      Qry.Free;
    end;

    cbbFechaEntrega.ItemIndex := 0;
  finally
    cbbFechaEntrega.Items.EndUpdate;
  end;
end;

procedure TfrmPedidosPendientesLogistica.CargarEstados;
begin
  cbbEstado.Items.Clear;
  cbbEstado.Items.Add('PENDIENTES Y EN PREPARACIÓN');
  cbbEstado.Items.Add('Solo PENDIENTES');
  cbbEstado.Items.Add('Solo EN PREPARACIÓN');
  cbbEstado.Items.Add('Solo PROCESADOS');
  cbbEstado.ItemIndex := 0;
end;

function TfrmPedidosPendientesLogistica.GetSelectedEmpresaId: Integer;
begin
  Result := 0;
  if cbbEmpresa.ItemIndex >= 0 then
    Result := Integer(IntPtr(cbbEmpresa.Items.Objects[cbbEmpresa.ItemIndex]));
end;

function TfrmPedidosPendientesLogistica.GetSelectedFechaEntregaVal: Integer;
begin
  Result := 0;
  if cbbFechaEntrega.ItemIndex >= 0 then
    Result := Integer(IntPtr(cbbFechaEntrega.Items.Objects[cbbFechaEntrega.ItemIndex]));
end;

function TfrmPedidosPendientesLogistica.GetActivePedidoId: string;
begin
  Result := '';
  case cbbModoVista.ItemIndex of
    0, 2: // Detalle contiene el pedido
    begin
      if not qDetallePedidos.IsEmpty and (qDetallePedidos.FindField('pedido_id') <> nil) then
        Result := qDetallePedidos.FieldByName('pedido_id').AsString;
    end;
    1: // Master contiene el pedido
    begin
      if not qProductos.IsEmpty and (qProductos.FindField('pedido_id') <> nil) then
        Result := qProductos.FieldByName('pedido_id').AsString;
    end;
  end;
end;

procedure TfrmPedidosPendientesLogistica.SetupGrids;
var
  LFixedMaster, LFixedDetail: Integer;
  LFlexMaster1, LFlexMaster2: Integer;
  LFlexDetail1, LFlexDetail2: Integer;
  LFixedTotales, LFlexTot1, LFlexTot2: Integer;
  LFixedIngr, LFlexIngr1, LFlexIngr2: Integer;
begin
  dbgProductos.Columns.Clear;
  dbgDetallePedidos.Columns.Clear;
  dbgTotalesProductos.Columns.Clear;

  // TAB TOTALES GLOBALES (Fijo para consulta rápida)
  LFixedTotales := 65 + 125 + 75 + 85 + 85 + 95 + 105 + 90 + 85; // 810
  LFlexTot1 := CalcGridFlexWidth(dbgTotalesProductos, LFixedTotales, 320, 0.65);
  LFlexTot2 := CalcGridFlexWidth(dbgTotalesProductos, LFixedTotales, 200, 0.35);

  with dbgTotalesProductos.Columns.Add do
  begin
    FieldName := 'articulo_id';
    Title.Caption := 'Ref.';
    Width := 65;
    Alignment := taCenter;
  end;
  with dbgTotalesProductos.Columns.Add do
  begin
    FieldName := 'ean';
    Title.Caption := 'EAN / Código';
    Width := 125;
    Alignment := taCenter;
  end;
  with dbgTotalesProductos.Columns.Add do
  begin
    FieldName := 'producto_nombre';
    Title.Caption := 'Artículo / Producto';
    Width := LFlexTot1;
  end;
  with dbgTotalesProductos.Columns.Add do
  begin
    FieldName := 'total_bultos';
    Title.Caption := 'Bultos';
    Width := 75;
    Alignment := taRightJustify;
  end;
  with dbgTotalesProductos.Columns.Add do
  begin
    FieldName := 'total_solicitado';
    Title.Caption := 'Cant. Sol';
    Width := 85;
    Alignment := taRightJustify;
  end;
  with dbgTotalesProductos.Columns.Add do
  begin
    FieldName := 'total_preparado';
    Title.Caption := 'Preparado';
    Width := 85;
    Alignment := taRightJustify;
  end;
  with dbgTotalesProductos.Columns.Add do
  begin
    FieldName := 'total_pendiente';
    Title.Caption := 'PENDIENTE';
    Width := 95;
    Alignment := taRightJustify;
  end;
  with dbgTotalesProductos.Columns.Add do
  begin
    FieldName := 'stock_actual';
    Title.Caption := 'Stock Almacén';
    Width := 105;
    Alignment := taRightJustify;
  end;
  with dbgTotalesProductos.Columns.Add do
  begin
    FieldName := 'balance_stock';
    Title.Caption := 'Balance (Déficit < 0)';
    Width := 130;
    Alignment := taRightJustify;
  end;
  with dbgTotalesProductos.Columns.Add do
  begin
    FieldName := 'receta_nombre';
    Title.Caption := 'Receta Maestra';
    Width := LFlexTot2;
  end;
  with dbgTotalesProductos.Columns.Add do
  begin
    FieldName := 'masas_necesarias';
    Title.Caption := 'Nº Masas';
    Width := 130;
    Alignment := taRightJustify;
  end;

  // Configuración de columnas para la pestaña de ingredientes / pesadas de obrador
  dbgIngredientesMasas.Columns.Clear;
  LFixedIngr := 200 + 65 + 140 + 120 + 65; // 590
  LFlexIngr1 := CalcGridFlexWidth(dbgIngredientesMasas, LFixedIngr, 280, 0.40);
  LFlexIngr2 := CalcGridFlexWidth(dbgIngredientesMasas, LFixedIngr, 380, 0.60);

  with dbgIngredientesMasas.Columns.Add do
  begin
    FieldName := 'proceso_nombre';
    Title.Caption := 'Fase / Proceso Elaboración';
    Width := 200;
  end;
  with dbgIngredientesMasas.Columns.Add do
  begin
    FieldName := 'materia_prima_id';
    Title.Caption := 'Ref.';
    Width := 65;
    Alignment := taCenter;
  end;
  with dbgIngredientesMasas.Columns.Add do
  begin
    FieldName := 'ingrediente_nombre';
    Title.Caption := 'Materia Prima / Ingrediente';
    Width := LFlexIngr1;
  end;
  with dbgIngredientesMasas.Columns.Add do
  begin
    FieldName := 'total_necesario_kg';
    Title.Caption := 'Total Necesario (Kg)';
    Width := 140;
    Alignment := taRightJustify;
  end;
  with dbgIngredientesMasas.Columns.Add do
  begin
    FieldName := 'total_necesario_g';
    Title.Caption := 'Total (Gramos)';
    Width := 120;
    Alignment := taRightJustify;
  end;
  with dbgIngredientesMasas.Columns.Add do
  begin
    FieldName := 'unidad';
    Title.Caption := 'Unidad';
    Width := 65;
    Alignment := taCenter;
  end;
  with dbgIngredientesMasas.Columns.Add do
  begin
    FieldName := 'recetas_usadas';
    Title.Caption := 'Recetas Destino Donde se Utiliza';
    Width := LFlexIngr2;
  end;
  tsIngredientesMasas.Caption := 'Desglose de Ingredientes / Obrador';

  case cbbModoVista.ItemIndex of
    0: // Por Fecha de Entrega y Producto
    begin
      lblMasterTitle.Caption := 'PRODUCTOS A PREPARAR AGRUPADOS POR FECHA / ORDEN DE ENTREGA:';
      lblDetailTitle.Caption := 'DETALLE DEL PRODUCTO SELECCIONADO (Doble clic para abrir pedido):';
      tsDetallePedidos.Caption := 'Desglose de Pedidos de la Fecha';
      tsTotalesProductos.Caption := 'Totales Globales de Cada Producto y Stock';

      LFixedMaster := 90 + 60 + 125 + 65 + 65 + 85 + 85 + 105 + 95 + 115 + 95 + 130 + 70; // 1185
      LFlexMaster1 := CalcGridFlexWidth(dbgProductos, LFixedMaster, 320, 0.65);
      LFlexMaster2 := CalcGridFlexWidth(dbgProductos, LFixedMaster, 180, 0.35);

      with dbgProductos.Columns.Add do
      begin
        FieldName := 'fecha_entrega_str';
        Title.Caption := 'F. Entrega';
        Width := 90;
        Alignment := taCenter;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'articulo_id';
        Title.Caption := 'Ref.';
        Width := 60;
        Alignment := taCenter;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'ean';
        Title.Caption := 'EAN / Código';
        Width := 125;
        Alignment := taCenter;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'producto_nombre';
        Title.Caption := 'Artículo / Producto';
        Width := LFlexMaster1;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'total_pedidos';
        Title.Caption := 'Nº Ped.';
        Width := 65;
        Alignment := taRightJustify;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'total_bultos';
        Title.Caption := 'Bultos';
        Width := 65;
        Alignment := taRightJustify;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'total_solicitado';
        Title.Caption := 'Solicitado';
        Width := 85;
        Alignment := taRightJustify;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'total_preparado';
        Title.Caption := 'Preparado';
        Width := 85;
        Alignment := taRightJustify;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'total_pendiente';
        Title.Caption := 'Pendiente Fecha';
        Width := 105;
        Alignment := taRightJustify;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'stock_actual';
        Title.Caption := 'Stock Almacén';
        Width := 95;
        Alignment := taRightJustify;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'total_global_articulo';
        Title.Caption := 'TOTAL PROD. (Global)';
        Width := 125;
        Alignment := taRightJustify;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'balance_stock';
        Title.Caption := 'Balance Global';
        Width := 95;
        Alignment := taRightJustify;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'receta_nombre';
        Title.Caption := 'Receta';
        Width := LFlexMaster2;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'formato_rendimiento';
        Title.Caption := 'Formato (Rdto)';
        Width := 130;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'masas_necesarias';
        Title.Caption := 'Masas Global';
        Width := 125;
        Alignment := taRightJustify;
      end;

      // Detalle (pedidos de esa fecha y producto)
      LFixedDetail := 115 + 90 + 140 + 95 + 70 + 90 + 95 + 120; // 815
      LFlexDetail1 := CalcGridFlexWidth(dbgDetallePedidos, LFixedDetail, 280, 0.55);
      LFlexDetail2 := CalcGridFlexWidth(dbgDetallePedidos, LFixedDetail, 240, 0.45);

      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'numero_pedido';
        Title.Caption := 'Nº Pedido';
        Width := 115;
        Alignment := taCenter;
      end;
      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'fecha_entrega';
        Title.Caption := 'F. Entrega';
        Width := 90;
        Alignment := taCenter;
      end;
      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'cliente_nombre';
        Title.Caption := 'Cliente';
        Width := LFlexDetail1;
      end;
      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'destino_nombre';
        Title.Caption := 'Destino / Entrega';
        Width := LFlexDetail2;
      end;
      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'poblacion';
        Title.Caption := 'Población';
        Width := 140;
      end;
      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'cantidad';
        Title.Caption := 'Cant. Pedida';
        Width := 95;
        Alignment := taRightJustify;
      end;
      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'bultos';
        Title.Caption := 'Bultos';
        Width := 70;
        Alignment := taRightJustify;
      end;
      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'cantidad_preparada';
        Title.Caption := 'Preparado';
        Width := 90;
        Alignment := taRightJustify;
      end;
      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'cantidad_pendiente';
        Title.Caption := 'Pendiente';
        Width := 95;
        Alignment := taRightJustify;
      end;
      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'estado';
        Title.Caption := 'Estado';
        Width := 120;
        Alignment := taCenter;
      end;
    end;

    1: // Por Pedido / Orden de Entrega
    begin
      lblMasterTitle.Caption := 'PEDIDOS / ' + #211 + 'RDENES DE ENTREGA (Secuencia por fecha de entrega - Doble clic para abrir):';
      lblDetailTitle.Caption := 'PRODUCTOS DE LA ORDEN DE ENTREGA SELECCIONADA Y STOCK:';
      tsDetallePedidos.Caption := 'Productos del Pedido';
      tsTotalesProductos.Caption := 'Totales Globales de Cada Producto y Stock';

      LFixedMaster := 95 + 115 + 140 + 75 + 75 + 90 + 90 + 95 + 120; // 895
      LFlexMaster1 := CalcGridFlexWidth(dbgProductos, LFixedMaster, 300, 0.55);
      LFlexMaster2 := CalcGridFlexWidth(dbgProductos, LFixedMaster, 250, 0.45);

      with dbgProductos.Columns.Add do
      begin
        FieldName := 'fecha_entrega_str';
        Title.Caption := 'F. Entrega';
        Width := 95;
        Alignment := taCenter;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'numero_pedido';
        Title.Caption := 'Nº Pedido';
        Width := 115;
        Alignment := taCenter;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'cliente_nombre';
        Title.Caption := 'Cliente';
        Width := LFlexMaster1;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'destino_nombre';
        Title.Caption := 'Destino / Entrega';
        Width := LFlexMaster2;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'poblacion';
        Title.Caption := 'Población';
        Width := 140;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'total_lineas';
        Title.Caption := 'Artículos';
        Width := 75;
        Alignment := taRightJustify;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'total_bultos';
        Title.Caption := 'Bultos';
        Width := 75;
        Alignment := taRightJustify;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'total_solicitado';
        Title.Caption := 'Solicitado';
        Width := 90;
        Alignment := taRightJustify;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'total_preparado';
        Title.Caption := 'Preparado';
        Width := 90;
        Alignment := taRightJustify;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'total_pendiente';
        Title.Caption := 'Pendiente';
        Width := 95;
        Alignment := taRightJustify;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'estado';
        Title.Caption := 'Estado';
        Width := 120;
        Alignment := taCenter;
      end;

      // Detalle (productos del pedido con stock)
      LFixedDetail := 65 + 125 + 70 + 90 + 90 + 95 + 95 + 95 + 130 + 70; // 925
      LFlexDetail1 := CalcGridFlexWidth(dbgDetallePedidos, LFixedDetail, 320, 0.65);
      LFlexDetail2 := CalcGridFlexWidth(dbgDetallePedidos, LFixedDetail, 180, 0.35);

      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'articulo_id';
        Title.Caption := 'Ref.';
        Width := 65;
        Alignment := taCenter;
      end;
      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'ean';
        Title.Caption := 'EAN / Código';
        Width := 125;
        Alignment := taCenter;
      end;
      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'producto_nombre';
        Title.Caption := 'Artículo / Producto';
        Width := LFlexDetail1;
      end;
      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'bultos';
        Title.Caption := 'Bultos';
        Width := 70;
        Alignment := taRightJustify;
      end;
      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'cantidad';
        Title.Caption := 'Cant. Pedida';
        Width := 90;
        Alignment := taRightJustify;
      end;
      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'cantidad_preparada';
        Title.Caption := 'Preparado';
        Width := 90;
        Alignment := taRightJustify;
      end;
      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'cantidad_pendiente';
        Title.Caption := 'Pendiente';
        Width := 95;
        Alignment := taRightJustify;
      end;
      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'stock_actual';
        Title.Caption := 'Stock Almacén';
        Width := 95;
        Alignment := taRightJustify;
      end;
      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'balance_stock';
        Title.Caption := 'Balance Stock';
        Width := 95;
        Alignment := taRightJustify;
      end;
      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'receta_nombre';
        Title.Caption := 'Receta';
        Width := LFlexDetail2;
      end;
      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'formato_rendimiento';
        Title.Caption := 'Formato (Rdto)';
        Width := 130;
      end;
      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'masas_necesarias';
        Title.Caption := 'Masas';
        Width := 125;
        Alignment := taRightJustify;
      end;
    end;

    2: // Consolidado Global por Producto
    begin
      lblMasterTitle.Caption := 'PRODUCTOS A PREPARAR (Consolidado total vs Stock en Almacén):';
      lblDetailTitle.Caption := 'DESGLOSE DE PEDIDOS PARA EL PRODUCTO SELECCIONADO (Doble clic para abrir pedido):';
      tsDetallePedidos.Caption := 'Desglose de Pedidos';
      tsTotalesProductos.Caption := 'Resumen General y Stock';

      LFixedMaster := 65 + 125 + 80 + 70 + 100 + 95 + 100 + 100 + 100 + 135 + 115; // 1085
      LFlexMaster1 := CalcGridFlexWidth(dbgProductos, LFixedMaster, 340, 0.65);
      LFlexMaster2 := CalcGridFlexWidth(dbgProductos, LFixedMaster, 200, 0.35);

      with dbgProductos.Columns.Add do
      begin
        FieldName := 'articulo_id';
        Title.Caption := 'Ref.';
        Width := 65;
        Alignment := taCenter;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'ean';
        Title.Caption := 'EAN / Código';
        Width := 125;
        Alignment := taCenter;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'producto_nombre';
        Title.Caption := 'Artículo / Producto';
        Width := LFlexMaster1;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'total_pedidos';
        Title.Caption := 'Nº Pedidos';
        Width := 80;
        Alignment := taRightJustify;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'total_bultos';
        Title.Caption := 'Bultos';
        Width := 70;
        Alignment := taRightJustify;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'total_solicitado';
        Title.Caption := 'Cant. Solicitada';
        Width := 100;
        Alignment := taRightJustify;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'total_preparado';
        Title.Caption := 'Ya Preparado';
        Width := 95;
        Alignment := taRightJustify;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'total_pendiente';
        Title.Caption := 'Pendiente';
        Width := 100;
        Alignment := taRightJustify;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'stock_actual';
        Title.Caption := 'Stock Almacén';
        Width := 100;
        Alignment := taRightJustify;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'balance_stock';
        Title.Caption := 'Balance Stock';
        Width := 100;
        Alignment := taRightJustify;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'receta_nombre';
        Title.Caption := 'Receta Maestra';
        Width := LFlexMaster2;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'formato_rendimiento';
        Title.Caption := 'Formato (Rdto)';
        Width := 135;
      end;
      with dbgProductos.Columns.Add do
      begin
        FieldName := 'masas_necesarias';
        Title.Caption := 'Masas Necesarias';
        Width := 135;
        Alignment := taRightJustify;
      end;

      // Detalle (pedidos con ese producto)
      LFixedDetail := 115 + 90 + 90 + 140 + 95 + 70 + 90 + 95 + 120; // 905
      LFlexDetail1 := CalcGridFlexWidth(dbgDetallePedidos, LFixedDetail, 280, 0.55);
      LFlexDetail2 := CalcGridFlexWidth(dbgDetallePedidos, LFixedDetail, 240, 0.45);

      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'numero_pedido';
        Title.Caption := 'Nº Pedido';
        Width := 115;
        Alignment := taCenter;
      end;
      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'fecha_pedido';
        Title.Caption := 'F. Pedido';
        Width := 90;
        Alignment := taCenter;
      end;
      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'fecha_entrega';
        Title.Caption := 'F. Entrega';
        Width := 90;
        Alignment := taCenter;
      end;
      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'cliente_nombre';
        Title.Caption := 'Cliente';
        Width := LFlexDetail1;
      end;
      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'destino_nombre';
        Title.Caption := 'Destino / Entrega';
        Width := LFlexDetail2;
      end;
      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'poblacion';
        Title.Caption := 'Población';
        Width := 140;
      end;
      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'cantidad';
        Title.Caption := 'Cant. Pedida';
        Width := 95;
        Alignment := taRightJustify;
      end;
      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'bultos';
        Title.Caption := 'Bultos';
        Width := 70;
        Alignment := taRightJustify;
      end;
      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'cantidad_preparada';
        Title.Caption := 'Preparado';
        Width := 90;
        Alignment := taRightJustify;
      end;
      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'cantidad_pendiente';
        Title.Caption := 'Pendiente';
        Width := 95;
        Alignment := taRightJustify;
      end;
      with dbgDetallePedidos.Columns.Add do
      begin
        FieldName := 'estado';
        Title.Caption := 'Estado';
        Width := 120;
        Alignment := taCenter;
      end;
    end;
  end;
end;

procedure TfrmPedidosPendientesLogistica.RefrescarMaster;
var
  LSql, LSqlFiltrosTotArt: string;
  LEmpId, LFentVal: Integer;
  LSearch: string;
  LModo: Integer;
begin
  if FLoadingFilters then Exit;

  LEmpId := GetSelectedEmpresaId;
  LFentVal := GetSelectedFechaEntregaVal;
  LSearch := Trim(edtBuscar.Text);
  LModo := cbbModoVista.ItemIndex;

  LSqlFiltrosTotArt := '';
  if LEmpId > 0 then
    LSqlFiltrosTotArt := LSqlFiltrosTotArt + 'AND p2.empresa_id = ' + IntToStr(LEmpId) + ' ';

  if LFentVal = -1 then
    LSqlFiltrosTotArt := LSqlFiltrosTotArt + 'AND p2.fecha_entrega IS NULL '
  else if LFentVal > 0 then
    LSqlFiltrosTotArt := LSqlFiltrosTotArt + 'AND DATE(p2.fecha_entrega) = ''' + FormatDateTime('yyyy-mm-dd', TDateTime(LFentVal)) + ''' ';

  if chkFiltrarFecha.Checked then
    LSqlFiltrosTotArt := LSqlFiltrosTotArt + 'AND p2.fecha_entrega >= ''' + FormatDateTime('yyyy-mm-dd', Trunc(dtpDesde.Date)) + ''' AND p2.fecha_entrega < ''' + FormatDateTime('yyyy-mm-dd', Trunc(dtpHasta.Date) + 1) + ''' ';

  qProductos.DisableControls;
  try
    qProductos.Close;

    case LModo of
      0: // Por Fecha de Entrega y Producto
      begin
        LSql :=
          'SELECT ' +
          '  DATE(p.fecha_entrega) AS f_entrega_date, ' +
          '  COALESCE(DATE_FORMAT(p.fecha_entrega, ''%d/%m/%Y''), ''Sin fecha'') AS fecha_entrega_str, ' +
          '  COALESCE(a.id, pl.id_articulo) AS articulo_id, ' +
          '  COALESCE(NULLIF(TRIM(a.ean), ''''), NULLIF(TRIM(pl.ean_producto), ''''), '''') AS ean, ' +
          '  COALESCE(a.descripcion, pl.descripcion) AS producto_nombre, ' +
          '  COUNT(DISTINCT p.id) AS total_pedidos, ' +
          '  CAST(SUM(COALESCE(pl.bultos, 0)) AS SIGNED) AS total_bultos, ' +
          '  SUM(pl.cantidad) AS total_solicitado, ' +
          '  COALESCE(SUM(prep.cantidad_preparada), 0) AS total_preparado, ' +
          '  (SUM(pl.cantidad) - COALESCE(SUM(prep.cantidad_preparada), 0)) AS total_pendiente, ' +
          '  COALESCE(stk.stock_actual, 0) AS stock_actual, ' +
          '  (COALESCE(stk.stock_actual, 0) - COALESCE(tot_art.total_global_art, (SUM(pl.cantidad) - COALESCE(SUM(prep.cantidad_preparada), 0)))) AS balance_stock, ' +
          '  COALESCE(tot_art.total_global_art, (SUM(pl.cantidad) - COALESCE(SUM(prep.cantidad_preparada), 0))) AS total_global_articulo, ' +
          '  COALESCE(tot_art.pedidos_global_art, COUNT(DISTINCT p.id)) AS total_pedidos_global, ' +
          '  COALESCE(rec.receta_nombre, '''') AS receta_nombre, ' +
          '  COALESCE(rec.formato_rendimiento, '''') AS formato_rendimiento, ' +
          '  ' + GetSqlExprMasas('COALESCE(tot_art.total_global_art, (SUM(pl.cantidad) - COALESCE(SUM(prep.cantidad_preparada), 0))) - COALESCE(stk.stock_actual, 0)') + ' AS masas_necesarias ' +
          'FROM ge_pedidos p ' +
          'JOIN ge_pedidos_lineas pl ON pl.id_pedido = p.id ' +
          'LEFT JOIN ge_articulos a ON a.id = pl.id_articulo ' +
          'LEFT JOIN ge_clientes c ON p.cliente_id = c.id ' +
          'LEFT JOIN ( ' +
          '  SELECT al.id_linea_pedido, SUM(lb.cantidad) AS cantidad_preparada ' +
          '  FROM ge_albaranes_lineas_bultos lb ' +
          '  JOIN ge_albaranes_lineas al ON lb.linea_albaran_id = al.id ' +
          '  GROUP BY al.id_linea_pedido ' +
          ') prep ON prep.id_linea_pedido = pl.id ' +
          'LEFT JOIN ( ' +
          '  SELECT se.id_articulo, SUM(se.cantidad_unidades) AS stock_actual ' +
          '  FROM ge_stock_envasado se ' +
          '  JOIN ge_almacenes alm ON se.id_almacen = alm.id AND alm.activo = 1 AND alm.compartido = 1 ' +
          '  WHERE se.estado_fabricacion = ''ENVASADO'' ' +
          '  GROUP BY se.id_articulo ' +
          ') stk ON stk.id_articulo = COALESCE(NULLIF(a.id_maestro, 0), a.id, pl.id_articulo) ' +
          'LEFT JOIN ( ' +
          '  SELECT ' +
          '    COALESCE(a2.id, pl2.id_articulo) AS id_art_tot, ' +
          '    COALESCE(a2.descripcion, pl2.descripcion) AS desc_art_tot, ' +
          '    COUNT(DISTINCT p2.id) AS pedidos_global_art, ' +
          '    SUM(pl2.cantidad - COALESCE(prep2.cant_prep, 0)) AS total_global_art ' +
          '  FROM ge_pedidos p2 ' +
          '  JOIN ge_pedidos_lineas pl2 ON pl2.id_pedido = p2.id ' +
          '  LEFT JOIN ge_articulos a2 ON a2.id = pl2.id_articulo ' +
          '  LEFT JOIN ( ' +
          '    SELECT al2.id_linea_pedido, SUM(lb2.cantidad) AS cant_prep ' +
          '    FROM ge_albaranes_lineas_bultos lb2 ' +
          '    JOIN ge_albaranes_lineas al2 ON lb2.linea_albaran_id = al2.id ' +
          '    GROUP BY al2.id_linea_pedido ' +
          '  ) prep2 ON prep2.id_linea_pedido = pl2.id ' +
          '  WHERE 1=1 ' +
          '    AND p2.estado IN (''PENDIENTE'', ''EN PREPARACION'', ''PROCESADO'') ' +
          LSqlFiltrosTotArt +
          '  GROUP BY COALESCE(a2.id, pl2.id_articulo), COALESCE(a2.descripcion, pl2.descripcion) ' +
          ') tot_art ON ( ' +
          '  (COALESCE(a.id, pl.id_articulo) > 0 AND tot_art.id_art_tot = COALESCE(a.id, pl.id_articulo)) ' +
          '  OR ((COALESCE(a.id, pl.id_articulo) IS NULL OR COALESCE(a.id, pl.id_articulo) = 0) AND tot_art.desc_art_tot = COALESCE(a.descripcion, pl.descripcion)) ' +
          ') ' +
          'LEFT JOIN ' + GetSqlSubqueryRecetaCanonica + ' rec ON rec.articulo_id = COALESCE(a.id, pl.id_articulo) ' +
          'WHERE 1=1 ';
      end;

      1: // Por Pedido / Orden de Entrega
      begin
        LSql :=
          'SELECT ' +
          '  p.id AS pedido_id, ' +
          '  p.numero_pedido, ' +
          '  DATE(p.fecha_entrega) AS f_entrega_date, ' +
          '  COALESCE(DATE_FORMAT(p.fecha_entrega, ''%d/%m/%Y''), ''Sin fecha'') AS fecha_entrega_str, ' +
          '  p.fecha_pedido, ' +
          '  c.nombre_fiscal AS cliente_nombre, ' +
          '  COALESCE(d.descripcion, c.nombre_fiscal) AS destino_nombre, ' +
          '  COALESCE(d.poblacion, c.poblacion) AS poblacion, ' +
          '  COUNT(DISTINCT pl.id) AS total_lineas, ' +
          '  CAST(SUM(COALESCE(pl.bultos, 0)) AS SIGNED) AS total_bultos, ' +
          '  SUM(pl.cantidad) AS total_solicitado, ' +
          '  COALESCE(SUM(prep.cantidad_preparada), 0) AS total_preparado, ' +
          '  (SUM(pl.cantidad) - COALESCE(SUM(prep.cantidad_preparada), 0)) AS total_pendiente, ' +
          '  p.estado ' +
          'FROM ge_pedidos p ' +
          'JOIN ge_pedidos_lineas pl ON pl.id_pedido = p.id ' +
          'LEFT JOIN ge_articulos a ON a.id = pl.id_articulo ' +
          'JOIN ge_clientes c ON p.cliente_id = c.id ' +
          'LEFT JOIN ge_clientes_destinos d ON p.clientedestino_id = d.id ' +
          'LEFT JOIN ( ' +
          '  SELECT al.id_linea_pedido, SUM(lb.cantidad) AS cantidad_preparada ' +
          '  FROM ge_albaranes_lineas_bultos lb ' +
          '  JOIN ge_albaranes_lineas al ON lb.linea_albaran_id = al.id ' +
          '  GROUP BY al.id_linea_pedido ' +
          ') prep ON prep.id_linea_pedido = pl.id ' +
          'WHERE 1=1 ';
      end;

      else // Modo 2: Consolidado Global por Producto
      begin
        LSql :=
          'SELECT ' +
          '  COALESCE(a.id, pl.id_articulo) AS articulo_id, ' +
          '  COALESCE(NULLIF(TRIM(a.ean), ''''), NULLIF(TRIM(pl.ean_producto), ''''), '''') AS ean, ' +
          '  COALESCE(a.descripcion, pl.descripcion) AS producto_nombre, ' +
          '  COUNT(DISTINCT p.id) AS total_pedidos, ' +
          '  CAST(SUM(COALESCE(pl.bultos, 0)) AS SIGNED) AS total_bultos, ' +
          '  SUM(pl.cantidad) AS total_solicitado, ' +
          '  COALESCE(SUM(prep.cantidad_preparada), 0) AS total_preparado, ' +
          '  (SUM(pl.cantidad) - COALESCE(SUM(prep.cantidad_preparada), 0)) AS total_pendiente, ' +
          '  COALESCE(stk.stock_actual, 0) AS stock_actual, ' +
          '  (COALESCE(stk.stock_actual, 0) - (SUM(pl.cantidad) - COALESCE(SUM(prep.cantidad_preparada), 0))) AS balance_stock, ' +
          '  COALESCE(rec.receta_nombre, '''') AS receta_nombre, ' +
          '  COALESCE(rec.formato_rendimiento, '''') AS formato_rendimiento, ' +
          '  ' + GetSqlExprMasas('(SUM(pl.cantidad) - COALESCE(SUM(prep.cantidad_preparada), 0)) - COALESCE(stk.stock_actual, 0)') + ' AS masas_necesarias ' +
          'FROM ge_pedidos p ' +
          'JOIN ge_pedidos_lineas pl ON pl.id_pedido = p.id ' +
          'LEFT JOIN ge_articulos a ON a.id = pl.id_articulo ' +
          'LEFT JOIN ge_clientes c ON p.cliente_id = c.id ' +
          'LEFT JOIN ( ' +
          '  SELECT al.id_linea_pedido, SUM(lb.cantidad) AS cantidad_preparada ' +
          '  FROM ge_albaranes_lineas_bultos lb ' +
          '  JOIN ge_albaranes_lineas al ON lb.linea_albaran_id = al.id ' +
          '  GROUP BY al.id_linea_pedido ' +
          ') prep ON prep.id_linea_pedido = pl.id ' +
          'LEFT JOIN ( ' +
          '  SELECT se.id_articulo, SUM(se.cantidad_unidades) AS stock_actual ' +
          '  FROM ge_stock_envasado se ' +
          '  JOIN ge_almacenes alm ON se.id_almacen = alm.id AND alm.activo = 1 AND alm.compartido = 1 ' +
          '  GROUP BY se.id_articulo ' +
          ') stk ON stk.id_articulo = COALESCE(NULLIF(a.id_maestro, 0), a.id, pl.id_articulo) ' +
          'LEFT JOIN ' + GetSqlSubqueryRecetaCanonica + ' rec ON rec.articulo_id = COALESCE(a.id, pl.id_articulo) ' +
          'WHERE 1=1 ';
      end;
    end;

    // Filtros comunes
    if LEmpId > 0 then
      LSql := LSql + 'AND p.empresa_id = :emp ';

    case cbbEstado.ItemIndex of
      0: LSql := LSql + 'AND p.estado IN (''PENDIENTE'', ''EN PREPARACION'', ''PROCESADO'') ';
      1: LSql := LSql + 'AND p.estado = ''PENDIENTE'' ';
      2: LSql := LSql + 'AND p.estado = ''EN PREPARACION'' ';
      3: LSql := LSql + 'AND p.estado = ''PROCESADO'' ';
    end;

    // Filtro por Fecha de Entrega del combo
    if LFentVal = -1 then
      LSql := LSql + 'AND p.fecha_entrega IS NULL '
    else if LFentVal > 0 then
      LSql := LSql + 'AND DATE(p.fecha_entrega) = :f_entrega_sel ';

    // Filtro por rango de fechas (dtp)
    if chkFiltrarFecha.Checked then
      LSql := LSql + 'AND p.fecha_entrega >= :f_desde AND p.fecha_entrega < :f_hasta ';

    // Búsqueda
    if LSearch <> '' then
    begin
      LSql := LSql + 'AND (a.descripcion LIKE :search ' +
                     '     OR pl.descripcion LIKE :search ' +
                     '     OR a.ean LIKE :search ' +
                     '     OR pl.ean_producto LIKE :search ' +
                     '     OR c.nombre_fiscal LIKE :search ' +
                     '     OR p.numero_pedido LIKE :search) ';
    end;

    // Group by y Order by según modo
    case LModo of
      0: // Por Fecha de Entrega y Producto
      begin
        LSql := LSql +
          'GROUP BY DATE(p.fecha_entrega), COALESCE(a.id, pl.id_articulo), COALESCE(a.descripcion, pl.descripcion), rec.receta_nombre, rec.formato_rendimiento, rec.unidades_base ' +
          'HAVING total_pendiente > 0 ' +
          'ORDER BY f_entrega_date ASC, total_pendiente DESC, producto_nombre ASC';
      end;

      1: // Por Pedido / Orden de Entrega
      begin
        LSql := LSql +
          'GROUP BY p.id ' +
          'HAVING total_pendiente > 0 ' +
          'ORDER BY p.fecha_entrega ASC, p.id ASC';
      end;

      else // Modo 2: Consolidado Global
      begin
        LSql := LSql +
          'GROUP BY COALESCE(a.id, pl.id_articulo), COALESCE(a.descripcion, pl.descripcion), rec.receta_nombre, rec.formato_rendimiento, rec.unidades_base ' +
          'HAVING total_pendiente > 0 ' +
          'ORDER BY total_pendiente DESC, producto_nombre ASC';
      end;
    end;

    qProductos.SQL.Text := LSql;

    if LEmpId > 0 then
      qProductos.ParamByName('emp').AsInteger := LEmpId;

    if LFentVal > 0 then
      qProductos.ParamByName('f_entrega_sel').AsString := FormatDateTime('yyyy-mm-dd', TDateTime(LFentVal));

    if chkFiltrarFecha.Checked then
    begin
      qProductos.ParamByName('f_desde').AsDateTime := Trunc(dtpDesde.Date);
      qProductos.ParamByName('f_hasta').AsDateTime := Trunc(dtpHasta.Date) + 1;
    end;

    if LSearch <> '' then
      qProductos.ParamByName('search').AsString := '%' + LSearch + '%';

    qProductos.Open;
  finally
    qProductos.EnableControls;
  end;

  RefrescarTotalesProductos;
  ActualizarKPIs;
  RefrescarDetalle;
  CargarIngredientesMasas;
end;

procedure TfrmPedidosPendientesLogistica.RefrescarTotalesProductos;
var
  LSql: string;
  LEmpId, LFentVal: Integer;
  LSearch: string;
begin
  LEmpId := GetSelectedEmpresaId;
  LFentVal := GetSelectedFechaEntregaVal;
  LSearch := Trim(edtBuscar.Text);

  qTotalesProductos.DisableControls;
  try
    qTotalesProductos.Close;
    LSql :=
      'SELECT ' +
      '  COALESCE(a.id, pl.id_articulo) AS articulo_id, ' +
      '  COALESCE(NULLIF(TRIM(a.ean), ''''), NULLIF(TRIM(pl.ean_producto), ''''), '''') AS ean, ' +
      '  COALESCE(a.descripcion, pl.descripcion) AS producto_nombre, ' +
      '  COUNT(DISTINCT p.id) AS total_pedidos, ' +
      '  CAST(SUM(COALESCE(pl.bultos, 0)) AS SIGNED) AS total_bultos, ' +
      '  SUM(pl.cantidad) AS total_solicitado, ' +
      '  COALESCE(SUM(prep.cantidad_preparada), 0) AS total_preparado, ' +
      '  (SUM(pl.cantidad) - COALESCE(SUM(prep.cantidad_preparada), 0)) AS total_pendiente, ' +
      '  COALESCE(stk.stock_actual, 0) AS stock_actual, ' +
      '  (COALESCE(stk.stock_actual, 0) - (SUM(pl.cantidad) - COALESCE(SUM(prep.cantidad_preparada), 0))) AS balance_stock, ' +
      '  COALESCE(rec.receta_nombre, '''') AS receta_nombre, ' +
      '  COALESCE(rec.formato_rendimiento, '''') AS formato_rendimiento, ' +
      '  ' + GetSqlExprMasas('(SUM(pl.cantidad) - COALESCE(SUM(prep.cantidad_preparada), 0)) - COALESCE(stk.stock_actual, 0)') + ' AS masas_necesarias ' +
      'FROM ge_pedidos p ' +
      'JOIN ge_pedidos_lineas pl ON pl.id_pedido = p.id ' +
      'LEFT JOIN ge_articulos a ON a.id = pl.id_articulo ' +
      'LEFT JOIN ge_clientes c ON p.cliente_id = c.id ' +
      'LEFT JOIN ( ' +
      '  SELECT al.id_linea_pedido, SUM(lb.cantidad) AS cantidad_preparada ' +
      '  FROM ge_albaranes_lineas_bultos lb ' +
      '  JOIN ge_albaranes_lineas al ON lb.linea_albaran_id = al.id ' +
      '  GROUP BY al.id_linea_pedido ' +
      ') prep ON prep.id_linea_pedido = pl.id ' +
      'LEFT JOIN ( ' +
      '  SELECT se.id_articulo, SUM(se.cantidad_unidades) AS stock_actual ' +
      '  FROM ge_stock_envasado se ' +
      '  JOIN ge_almacenes alm ON se.id_almacen = alm.id AND alm.activo = 1 AND alm.compartido = 1 ' +
      '  WHERE se.estado_fabricacion = ''ENVASADO'' ' +
      '  GROUP BY se.id_articulo ' +
      ') stk ON stk.id_articulo = COALESCE(NULLIF(a.id_maestro, 0), a.id, pl.id_articulo) ' +
      'LEFT JOIN ' + GetSqlSubqueryRecetaCanonica + ' rec ON rec.articulo_id = COALESCE(a.id, pl.id_articulo) ' +
      'WHERE 1=1 ';

    if LEmpId > 0 then
      LSql := LSql + 'AND p.empresa_id = :emp ';

    case cbbEstado.ItemIndex of
      0: LSql := LSql + 'AND p.estado IN (''PENDIENTE'', ''EN PREPARACION'', ''PROCESADO'') ';
      1: LSql := LSql + 'AND p.estado = ''PENDIENTE'' ';
      2: LSql := LSql + 'AND p.estado = ''EN PREPARACION'' ';
      3: LSql := LSql + 'AND p.estado = ''PROCESADO'' ';
    end;

    if LFentVal = -1 then
      LSql := LSql + 'AND p.fecha_entrega IS NULL '
    else if LFentVal > 0 then
      LSql := LSql + 'AND DATE(p.fecha_entrega) = :f_entrega_sel ';

    if chkFiltrarFecha.Checked then
      LSql := LSql + 'AND p.fecha_entrega >= :f_desde AND p.fecha_entrega < :f_hasta ';

    if LSearch <> '' then
    begin
      LSql := LSql + 'AND (a.descripcion LIKE :search ' +
                     '     OR pl.descripcion LIKE :search ' +
                     '     OR a.ean LIKE :search ' +
                     '     OR pl.ean_producto LIKE :search ' +
                     '     OR c.nombre_fiscal LIKE :search ' +
                     '     OR p.numero_pedido LIKE :search) ';
    end;

    LSql := LSql +
      'GROUP BY COALESCE(a.id, pl.id_articulo), COALESCE(a.descripcion, pl.descripcion), rec.receta_nombre, rec.formato_rendimiento, rec.unidades_base ' +
      'HAVING total_pendiente > 0 ' +
      'ORDER BY total_pendiente DESC, producto_nombre ASC';

    qTotalesProductos.SQL.Text := LSql;

    if LEmpId > 0 then
      qTotalesProductos.ParamByName('emp').AsInteger := LEmpId;

    if LFentVal > 0 then
      qTotalesProductos.ParamByName('f_entrega_sel').AsString := FormatDateTime('yyyy-mm-dd', TDateTime(LFentVal));

    if chkFiltrarFecha.Checked then
    begin
      qTotalesProductos.ParamByName('f_desde').AsDateTime := Trunc(dtpDesde.Date);
      qTotalesProductos.ParamByName('f_hasta').AsDateTime := Trunc(dtpHasta.Date) + 1;
    end;

    if LSearch <> '' then
      qTotalesProductos.ParamByName('search').AsString := '%' + LSearch + '%';

    qTotalesProductos.Open;
    if qTotalesProductos.IsEmpty then
      tsTotalesProductos.Caption := 'Totales Globales de Cada Producto (0)'
    else
      tsTotalesProductos.Caption := Format('Totales Globales de Cada Producto (%d)', [qTotalesProductos.RecordCount]);
  finally
    qTotalesProductos.EnableControls;
  end;
end;

procedure TfrmPedidosPendientesLogistica.RefrescarDetalle;
var
  LSql: string;
  LEmpId, LArtId, LFentVal: Integer;
  LDesc, LFechaStr, LPedId: string;
  LModo: Integer;
begin
  if qProductos.IsEmpty then
  begin
    qDetallePedidos.Close;
    lblDetailTitle.Caption := 'DETALLE: No hay registros seleccionados.';
    Exit;
  end;

  LEmpId := GetSelectedEmpresaId;
  LFentVal := GetSelectedFechaEntregaVal;
  LModo := cbbModoVista.ItemIndex;

  qDetallePedidos.DisableControls;
  try
    qDetallePedidos.Close;

    case LModo of
      0: // Por Fecha de Entrega y Producto -> Muestra pedidos de esa fecha y producto
      begin
        LArtId := qProductos.FieldByName('articulo_id').AsInteger;
        LDesc := qProductos.FieldByName('producto_nombre').AsString;
        LFechaStr := qProductos.FieldByName('fecha_entrega_str').AsString;

        lblDetailTitle.Caption := Format(
          'PEDIDOS CON "%s" [F. Entrega: %s] | Pendiente en Fecha: %s uds | Stock Almac'#233'n: %s | TOTAL PRODUCTO: %s uds en %s pedidos',
          [LDesc,
           LFechaStr,
           FormatFloat('0.##', qProductos.FieldByName('total_pendiente').AsFloat),
           FormatFloat('0.##', qProductos.FieldByName('stock_actual').AsFloat),
           FormatFloat('0.##', qProductos.FieldByName('total_global_articulo').AsFloat),
           qProductos.FieldByName('total_pedidos_global').AsString]
        );

        LSql :=
          'SELECT ' +
          '  p.id AS pedido_id, ' +
          '  p.numero_pedido, ' +
          '  p.fecha_pedido, ' +
          '  p.fecha_entrega, ' +
          '  p.estado, ' +
          '  c.nombre_fiscal AS cliente_nombre, ' +
          '  COALESCE(d.descripcion, c.nombre_fiscal) AS destino_nombre, ' +
          '  COALESCE(d.poblacion, c.poblacion) AS poblacion, ' +
          '  pl.cantidad, ' +
          '  COALESCE(pl.bultos, 0) AS bultos, ' +
          '  COALESCE(prep.cantidad_preparada, 0) AS cantidad_preparada, ' +
          '  (pl.cantidad - COALESCE(prep.cantidad_preparada, 0)) AS cantidad_pendiente ' +
          'FROM ge_pedidos p ' +
          'JOIN ge_pedidos_lineas pl ON pl.id_pedido = p.id ' +
          'JOIN ge_clientes c ON p.cliente_id = c.id ' +
          'LEFT JOIN ge_clientes_destinos d ON p.clientedestino_id = d.id ' +
          'LEFT JOIN ( ' +
          '  SELECT al.id_linea_pedido, SUM(lb.cantidad) AS cantidad_preparada ' +
          '  FROM ge_albaranes_lineas_bultos lb ' +
          '  JOIN ge_albaranes_lineas al ON lb.linea_albaran_id = al.id ' +
          '  GROUP BY al.id_linea_pedido ' +
          ') prep ON prep.id_linea_pedido = pl.id ' +
          'WHERE 1=1 ';

        if LEmpId > 0 then
          LSql := LSql + 'AND p.empresa_id = :emp ';

        case cbbEstado.ItemIndex of
          0: LSql := LSql + 'AND p.estado IN (''PENDIENTE'', ''EN PREPARACION'', ''PROCESADO'') ';
          1: LSql := LSql + 'AND p.estado = ''PENDIENTE'' ';
          2: LSql := LSql + 'AND p.estado = ''EN PREPARACION'' ';
          3: LSql := LSql + 'AND p.estado = ''PROCESADO'' ';
        end;

        if qProductos.FieldByName('f_entrega_date').IsNull then
          LSql := LSql + 'AND p.fecha_entrega IS NULL '
        else
          LSql := LSql + 'AND DATE(p.fecha_entrega) = :f_entrega_row ';

        if LArtId > 0 then
          LSql := LSql + 'AND pl.id_articulo = :art_id '
        else
          LSql := LSql + 'AND pl.descripcion = :desc ';

        LSql := LSql + 'ORDER BY p.fecha_entrega ASC, p.id ASC';

        qDetallePedidos.SQL.Text := LSql;

        if LEmpId > 0 then
          qDetallePedidos.ParamByName('emp').AsInteger := LEmpId;

        if not qProductos.FieldByName('f_entrega_date').IsNull then
          qDetallePedidos.ParamByName('f_entrega_row').AsString := FormatDateTime('yyyy-mm-dd', qProductos.FieldByName('f_entrega_date').AsDateTime);

        if LArtId > 0 then
          qDetallePedidos.ParamByName('art_id').AsInteger := LArtId
        else
          qDetallePedidos.ParamByName('desc').AsString := LDesc;
      end;

      1: // Por Pedido / Orden de Entrega -> Muestra productos del pedido seleccionado con stock
      begin
        LPedId := qProductos.FieldByName('pedido_id').AsString;
        lblDetailTitle.Caption := Format(
          'PRODUCTOS PENDIENTES DEL PEDIDO %s (Cliente: %s | Entrega: %s):',
          [qProductos.FieldByName('numero_pedido').AsString,
           qProductos.FieldByName('cliente_nombre').AsString,
           qProductos.FieldByName('fecha_entrega_str').AsString]
        );

        LSql :=
          'SELECT ' +
          '  COALESCE(a.id, pl.id_articulo) AS articulo_id, ' +
          '  COALESCE(NULLIF(TRIM(a.ean), ''''), NULLIF(TRIM(pl.ean_producto), ''''), '''') AS ean, ' +
          '  COALESCE(a.descripcion, pl.descripcion) AS producto_nombre, ' +
          '  COALESCE(pl.bultos, 0) AS bultos, ' +
          '  pl.cantidad AS cantidad, ' +
          '  COALESCE(prep.cantidad_preparada, 0) AS cantidad_preparada, ' +
          '  (pl.cantidad - COALESCE(prep.cantidad_preparada, 0)) AS cantidad_pendiente, ' +
          '  COALESCE(stk.stock_actual, 0) AS stock_actual, ' +
          '  (COALESCE(stk.stock_actual, 0) - (pl.cantidad - COALESCE(prep.cantidad_preparada, 0))) AS balance_stock, ' +
          '  COALESCE(rec.receta_nombre, '''') AS receta_nombre, ' +
          '  COALESCE(rec.formato_rendimiento, '''') AS formato_rendimiento, ' +
          '  ' + GetSqlExprMasas('(pl.cantidad - COALESCE(prep.cantidad_preparada, 0)) - COALESCE(stk.stock_actual, 0)') + ' AS masas_necesarias ' +
          'FROM ge_pedidos_lineas pl ' +
          'JOIN ge_pedidos p ON pl.id_pedido = p.id ' +
          'LEFT JOIN ge_articulos a ON a.id = pl.id_articulo ' +
          'LEFT JOIN ( ' +
          '  SELECT al.id_linea_pedido, SUM(lb.cantidad) AS cantidad_preparada ' +
          '  FROM ge_albaranes_lineas_bultos lb ' +
          '  JOIN ge_albaranes_lineas al ON lb.linea_albaran_id = al.id ' +
          '  GROUP BY al.id_linea_pedido ' +
          ') prep ON prep.id_linea_pedido = pl.id ' +
          'LEFT JOIN ( ' +
          '  SELECT se.id_articulo, SUM(se.cantidad_unidades) AS stock_actual ' +
          '  FROM ge_stock_envasado se ' +
          '  JOIN ge_almacenes alm ON se.id_almacen = alm.id AND alm.activo = 1 AND alm.compartido = 1 ' +
          '  GROUP BY se.id_articulo ' +
          ') stk ON stk.id_articulo = COALESCE(NULLIF(a.id_maestro, 0), a.id, pl.id_articulo) ' +
          'LEFT JOIN ' + GetSqlSubqueryRecetaCanonica + ' rec ON rec.articulo_id = COALESCE(a.id, pl.id_articulo) ' +
          'WHERE pl.id_pedido = :pedido_id ' +
          'ORDER BY pl.id ASC';

        qDetallePedidos.SQL.Text := LSql;
        qDetallePedidos.ParamByName('pedido_id').AsString := LPedId;
      end;

      else // Modo 2: Consolidado Global por Producto -> Muestra pedidos con ese producto
      begin
        LArtId := qProductos.FieldByName('articulo_id').AsInteger;
        LDesc := qProductos.FieldByName('producto_nombre').AsString;

        lblDetailTitle.Caption := Format(
          'DESGLOSE DE PEDIDOS PARA "%s" (Pendiente: %s uds | Stock Almac'#233'n: %s | Balance: %s):',
          [LDesc,
           FormatFloat('0.##', qProductos.FieldByName('total_pendiente').AsFloat),
           FormatFloat('0.##', qProductos.FieldByName('stock_actual').AsFloat),
           FormatFloat('0.##', qProductos.FieldByName('balance_stock').AsFloat)]
        );

        LSql :=
          'SELECT ' +
          '  p.id AS pedido_id, ' +
          '  p.numero_pedido, ' +
          '  p.fecha_pedido, ' +
          '  p.fecha_entrega, ' +
          '  p.estado, ' +
          '  c.nombre_fiscal AS cliente_nombre, ' +
          '  COALESCE(d.descripcion, c.nombre_fiscal) AS destino_nombre, ' +
          '  COALESCE(d.poblacion, c.poblacion) AS poblacion, ' +
          '  pl.cantidad, ' +
          '  COALESCE(pl.bultos, 0) AS bultos, ' +
          '  COALESCE(prep.cantidad_preparada, 0) AS cantidad_preparada, ' +
          '  (pl.cantidad - COALESCE(prep.cantidad_preparada, 0)) AS cantidad_pendiente ' +
          'FROM ge_pedidos p ' +
          'JOIN ge_pedidos_lineas pl ON pl.id_pedido = p.id ' +
          'JOIN ge_clientes c ON p.cliente_id = c.id ' +
          'LEFT JOIN ge_clientes_destinos d ON p.clientedestino_id = d.id ' +
          'LEFT JOIN ( ' +
          '  SELECT al.id_linea_pedido, SUM(lb.cantidad) AS cantidad_preparada ' +
          '  FROM ge_albaranes_lineas_bultos lb ' +
          '  JOIN ge_albaranes_lineas al ON lb.linea_albaran_id = al.id ' +
          '  GROUP BY al.id_linea_pedido ' +
          ') prep ON prep.id_linea_pedido = pl.id ' +
          'WHERE 1=1 ';

        if LEmpId > 0 then
          LSql := LSql + 'AND p.empresa_id = :emp ';

        case cbbEstado.ItemIndex of
          0: LSql := LSql + 'AND p.estado IN (''PENDIENTE'', ''EN PREPARACION'', ''PROCESADO'') ';
          1: LSql := LSql + 'AND p.estado = ''PENDIENTE'' ';
          2: LSql := LSql + 'AND p.estado = ''EN PREPARACION'' ';
          3: LSql := LSql + 'AND p.estado = ''PROCESADO'' ';
        end;

        if LFentVal = -1 then
          LSql := LSql + 'AND p.fecha_entrega IS NULL '
        else if LFentVal > 0 then
          LSql := LSql + 'AND DATE(p.fecha_entrega) = :f_entrega_sel ';

        if chkFiltrarFecha.Checked then
          LSql := LSql + 'AND p.fecha_entrega >= :f_desde AND p.fecha_entrega < :f_hasta ';

        if LArtId > 0 then
          LSql := LSql + 'AND pl.id_articulo = :art_id '
        else
          LSql := LSql + 'AND pl.descripcion = :desc ';

        LSql := LSql + 'ORDER BY p.fecha_entrega ASC, p.fecha_pedido ASC, p.id ASC';

        qDetallePedidos.SQL.Text := LSql;

        if LEmpId > 0 then
          qDetallePedidos.ParamByName('emp').AsInteger := LEmpId;

        if LFentVal > 0 then
          qDetallePedidos.ParamByName('f_entrega_sel').AsString := FormatDateTime('yyyy-mm-dd', TDateTime(LFentVal));

        if chkFiltrarFecha.Checked then
        begin
          qDetallePedidos.ParamByName('f_desde').AsDateTime := Trunc(dtpDesde.Date);
          qDetallePedidos.ParamByName('f_hasta').AsDateTime := Trunc(dtpHasta.Date) + 1;
        end;

        if LArtId > 0 then
          qDetallePedidos.ParamByName('art_id').AsInteger := LArtId
        else
          qDetallePedidos.ParamByName('desc').AsString := LDesc;
      end;
    end;

    qDetallePedidos.Open;
  finally
    qDetallePedidos.EnableControls;
  end;
end;

procedure TfrmPedidosPendientesLogistica.ActualizarKPIs;
var
  LBookmark: TBookmark;
  LTotRegistros, LTotBultos: Integer;
  LBal, LDeficit, LMasas: Double;
  LQryPed, LQryArts: TFDQuery;
  LSql: string;
  LEmpId, LFentVal: Integer;
  LSearch: string;
begin
  LTotRegistros := qProductos.RecordCount;
  LTotBultos := 0;

  // Bultos totales desde qProductos
  if not qProductos.IsEmpty then
  begin
    LBookmark := qProductos.GetBookmark;
    try
      qProductos.First;
      while not qProductos.Eof do
      begin
        LTotBultos := LTotBultos + qProductos.FieldByName('total_bultos').AsInteger;
        qProductos.Next;
      end;
    finally
      if qProductos.BookmarkValid(LBookmark) then
        qProductos.GotoBookmark(LBookmark);
      qProductos.FreeBookmark(LBookmark);
    end;
  end;

  lblKpiBultosVal.Caption := IntToStr(LTotBultos);

  // Totales calculados desde el apartado de totales globales de cada producto (qTotalesProductos)
  FTotPendientesPedidos := 0.0;
  FTotStockAlmacen := 0.0;
  FTotFabricar := 0.0;
  FTotMasas := 0.0;

  if not qTotalesProductos.IsEmpty then
  begin
    LBookmark := qTotalesProductos.GetBookmark;
    try
      qTotalesProductos.First;
      while not qTotalesProductos.Eof do
      begin
        FTotPendientesPedidos := FTotPendientesPedidos + qTotalesProductos.FieldByName('total_pendiente').AsFloat;
        FTotStockAlmacen := FTotStockAlmacen + qTotalesProductos.FieldByName('stock_actual').AsFloat;

        LBal := qTotalesProductos.FieldByName('balance_stock').AsFloat;
        if LBal < 0 then
        begin
          LDeficit := Abs(LBal);
          FTotFabricar := FTotFabricar + LDeficit;
        end;

        LMasas := qTotalesProductos.FieldByName('masas_necesarias').AsFloat;
        FTotMasas := FTotMasas + LMasas;

        qTotalesProductos.Next;
      end;
    finally
      if qTotalesProductos.BookmarkValid(LBookmark) then
        qTotalesProductos.GotoBookmark(LBookmark);
      qTotalesProductos.FreeBookmark(LBookmark);
    end;
  end;

  // KPI Unidades Pendientes de Fabricar (Déficit balance < 0)
  lblKpiUnidadesVal.Caption := FormatFloat('#,##0.##', FTotFabricar) + ' uds';
  lblKpiUnidadesLbl.Caption := 'Pend. Fabricar';
  lblKpiUnidadesVal.Hint := Format('Déficit real a fabricar: %s uds (según balance de stock) de %s uds solicitadas en pedidos',
    [FormatFloat('#,##0.##', FTotFabricar), FormatFloat('#,##0.##', FTotPendientesPedidos)]);
  lblKpiUnidadesVal.ShowHint := True;
  lblKpiUnidadesLbl.Hint := lblKpiUnidadesVal.Hint;
  lblKpiUnidadesLbl.ShowHint := True;

  // KPI Masas Estimadas
  if FTotMasas > 0 then
  begin
    if FAjustarCuartos then
      lblKpiMasasVal.Caption := FormatFloat('#,##0.##', FTotMasas) + ' masas (1/4)'
    else
      lblKpiMasasVal.Caption := FormatFloat('#,##0.##', FTotMasas) + ' masas';
  end
  else
    lblKpiMasasVal.Caption := '0 masas (Stock OK)';

  if FAjustarCuartos then
    lblKpiMasasVal.Hint := Format('Total masas ajustadas a múltiplos de 1/4 (0.25) al alza (%s uds a fabricar)',
      [FormatFloat('#,##0.##', FTotFabricar)])
  else
    lblKpiMasasVal.Hint := Format('Total masas estimadas calculadas a partir del déficit de balance de cada producto (%s uds a fabricar)',
      [FormatFloat('#,##0.##', FTotFabricar)]);
  lblKpiMasasVal.ShowHint := True;

  // Actualizar resumen en pie de pestaña Totales Globales
  if Assigned(lblTotalesSummaryText) then
  begin
    if qTotalesProductos.IsEmpty then
      lblTotalesSummaryText.Caption := 'RESUMEN: No hay productos pendientes con los filtros actuales.'
    else
    begin
      if FAjustarCuartos then
        LSql := 'MASAS AJUSTADAS (+1/4): '
      else
        LSql := 'MASAS ESTIMADAS: ';

      lblTotalesSummaryText.Caption := Format(
        'TOTALES GLOBALES:  %d Artículos  |  Total Pedidos: %s uds  |  Stock Almacén: %s uds  |  DÉFICIT A FABRICAR (Balance < 0): %s uds  |  %s%s masas',
        [qTotalesProductos.RecordCount,
         FormatFloat('#,##0.##', FTotPendientesPedidos),
         FormatFloat('#,##0.##', FTotStockAlmacen),
         FormatFloat('#,##0.##', FTotFabricar),
         LSql,
         FormatFloat('#,##0.##', FTotMasas)]
      );
    end;
  end;

  // Actualizar título de la pestaña de Totales Globales
  if qTotalesProductos.IsEmpty then
    tsTotalesProductos.Caption := 'Totales Globales de Cada Producto (0)'
  else if FAjustarCuartos then
    tsTotalesProductos.Caption := Format('Totales Globales (%d art. | %s uds a fabricar | %s masas [1/4])',
      [qTotalesProductos.RecordCount, FormatFloat('#,##0', FTotFabricar), FormatFloat('0.##', FTotMasas)])
  else
    tsTotalesProductos.Caption := Format('Totales Globales (%d art. | %s uds a fabricar | %s masas)',
      [qTotalesProductos.RecordCount, FormatFloat('#,##0', FTotFabricar), FormatFloat('0.##', FTotMasas)]);

  LEmpId := GetSelectedEmpresaId;
  LFentVal := GetSelectedFechaEntregaVal;
  LSearch := Trim(edtBuscar.Text);

  if cbbModoVista.ItemIndex = 1 then
  begin
    lblKpiPedidosVal.Caption := IntToStr(LTotRegistros);

    LQryArts := TFDQuery.Create(nil);
    try
      LQryArts.Connection := dmgMain.dbConn;
      LSql :=
        'SELECT COUNT(DISTINCT COALESCE(a.id, pl.id_articulo)) AS cant_articulos ' +
        'FROM ge_pedidos p ' +
        'JOIN ge_pedidos_lineas pl ON pl.id_pedido = p.id ' +
        'LEFT JOIN ge_articulos a ON a.id = pl.id_articulo ' +
        'LEFT JOIN ( ' +
        '  SELECT al.id_linea_pedido, SUM(lb.cantidad) AS cantidad_preparada ' +
        '  FROM ge_albaranes_lineas_bultos lb ' +
        '  JOIN ge_albaranes_lineas al ON lb.linea_albaran_id = al.id ' +
        '  GROUP BY al.id_linea_pedido ' +
        ') prep ON prep.id_linea_pedido = pl.id ' +
        'WHERE 1=1 ';

      if LEmpId > 0 then
        LSql := LSql + 'AND p.empresa_id = :emp ';

      case cbbEstado.ItemIndex of
        0: LSql := LSql + 'AND p.estado IN (''PENDIENTE'', ''EN PREPARACION'', ''PROCESADO'') ';
        1: LSql := LSql + 'AND p.estado = ''PENDIENTE'' ';
        2: LSql := LSql + 'AND p.estado = ''EN PREPARACION'' ';
        3: LSql := LSql + 'AND p.estado = ''PROCESADO'' ';
      end;

      if LFentVal = -1 then
        LSql := LSql + 'AND p.fecha_entrega IS NULL '
      else if LFentVal > 0 then
        LSql := LSql + 'AND DATE(p.fecha_entrega) = :f_entrega_sel ';

      if chkFiltrarFecha.Checked then
        LSql := LSql + 'AND p.fecha_entrega >= :f_desde AND p.fecha_entrega < :f_hasta ';

      LSql := LSql + 'AND (pl.cantidad - COALESCE(prep.cantidad_preparada, 0)) > 0 ';

      LQryArts.SQL.Text := LSql;
      if LEmpId > 0 then
        LQryArts.ParamByName('emp').AsInteger := LEmpId;
      if LFentVal > 0 then
        LQryArts.ParamByName('f_entrega_sel').AsString := FormatDateTime('yyyy-mm-dd', TDateTime(LFentVal));
      if chkFiltrarFecha.Checked then
      begin
        LQryArts.ParamByName('f_desde').AsDateTime := Trunc(dtpDesde.Date);
        LQryArts.ParamByName('f_hasta').AsDateTime := Trunc(dtpHasta.Date) + 1;
      end;

      LQryArts.Open;
      lblKpiArticulosVal.Caption := IntToStr(LQryArts.FieldByName('cant_articulos').AsInteger);
    finally
      LQryArts.Free;
    end;
  end
  else
  begin
    lblKpiArticulosVal.Caption := IntToStr(qTotalesProductos.RecordCount);

    LQryPed := TFDQuery.Create(nil);
    try
      LQryPed.Connection := dmgMain.dbConn;
      LSql :=
        'SELECT COUNT(DISTINCT p.id) AS cant_pedidos ' +
        'FROM ge_pedidos p ' +
        'JOIN ge_pedidos_lineas pl ON pl.id_pedido = p.id ' +
        'LEFT JOIN ( ' +
        '  SELECT al.id_linea_pedido, SUM(lb.cantidad) AS cantidad_preparada ' +
        '  FROM ge_albaranes_lineas_bultos lb ' +
        '  JOIN ge_albaranes_lineas al ON lb.linea_albaran_id = al.id ' +
        '  GROUP BY al.id_linea_pedido ' +
        ') prep ON prep.id_linea_pedido = pl.id ' +
        'WHERE 1=1 ';

      if LEmpId > 0 then
        LSql := LSql + 'AND p.empresa_id = :emp ';

      case cbbEstado.ItemIndex of
        0: LSql := LSql + 'AND p.estado IN (''PENDIENTE'', ''EN PREPARACION'', ''PROCESADO'') ';
        1: LSql := LSql + 'AND p.estado = ''PENDIENTE'' ';
        2: LSql := LSql + 'AND p.estado = ''EN PREPARACION'' ';
        3: LSql := LSql + 'AND p.estado = ''PROCESADO'' ';
      end;

      if LFentVal = -1 then
        LSql := LSql + 'AND p.fecha_entrega IS NULL '
      else if LFentVal > 0 then
        LSql := LSql + 'AND DATE(p.fecha_entrega) = :f_entrega_sel ';

      if chkFiltrarFecha.Checked then
        LSql := LSql + 'AND p.fecha_entrega >= :f_desde AND p.fecha_entrega < :f_hasta ';

      LSql := LSql + 'AND (pl.cantidad - COALESCE(prep.cantidad_preparada, 0)) > 0 ';

      LQryPed.SQL.Text := LSql;
      if LEmpId > 0 then
        LQryPed.ParamByName('emp').AsInteger := LEmpId;
      if LFentVal > 0 then
        LQryPed.ParamByName('f_entrega_sel').AsString := FormatDateTime('yyyy-mm-dd', TDateTime(LFentVal));
      if chkFiltrarFecha.Checked then
      begin
        LQryPed.ParamByName('f_desde').AsDateTime := Trunc(dtpDesde.Date);
        LQryPed.ParamByName('f_hasta').AsDateTime := Trunc(dtpHasta.Date) + 1;
      end;

      LQryPed.Open;
      lblKpiPedidosVal.Caption := IntToStr(LQryPed.FieldByName('cant_pedidos').AsInteger);
    finally
      LQryPed.Free;
    end;
  end;

  lblSubtitle.Caption := Format(
    'Diferenciado por orden de entrega, fecha de salida y consolidado | Total pedidos: %s uds en %s pedidos (%s uds a fabricar)',
    [FormatFloat('#,##0', FTotPendientesPedidos), lblKpiPedidosVal.Caption, FormatFloat('#,##0', FTotFabricar)]
  );
end;

procedure TfrmPedidosPendientesLogistica.qProductosAfterScroll(DataSet: TDataSet);
begin
  RefrescarDetalle;
end;

procedure TfrmPedidosPendientesLogistica.cbbModoVistaChange(Sender: TObject);
begin
  SetupGrids;
  RefrescarMaster;
end;

procedure TfrmPedidosPendientesLogistica.cbbEmpresaChange(Sender: TObject);
begin
  CargarFechasEntrega;
  RefrescarMaster;
end;

procedure TfrmPedidosPendientesLogistica.cbbFechaEntregaChange(Sender: TObject);
begin
  RefrescarMaster;
end;

procedure TfrmPedidosPendientesLogistica.cbbEstadoChange(Sender: TObject);
begin
  RefrescarMaster;
end;

procedure TfrmPedidosPendientesLogistica.chkFiltrarFechaClick(Sender: TObject);
begin
  dtpDesde.Enabled := chkFiltrarFecha.Checked;
  dtpHasta.Enabled := chkFiltrarFecha.Checked;
  RefrescarMaster;
end;

procedure TfrmPedidosPendientesLogistica.dtpDesdeChange(Sender: TObject);
begin
  if chkFiltrarFecha.Checked then
    RefrescarMaster;
end;

procedure TfrmPedidosPendientesLogistica.dtpHastaChange(Sender: TObject);
begin
  if chkFiltrarFecha.Checked then
    RefrescarMaster;
end;

procedure TfrmPedidosPendientesLogistica.edtBuscarChange(Sender: TObject);
begin
  RefrescarMaster;
end;

procedure TfrmPedidosPendientesLogistica.btnRefrescarClick(Sender: TObject);
begin
  CargarFechasEntrega;
  RefrescarMaster;
end;

procedure TfrmPedidosPendientesLogistica.btnCerrarClick(Sender: TObject);
begin
  Close;
end;

function TfrmPedidosPendientesLogistica.GetSqlExprMasas(const ADeficitExpr: string): string;
begin
  if FAjustarCuartos then
    Result := '(CEIL(ROUND(GREATEST(0, ' + ADeficitExpr + ') / NULLIF(rec.unidades_base, 0), 4) * 4) / 4.0)'
  else
    Result := 'ROUND(GREATEST(0, ' + ADeficitExpr + ') / NULLIF(rec.unidades_base, 0), 2)';
end;

function TfrmPedidosPendientesLogistica.GetSqlSubqueryRecetaCanonica: string;
begin
  Result :=
    '( ' +
    '  SELECT ' +
    '    rp.articulo_id, ' +
    '    r.id AS receta_id, ' +
    '    r.descripcion AS receta_nombre, ' +
    '    rp.formato, ' +
    '    rp.unidades_base, ' +
    '    CONCAT(COALESCE(rp.formato, ''''), IF(rp.unidades_base > 0, CONCAT('' ('', CAST(ROUND(rp.unidades_base, 0) AS CHAR), '' u/m)''), '''')) AS formato_rendimiento ' +
    '  FROM ( ' +
    '    SELECT ' +
    '      rp_sub.*, ' +
    '      ROW_NUMBER() OVER ( ' +
    '        PARTITION BY rp_sub.articulo_id ' +
    '        ORDER BY ' +
    '          CASE ' +
    '            WHEN a_sub.descripcion IS NOT NULL AND ( ' +
    '              UPPER(a_sub.descripcion) LIKE CONCAT(''%'', UPPER(TRIM(r_sub.descripcion)), ''%'') ' +
    '              OR UPPER(TRIM(r_sub.descripcion)) LIKE CONCAT(''%'', SUBSTRING_INDEX(UPPER(TRIM(a_sub.descripcion)), '' '', 2), ''%'') ' +
    '            ) THEN 0 ' +
    '            ELSE 1 ' +
    '          END, ' +
    '          CASE WHEN UPPER(r_sub.descripcion) LIKE ''%ADRIANO%'' THEN 1 ELSE 0 END, ' +
    '          rp_sub.id ASC ' +
    '      ) AS rn ' +
    '    FROM ob_recetas_productos rp_sub ' +
    '    JOIN ob_recetas r_sub ON rp_sub.receta_id = r_sub.id AND r_sub.activo = 1 ' +
    '    LEFT JOIN ge_articulos a_sub ON rp_sub.articulo_id = a_sub.id ' +
    '    WHERE rp_sub.activo = 1 ' +
    '  ) rp ' +
    '  JOIN ob_recetas r ON rp.receta_id = r.id ' +
    '  WHERE rp.rn = 1 ' +
    ') ';
end;

function TfrmPedidosPendientesLogistica.FormatearMasasStr(AMasas: Double): string;
var
  LEntero, LCuartos: Integer;
  LFracStr: string;
begin
  if AMasas <= 0.00001 then
  begin
    Result := '0 (Stock OK)';
    Exit;
  end;

  if not FAjustarCuartos then
  begin
    Result := FormatFloat('0.##', AMasas);
    Exit;
  end;

  LEntero := Trunc(AMasas);
  LCuartos := Round((AMasas - LEntero) * 4.0);
  if LCuartos >= 4 then
  begin
    Inc(LEntero);
    LCuartos := 0;
  end;

  case LCuartos of
    1: LFracStr := '1/4';
    2: LFracStr := '1/2';
    3: LFracStr := '3/4';
    else LFracStr := '';
  end;

  if LEntero = 0 then
    Result := FormatFloat('0.##', AMasas) + ' (' + LFracStr + ' masa)'
  else if LFracStr = '' then
  begin
    if LEntero = 1 then
      Result := '1 masa'
    else
      Result := IntToStr(LEntero) + ' masas';
  end
  else
    Result := FormatFloat('0.##', AMasas) + ' (' + IntToStr(LEntero) + ' ' + LFracStr + ' masas)';
end;

procedure TfrmPedidosPendientesLogistica.btnAjustarCuartosClick(Sender: TObject);
begin
  TfrmPlanificacionMasasProduccion.MostrarPlan(
    Self,
    GetSelectedEmpresaId,
    GetSelectedFechaEntregaVal,
    cbbEstado.ItemIndex,
    chkFiltrarFecha.Checked,
    dtpDesde.Date,
    dtpHasta.Date,
    Trim(edtBuscar.Text)
  );
  RefrescarMaster;
end;

procedure TfrmPedidosPendientesLogistica.dbgProductosDrawColumnCell(Sender: TObject;
  const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
var
  LVal: Double;
  LText: string;
begin
  if (gdSelected in State) then
  begin
    dbgProductos.Canvas.Brush.Color := clHighlight;
    dbgProductos.Canvas.Font.Color := clHighlightText;
  end
  else if (Column.FieldName = 'total_pendiente') then
  begin
    dbgProductos.Canvas.Font.Style := [fsBold];
    dbgProductos.Canvas.Font.Color := $000055CC;
  end
  else if (Column.FieldName = 'receta_nombre') then
  begin
    if (Column.Field = nil) or (Trim(Column.Field.AsString) = '') then
    begin
      if (gdSelected in State) then
      begin
        dbgProductos.Canvas.Font.Color := $00E0E0E0;
        dbgProductos.Canvas.Font.Style := [fsItalic];
      end
      else
      begin
        dbgProductos.Canvas.Brush.Color := $00F2F2F6;
        dbgProductos.Canvas.Font.Color := $007E7E94;
        dbgProductos.Canvas.Font.Style := [fsItalic];
      end;
      dbgProductos.Canvas.FillRect(Rect);
      LText := '(Sin receta vinculada)';
      dbgProductos.Canvas.TextRect(Rect, Rect.Left + 4, Rect.Top + 2, LText);
      Exit;
    end
    else
    begin
      dbgProductos.Canvas.Font.Style := [fsBold];
      dbgProductos.Canvas.Font.Color := $004A2610;
    end;
  end
  else if (Column.FieldName = 'formato_rendimiento') then
  begin
    if (Column.Field = nil) or (Trim(Column.Field.AsString) = '') then
    begin
      if not (gdSelected in State) then
      begin
        dbgProductos.Canvas.Font.Color := $00AAAAAA;
        dbgProductos.Canvas.Font.Style := [];
      end;
      dbgProductos.Canvas.FillRect(Rect);
      LText := '-';
      dbgProductos.Canvas.TextRect(Rect, Rect.Left + 4, Rect.Top + 2, LText);
      Exit;
    end
    else
    begin
      dbgProductos.Canvas.Font.Style := [];
      if not (gdSelected in State) then
        dbgProductos.Canvas.Font.Color := $00553311;
    end;
  end
  else if (Column.FieldName = 'masas_necesarias') then
  begin
    if (Column.Field = nil) or Column.Field.IsNull or (Trim(qProductos.FieldByName('receta_nombre').AsString) = '') then
    begin
      if not (gdSelected in State) then
      begin
        dbgProductos.Canvas.Font.Color := $00AAAAAA;
        dbgProductos.Canvas.Font.Style := [];
      end;
      dbgProductos.Canvas.FillRect(Rect);
      LText := '-';
      dbgProductos.Canvas.TextRect(Rect, Rect.Right - dbgProductos.Canvas.TextWidth(LText) - 6, Rect.Top + 2, LText);
      Exit;
    end
    else if (Column.Field.AsFloat <= 0) then
    begin
      if not (gdSelected in State) then
      begin
        dbgProductos.Canvas.Font.Color := $001B6B2B;
        dbgProductos.Canvas.Font.Style := [fsBold];
      end;
      dbgProductos.Canvas.FillRect(Rect);
      LText := '0 (Stock OK)';
      dbgProductos.Canvas.TextRect(Rect, Rect.Right - dbgProductos.Canvas.TextWidth(LText) - 6, Rect.Top + 2, LText);
      Exit;
    end
    else
    begin
      dbgProductos.Canvas.Font.Style := [fsBold];
      dbgProductos.Canvas.Font.Color := $00993300; // Ámbar/marrón distinguible para masas de obrador
      dbgProductos.Canvas.FillRect(Rect);
      LText := FormatearMasasStr(Column.Field.AsFloat);
      dbgProductos.Canvas.TextRect(Rect, Rect.Right - dbgProductos.Canvas.TextWidth(LText) - 6, Rect.Top + 2, LText);
      Exit;
    end;
  end
  else if (Column.FieldName = 'total_global_articulo') then
  begin
    dbgProductos.Canvas.Font.Style := [fsBold];
    dbgProductos.Canvas.Font.Color := $007A1A1A;
  end
  else if (Column.FieldName = 'stock_actual') then
  begin
    dbgProductos.Canvas.Font.Style := [fsBold];
    dbgProductos.Canvas.Font.Color := $00703010;
  end
  else if (Column.FieldName = 'balance_stock') then
  begin
    LVal := Column.Field.AsFloat;
    dbgProductos.Canvas.Font.Style := [fsBold];
    if LVal < 0 then
      dbgProductos.Canvas.Font.Color := $002020D0 // Rojo: déficit de existencias
    else
      dbgProductos.Canvas.Font.Color := $001B6B2B; // Verde: stock suficiente
  end;

  dbgProductos.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;

procedure TfrmPedidosPendientesLogistica.dbgProductosDblClick(Sender: TObject);
begin
  if cbbModoVista.ItemIndex = 1 then
    btnAbrirPedidoClick(Sender)
  else
  begin
    if not qDetallePedidos.IsEmpty then
      btnAbrirPedidoClick(Sender);
  end;
end;

procedure TfrmPedidosPendientesLogistica.dbgDetallePedidosDrawColumnCell(
  Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn;
  State: TGridDrawState);
var
  LVal: Double;
  LText: string;
begin
  if (gdSelected in State) then
  begin
    dbgDetallePedidos.Canvas.Brush.Color := clHighlight;
    dbgDetallePedidos.Canvas.Font.Color := clHighlightText;
  end
  else if (Column.FieldName = 'cantidad_pendiente') then
  begin
    dbgDetallePedidos.Canvas.Font.Style := [fsBold];
    dbgDetallePedidos.Canvas.Font.Color := $000055CC;
  end
  else if (Column.FieldName = 'receta_nombre') then
  begin
    if (Column.Field = nil) or (Trim(Column.Field.AsString) = '') then
    begin
      if (gdSelected in State) then
      begin
        dbgDetallePedidos.Canvas.Font.Color := $00E0E0E0;
        dbgDetallePedidos.Canvas.Font.Style := [fsItalic];
      end
      else
      begin
        dbgDetallePedidos.Canvas.Brush.Color := $00F2F2F6;
        dbgDetallePedidos.Canvas.Font.Color := $007E7E94;
        dbgDetallePedidos.Canvas.Font.Style := [fsItalic];
      end;
      dbgDetallePedidos.Canvas.FillRect(Rect);
      LText := '(Sin receta vinculada)';
      dbgDetallePedidos.Canvas.TextRect(Rect, Rect.Left + 4, Rect.Top + 2, LText);
      Exit;
    end
    else
    begin
      dbgDetallePedidos.Canvas.Font.Style := [fsBold];
      dbgDetallePedidos.Canvas.Font.Color := $004A2610;
    end;
  end
  else if (Column.FieldName = 'formato_rendimiento') then
  begin
    if (Column.Field = nil) or (Trim(Column.Field.AsString) = '') then
    begin
      if not (gdSelected in State) then
      begin
        dbgDetallePedidos.Canvas.Font.Color := $00AAAAAA;
        dbgDetallePedidos.Canvas.Font.Style := [];
      end;
      dbgDetallePedidos.Canvas.FillRect(Rect);
      LText := '-';
      dbgDetallePedidos.Canvas.TextRect(Rect, Rect.Left + 4, Rect.Top + 2, LText);
      Exit;
    end
    else
    begin
      dbgDetallePedidos.Canvas.Font.Style := [];
      if not (gdSelected in State) then
        dbgDetallePedidos.Canvas.Font.Color := $00553311;
    end;
  end
  else if (Column.FieldName = 'masas_necesarias') then
  begin
    if (Column.Field = nil) or Column.Field.IsNull or (Trim(qDetallePedidos.FieldByName('receta_nombre').AsString) = '') then
    begin
      if not (gdSelected in State) then
      begin
        dbgDetallePedidos.Canvas.Font.Color := $00AAAAAA;
        dbgDetallePedidos.Canvas.Font.Style := [];
      end;
      dbgDetallePedidos.Canvas.FillRect(Rect);
      LText := '-';
      dbgDetallePedidos.Canvas.TextRect(Rect, Rect.Right - dbgDetallePedidos.Canvas.TextWidth(LText) - 6, Rect.Top + 2, LText);
      Exit;
    end
    else if (Column.Field.AsFloat <= 0) then
    begin
      if not (gdSelected in State) then
      begin
        dbgDetallePedidos.Canvas.Font.Color := $001B6B2B;
        dbgDetallePedidos.Canvas.Font.Style := [fsBold];
      end;
      dbgDetallePedidos.Canvas.FillRect(Rect);
      LText := '0 (Stock OK)';
      dbgDetallePedidos.Canvas.TextRect(Rect, Rect.Right - dbgDetallePedidos.Canvas.TextWidth(LText) - 6, Rect.Top + 2, LText);
      Exit;
    end
    else
    begin
      dbgDetallePedidos.Canvas.Font.Style := [fsBold];
      dbgDetallePedidos.Canvas.Font.Color := $00993300;
      dbgDetallePedidos.Canvas.FillRect(Rect);
      LText := FormatearMasasStr(Column.Field.AsFloat);
      dbgDetallePedidos.Canvas.TextRect(Rect, Rect.Right - dbgDetallePedidos.Canvas.TextWidth(LText) - 6, Rect.Top + 2, LText);
      Exit;
    end;
  end
  else if (Column.FieldName = 'stock_actual') then
  begin
    dbgDetallePedidos.Canvas.Font.Style := [fsBold];
    dbgDetallePedidos.Canvas.Font.Color := $00703010;
  end
  else if (Column.FieldName = 'balance_stock') then
  begin
    LVal := Column.Field.AsFloat;
    dbgDetallePedidos.Canvas.Font.Style := [fsBold];
    if LVal < 0 then
      dbgDetallePedidos.Canvas.Font.Color := $002020D0
    else
      dbgDetallePedidos.Canvas.Font.Color := $001B6B2B;
  end;

  dbgDetallePedidos.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;

procedure TfrmPedidosPendientesLogistica.dbgDetallePedidosDblClick(Sender: TObject);
begin
  btnAbrirPedidoClick(Sender);
end;

procedure TfrmPedidosPendientesLogistica.dbgTotalesProductosDrawColumnCell(
  Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn;
  State: TGridDrawState);
var
  LVal: Double;
  LText: string;
begin
  if (gdSelected in State) then
  begin
    dbgTotalesProductos.Canvas.Brush.Color := clHighlight;
    dbgTotalesProductos.Canvas.Font.Color := clHighlightText;
  end
  else if (Column.FieldName = 'total_pendiente') then
  begin
    dbgTotalesProductos.Canvas.Font.Style := [fsBold];
    dbgTotalesProductos.Canvas.Font.Color := $000055CC;
  end
  else if (Column.FieldName = 'receta_nombre') then
  begin
    if (Column.Field = nil) or (Trim(Column.Field.AsString) = '') then
    begin
      if (gdSelected in State) then
      begin
        dbgTotalesProductos.Canvas.Font.Color := $00E0E0E0;
        dbgTotalesProductos.Canvas.Font.Style := [fsItalic];
      end
      else
      begin
        dbgTotalesProductos.Canvas.Brush.Color := $00F2F2F6;
        dbgTotalesProductos.Canvas.Font.Color := $007E7E94;
        dbgTotalesProductos.Canvas.Font.Style := [fsItalic];
      end;
      dbgTotalesProductos.Canvas.FillRect(Rect);
      LText := '(Sin receta vinculada)';
      dbgTotalesProductos.Canvas.TextRect(Rect, Rect.Left + 4, Rect.Top + 2, LText);
      Exit;
    end
    else
    begin
      dbgTotalesProductos.Canvas.Font.Style := [fsBold];
      dbgTotalesProductos.Canvas.Font.Color := $004A2610;
    end;
  end
  else if (Column.FieldName = 'formato_rendimiento') then
  begin
    if (Column.Field = nil) or (Trim(Column.Field.AsString) = '') then
    begin
      if not (gdSelected in State) then
      begin
        dbgTotalesProductos.Canvas.Font.Color := $00AAAAAA;
        dbgTotalesProductos.Canvas.Font.Style := [];
      end;
      dbgTotalesProductos.Canvas.FillRect(Rect);
      LText := '-';
      dbgTotalesProductos.Canvas.TextRect(Rect, Rect.Left + 4, Rect.Top + 2, LText);
      Exit;
    end
    else
    begin
      dbgTotalesProductos.Canvas.Font.Style := [];
      if not (gdSelected in State) then
        dbgTotalesProductos.Canvas.Font.Color := $00553311;
    end;
  end
  else if (Column.FieldName = 'masas_necesarias') then
  begin
    if (Column.Field = nil) or Column.Field.IsNull or (Trim(qTotalesProductos.FieldByName('receta_nombre').AsString) = '') then
    begin
      if not (gdSelected in State) then
      begin
        dbgTotalesProductos.Canvas.Font.Color := $00AAAAAA;
        dbgTotalesProductos.Canvas.Font.Style := [];
      end;
      dbgTotalesProductos.Canvas.FillRect(Rect);
      LText := '-';
      dbgTotalesProductos.Canvas.TextRect(Rect, Rect.Right - dbgTotalesProductos.Canvas.TextWidth(LText) - 6, Rect.Top + 2, LText);
      Exit;
    end
    else if (Column.Field.AsFloat <= 0) then
    begin
      if not (gdSelected in State) then
      begin
        dbgTotalesProductos.Canvas.Font.Color := $001B6B2B;
        dbgTotalesProductos.Canvas.Font.Style := [fsBold];
      end;
      dbgTotalesProductos.Canvas.FillRect(Rect);
      LText := '0 (Stock OK)';
      dbgTotalesProductos.Canvas.TextRect(Rect, Rect.Right - dbgTotalesProductos.Canvas.TextWidth(LText) - 6, Rect.Top + 2, LText);
      Exit;
    end
    else
    begin
      dbgTotalesProductos.Canvas.Font.Style := [fsBold];
      dbgTotalesProductos.Canvas.Font.Color := $00993300;
      dbgTotalesProductos.Canvas.FillRect(Rect);
      LText := FormatearMasasStr(Column.Field.AsFloat);
      dbgTotalesProductos.Canvas.TextRect(Rect, Rect.Right - dbgTotalesProductos.Canvas.TextWidth(LText) - 6, Rect.Top + 2, LText);
      Exit;
    end;
  end
  else if (Column.FieldName = 'stock_actual') then
  begin
    dbgTotalesProductos.Canvas.Font.Style := [fsBold];
    dbgTotalesProductos.Canvas.Font.Color := $00703010;
  end
  else if (Column.FieldName = 'balance_stock') then
  begin
    LVal := Column.Field.AsFloat;
    dbgTotalesProductos.Canvas.Font.Style := [fsBold];
    if LVal < 0 then
      dbgTotalesProductos.Canvas.Font.Color := $002020D0
    else
      dbgTotalesProductos.Canvas.Font.Color := $001B6B2B;
  end;

  dbgTotalesProductos.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;

procedure TfrmPedidosPendientesLogistica.dbgIngredientesMasasDrawColumnCell(
  Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn;
  State: TGridDrawState);
begin
  if (gdSelected in State) then
  begin
    dbgIngredientesMasas.Canvas.Brush.Color := clHighlight;
    dbgIngredientesMasas.Canvas.Font.Color := clHighlightText;
  end
  else if (Column.FieldName = 'proceso_nombre') then
  begin
    dbgIngredientesMasas.Canvas.Font.Style := [fsBold];
    dbgIngredientesMasas.Canvas.Font.Color := $004A2610; // Marrón chocolate corporativo
  end
  else if (Column.FieldName = 'total_necesario_kg') then
  begin
    dbgIngredientesMasas.Canvas.Font.Style := [fsBold];
    dbgIngredientesMasas.Canvas.Font.Color := $001B6B2B; // Verde oscuro distintivo
  end
  else if (Column.FieldName = 'total_necesario_g') then
  begin
    dbgIngredientesMasas.Canvas.Font.Style := [fsBold];
    dbgIngredientesMasas.Canvas.Font.Color := $00993300; // Ámbar/marrón
  end;

  dbgIngredientesMasas.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;

procedure TfrmPedidosPendientesLogistica.btnAbrirPedidoClick(Sender: TObject);
var
  LPedidoId: string;
begin
  LPedidoId := GetActivePedidoId;
  if LPedidoId = '' then
  begin
    ShowMessage('Seleccione una fila para abrir el pedido correspondiente.');
    Exit;
  end;

  if not Assigned(frmPedidosEditor) then
    Application.CreateForm(TfrmPedidosEditor, frmPedidosEditor);

  frmPedidosEditor.ParentForm := Self;
  frmPedidosEditor.PedidoId := LPedidoId;
  if frmPedidosEditor.ShowModal = mrOk then
    RefrescarMaster;
end;

procedure TfrmPedidosPendientesLogistica.btnPrepararPedidoClick(Sender: TObject);
var
  LPedidoId: string;
  LFrm: TfrmPreparacionPedidoEditor;
begin
  LPedidoId := GetActivePedidoId;
  if LPedidoId = '' then
  begin
    ShowMessage('Seleccione una fila para iniciar la preparación del pedido.');
    Exit;
  end;

  LFrm := TfrmPreparacionPedidoEditor.Create(Application);
  try
    LFrm.PedidoId := LPedidoId;
    LFrm.ShowModal;
  finally
    LFrm.Free;
    RefrescarMaster;
  end;
end;

procedure TfrmPedidosPendientesLogistica.btnExportarClick(Sender: TObject);
var
  LCSV: TStringList;
  LFileName: string;
  LBookmark: TBookmark;
  LModo: Integer;
begin
  if qProductos.IsEmpty then
  begin
    ShowMessage('No hay registros pendientes para exportar.');
    Exit;
  end;

  LModo := cbbModoVista.ItemIndex;
  saveDlgExport.FileName := Format('Pendientes_Logistica_Modo%d_%s.csv', [LModo, FormatDateTime('yyyymmdd_hhnn', Now)]);
  if not saveDlgExport.Execute then Exit;

  LFileName := saveDlgExport.FileName;
  LCSV := TStringList.Create;
  try
    LCSV.WriteBOM := True;

    case LModo of
      0: // Por Fecha de Entrega y Producto
      begin
        LCSV.Add('F. Entrega;Ref;EAN;Producto;Nº Pedidos Fecha;Bultos Fecha;Cant. Solicitada Fecha;Ya Preparado;Pendiente Fecha;Stock Almacén;TOTAL PRODUCTO;Balance Stock;Receta Maestra;Formato (Rdto);Masas Necesarias');
        LBookmark := qProductos.GetBookmark;
        try
          qProductos.First;
          while not qProductos.Eof do
          begin
            LCSV.Add(Format('"%s";"%s";"%s";"%s";%s;%s;%s;%s;%s;%s;%s;%s;"%s";"%s";%s', [
              qProductos.FieldByName('fecha_entrega_str').AsString,
              qProductos.FieldByName('articulo_id').AsString,
              qProductos.FieldByName('ean').AsString,
              StringReplace(qProductos.FieldByName('producto_nombre').AsString, '"', '""', [rfReplaceAll]),
              qProductos.FieldByName('total_pedidos').AsString,
              qProductos.FieldByName('total_bultos').AsString,
              FormatFloat('0.##', qProductos.FieldByName('total_solicitado').AsFloat),
              FormatFloat('0.##', qProductos.FieldByName('total_preparado').AsFloat),
              FormatFloat('0.##', qProductos.FieldByName('total_pendiente').AsFloat),
              FormatFloat('0.##', qProductos.FieldByName('stock_actual').AsFloat),
              FormatFloat('0.##', qProductos.FieldByName('total_global_articulo').AsFloat),
              FormatFloat('0.##', qProductos.FieldByName('balance_stock').AsFloat),
              StringReplace(qProductos.FieldByName('receta_nombre').AsString, '"', '""', [rfReplaceAll]),
              StringReplace(qProductos.FieldByName('formato_rendimiento').AsString, '"', '""', [rfReplaceAll]),
              FormatFloat('0.##', qProductos.FieldByName('masas_necesarias').AsFloat)
            ]));
            qProductos.Next;
          end;
        finally
          if qProductos.BookmarkValid(LBookmark) then
            qProductos.GotoBookmark(LBookmark);
          qProductos.FreeBookmark(LBookmark);
        end;
      end;

      1: // Por Pedido / Orden de Entrega
      begin
        LCSV.Add('F. Entrega;Nº Pedido;Cliente;Destino;Población;Artículos;Bultos;Solicitado;Preparado;Pendiente;Estado');
        LBookmark := qProductos.GetBookmark;
        try
          qProductos.First;
          while not qProductos.Eof do
          begin
            LCSV.Add(Format('"%s";"%s";"%s";"%s";"%s";%s;%s;%s;%s;%s;"%s"', [
              qProductos.FieldByName('fecha_entrega_str').AsString,
              qProductos.FieldByName('numero_pedido').AsString,
              StringReplace(qProductos.FieldByName('cliente_nombre').AsString, '"', '""', [rfReplaceAll]),
              StringReplace(qProductos.FieldByName('destino_nombre').AsString, '"', '""', [rfReplaceAll]),
              StringReplace(qProductos.FieldByName('poblacion').AsString, '"', '""', [rfReplaceAll]),
              qProductos.FieldByName('total_lineas').AsString,
              qProductos.FieldByName('total_bultos').AsString,
              FormatFloat('0.##', qProductos.FieldByName('total_solicitado').AsFloat),
              FormatFloat('0.##', qProductos.FieldByName('total_preparado').AsFloat),
              FormatFloat('0.##', qProductos.FieldByName('total_pendiente').AsFloat),
              qProductos.FieldByName('estado').AsString
            ]));
            qProductos.Next;
          end;
        finally
          if qProductos.BookmarkValid(LBookmark) then
            qProductos.GotoBookmark(LBookmark);
          qProductos.FreeBookmark(LBookmark);
        end;
      end;

      else // Modo 2: Consolidado Global
      begin
        LCSV.Add('Ref;EAN;Producto;Nº Pedidos;Bultos;Cant. Solicitada;Ya Preparado;Pendiente;Stock Almacén;Balance Stock;Receta Maestra;Formato (Rdto);Masas Necesarias');
        LBookmark := qProductos.GetBookmark;
        try
          qProductos.First;
          while not qProductos.Eof do
          begin
            LCSV.Add(Format('"%s";"%s";"%s";%s;%s;%s;%s;%s;%s;%s;"%s";"%s";%s', [
              qProductos.FieldByName('articulo_id').AsString,
              qProductos.FieldByName('ean').AsString,
              StringReplace(qProductos.FieldByName('producto_nombre').AsString, '"', '""', [rfReplaceAll]),
              qProductos.FieldByName('total_pedidos').AsString,
              qProductos.FieldByName('total_bultos').AsString,
              FormatFloat('0.##', qProductos.FieldByName('total_solicitado').AsFloat),
              FormatFloat('0.##', qProductos.FieldByName('total_preparado').AsFloat),
              FormatFloat('0.##', qProductos.FieldByName('total_pendiente').AsFloat),
              FormatFloat('0.##', qProductos.FieldByName('stock_actual').AsFloat),
              FormatFloat('0.##', qProductos.FieldByName('balance_stock').AsFloat),
              StringReplace(qProductos.FieldByName('receta_nombre').AsString, '"', '""', [rfReplaceAll]),
              StringReplace(qProductos.FieldByName('formato_rendimiento').AsString, '"', '""', [rfReplaceAll]),
              FormatFloat('0.##', qProductos.FieldByName('masas_necesarias').AsFloat)
            ]));
            qProductos.Next;
          end;
        finally
          if qProductos.BookmarkValid(LBookmark) then
            qProductos.GotoBookmark(LBookmark);
          qProductos.FreeBookmark(LBookmark);
        end;
      end;
    end;

    // Agregar sección de Totales Consolidados por Producto al final del CSV
    if (LModo in [0, 1]) and (not qTotalesProductos.IsEmpty) then
    begin
      LCSV.Add('');
      LCSV.Add('--- TOTALES CONSOLIDADOS POR PRODUCTO Y STOCK ---');
      LCSV.Add('Ref;EAN;Producto;Nº Pedidos Total;Bultos Total;Solicitado Total;Preparado Total;TOTAL PENDIENTE;Stock Almacén;Balance Stock;Receta Maestra;Formato (Rdto);Masas Necesarias');
      LBookmark := qTotalesProductos.GetBookmark;
      try
        qTotalesProductos.First;
        while not qTotalesProductos.Eof do
        begin
          LCSV.Add(Format('"%s";"%s";"%s";%s;%s;%s;%s;%s;%s;%s;"%s";"%s";%s', [
            qTotalesProductos.FieldByName('articulo_id').AsString,
            qTotalesProductos.FieldByName('ean').AsString,
            StringReplace(qTotalesProductos.FieldByName('producto_nombre').AsString, '"', '""', [rfReplaceAll]),
            qTotalesProductos.FieldByName('total_pedidos').AsString,
            qTotalesProductos.FieldByName('total_bultos').AsString,
            FormatFloat('0.##', qTotalesProductos.FieldByName('total_solicitado').AsFloat),
            FormatFloat('0.##', qTotalesProductos.FieldByName('total_preparado').AsFloat),
            FormatFloat('0.##', qTotalesProductos.FieldByName('total_pendiente').AsFloat),
            FormatFloat('0.##', qTotalesProductos.FieldByName('stock_actual').AsFloat),
            FormatFloat('0.##', qTotalesProductos.FieldByName('balance_stock').AsFloat),
            StringReplace(qTotalesProductos.FieldByName('receta_nombre').AsString, '"', '""', [rfReplaceAll]),
            StringReplace(qTotalesProductos.FieldByName('formato_rendimiento').AsString, '"', '""', [rfReplaceAll]),
            FormatFloat('0.##', qTotalesProductos.FieldByName('masas_necesarias').AsFloat)
          ]));
          qTotalesProductos.Next;
        end;

        LCSV.Add(Format('"TOTALES CONSOLIDADOS";"";"";"";"";"";"";"%s uds";"%s uds";"Déficit Fabricar: %s uds";"";"";"Total Masas: %s"', [
          FormatFloat('0.##', FTotPendientesPedidos),
          FormatFloat('0.##', FTotStockAlmacen),
          FormatFloat('0.##', FTotFabricar),
          FormatFloat('0.##', FTotMasas)
        ]));
      finally
        if qTotalesProductos.BookmarkValid(LBookmark) then
          qTotalesProductos.GotoBookmark(LBookmark);
        qTotalesProductos.FreeBookmark(LBookmark);
      end;
    end;

    LCSV.SaveToFile(LFileName, TEncoding.UTF8);

    if MessageDlg('Resumen exportado correctamente.'#13#10#191'Desea abrir el archivo generado?',
                  mtConfirmation, [mbYes, mbNo], 0) = mrYes then
    begin
      ShellExecute(0, 'open', PChar(LFileName), nil, nil, SW_SHOWNORMAL);
    end;
  finally
    LCSV.Free;
  end;
end;

procedure TfrmPedidosPendientesLogistica.CargarIngredientesMasas;
var
  LSql: string;
  LSqlFiltros: string;
  LEmpId, LFentVal: Integer;
  LSearch: string;
  LSqlMasasExpr: string;
begin
  LEmpId := GetSelectedEmpresaId;
  LFentVal := GetSelectedFechaEntregaVal;
  LSearch := Trim(edtBuscar.Text);

  if FAjustarCuartos then
    LSqlMasasExpr := 'SUM(CEIL(ROUND(GREATEST(0, tot.total_pendiente - COALESCE(stk.stock_actual, 0)) / NULLIF(rec.unidades_base, 0), 4) * 4) / 4.0)'
  else
    LSqlMasasExpr := 'SUM(ROUND(GREATEST(0, tot.total_pendiente - COALESCE(stk.stock_actual, 0)) / NULLIF(rec.unidades_base, 0), 4))';

  qIngredientesMasas.Close;

  LSqlFiltros := '';
  if LEmpId > 0 then
    LSqlFiltros := LSqlFiltros + 'AND p.empresa_id = :emp ';

  case cbbEstado.ItemIndex of
    0: LSqlFiltros := LSqlFiltros + 'AND p.estado IN (''PENDIENTE'', ''EN PREPARACION'', ''PROCESADO'') ';
    1: LSqlFiltros := LSqlFiltros + 'AND p.estado = ''PENDIENTE'' ';
    2: LSqlFiltros := LSqlFiltros + 'AND p.estado = ''EN PREPARACION'' ';
    3: LSqlFiltros := LSqlFiltros + 'AND p.estado = ''PROCESADO'' ';
  end;

  if LFentVal = -1 then
    LSqlFiltros := LSqlFiltros + 'AND p.fecha_entrega IS NULL '
  else if LFentVal > 0 then
    LSqlFiltros := LSqlFiltros + 'AND DATE(p.fecha_entrega) = :f_entrega_sel ';

  if chkFiltrarFecha.Checked then
    LSqlFiltros := LSqlFiltros + 'AND p.fecha_entrega >= :f_desde AND p.fecha_entrega < :f_hasta ';

  if LSearch <> '' then
  begin
    LSqlFiltros := LSqlFiltros + 'AND (a.descripcion LIKE :search ' +
                                 '     OR pl.descripcion LIKE :search ' +
                                 '     OR a.ean LIKE :search ' +
                                 '     OR pl.ean_producto LIKE :search ' +
                                 '     OR c.nombre_fiscal LIKE :search) ';
  end;

  LSql :=
    'SELECT ' +
    '  m.proceso_orden, ' +
    '  m.proceso_nombre, ' +
    '  m.materia_prima_id, ' +
    '  m.ingrediente_nombre, ' +
    '  GROUP_CONCAT(DISTINCT m.receta_nombre ORDER BY m.receta_nombre SEPARATOR '', '') AS recetas_usadas, ' +
    '  SUM(ROUND(m.masas_receta * m.cantidad_base, 2)) AS total_necesario_g, ' +
    '  ROUND(SUM(m.masas_receta * m.cantidad_base) / 1000.0, 3) AS total_necesario_kg, ' +
    '  m.unidad ' +
    'FROM ( ' +
    '  SELECT ' +
    '    v.proceso_orden, ' +
    '    v.proceso_nombre, ' +
    '    v.id_materia_prima AS materia_prima_id, ' +
    '    COALESCE(v.ingrediente_descripcion, CONCAT(''Ingrediente '', v.id_materia_prima)) AS ingrediente_nombre, ' +
    '    v.receta_raiz_desc AS receta_nombre, ' +
    '    rec_masas.masas_necesarias AS masas_receta, ' +
    '    v.cantidad_canonica AS cantidad_base, ' +
    '    v.unidad_canonica AS unidad ' +
    '  FROM ( ' +
    '    SELECT ' +
    '      rec.receta_id, ' +
    '      ' + LSqlMasasExpr + ' AS masas_necesarias ' +
    '    FROM ( ' +
    '      SELECT ' +
    '        COALESCE(a.id, pl.id_articulo) AS articulo_id, ' +
    '        COALESCE(NULLIF(a.id_maestro, 0), a.id, pl.id_articulo) AS articulo_maestro_id, ' +
    '        (SUM(pl.cantidad) - COALESCE(SUM(prep.cantidad_preparada), 0)) AS total_pendiente ' +
    '      FROM ge_pedidos p ' +
    '      JOIN ge_pedidos_lineas pl ON pl.id_pedido = p.id ' +
    '      LEFT JOIN ge_articulos a ON a.id = pl.id_articulo ' +
    '      LEFT JOIN ge_clientes c ON p.cliente_id = c.id ' +
    '      LEFT JOIN ( ' +
    '        SELECT al.id_linea_pedido, SUM(lb.cantidad) AS cantidad_preparada ' +
    '        FROM ge_albaranes_lineas_bultos lb ' +
    '        JOIN ge_albaranes_lineas al ON lb.linea_albaran_id = al.id ' +
    '        GROUP BY al.id_linea_pedido ' +
    '      ) prep ON prep.id_linea_pedido = pl.id ' +
    '      WHERE 1=1 ' + LSqlFiltros +
    '      GROUP BY COALESCE(a.id, pl.id_articulo), COALESCE(NULLIF(a.id_maestro, 0), a.id, pl.id_articulo) ' +
    '      HAVING total_pendiente > 0 ' +
    '    ) tot ' +
    '    LEFT JOIN ( ' +
    '      SELECT se.id_articulo, SUM(se.cantidad_unidades) AS stock_actual ' +
    '      FROM ge_stock_envasado se ' +
    '      JOIN ge_almacenes alm ON se.id_almacen = alm.id AND alm.activo = 1 AND alm.compartido = 1 ' +
    '      WHERE se.estado_fabricacion = ''ENVASADO'' ' +
    '      GROUP BY se.id_articulo ' +
    '    ) stk ON stk.id_articulo = tot.articulo_maestro_id ' +
    '    JOIN ( ' +
    '      SELECT rp.articulo_id, rp.receta_id, rp.unidades_base ' +
    '      FROM ' + GetSqlSubqueryRecetaCanonica + ' rp ' +
    '    ) rec ON (rec.articulo_id = tot.articulo_id OR rec.articulo_id = tot.articulo_maestro_id) ' +
    '    WHERE GREATEST(0, tot.total_pendiente - COALESCE(stk.stock_actual, 0)) > 0 ' +
    '    GROUP BY rec.receta_id ' +
    '    HAVING masas_necesarias > 0 ' +
    '  ) rec_masas ' +
    '  JOIN vw_recetas_ingredientes_arbol v ON v.receta_raiz_id = rec_masas.receta_id AND v.es_hoja = 1 ' +
    ') m ' +
    'GROUP BY m.proceso_orden, m.proceso_nombre, m.materia_prima_id, m.ingrediente_nombre, m.unidad ' +
    'ORDER BY m.proceso_orden ASC, total_necesario_g DESC';

  qIngredientesMasas.SQL.Text := LSql;

  if LEmpId > 0 then
    qIngredientesMasas.ParamByName('emp').AsInteger := LEmpId;

  if LFentVal > 0 then
    qIngredientesMasas.ParamByName('f_entrega_sel').AsString := FormatDateTime('yyyy-mm-dd', TDateTime(LFentVal));

  if chkFiltrarFecha.Checked then
  begin
    qIngredientesMasas.ParamByName('f_desde').AsDateTime := Trunc(dtpDesde.Date);
    qIngredientesMasas.ParamByName('f_hasta').AsDateTime := Trunc(dtpHasta.Date) + 1;
  end;

  if LSearch <> '' then
    qIngredientesMasas.ParamByName('search').AsString := '%' + LSearch + '%';

  qIngredientesMasas.Open;

  if qIngredientesMasas.FindField('total_necesario_kg') <> nil then
    TNumericField(qIngredientesMasas.FieldByName('total_necesario_kg')).DisplayFormat := '#,##0.000 ''kg''';
  if qIngredientesMasas.FindField('total_necesario_g') <> nil then
    TNumericField(qIngredientesMasas.FieldByName('total_necesario_g')).DisplayFormat := '#,##0.## ''g''';

  if qIngredientesMasas.IsEmpty then
    tsIngredientesMasas.Caption := 'Desglose de Ingredientes (0)'
  else
    tsIngredientesMasas.Caption := Format('Desglose de Ingredientes (%d)', [qIngredientesMasas.RecordCount]);
end;

procedure TfrmPedidosPendientesLogistica.btnImprimirClick(Sender: TObject);
var
  LReportPath: string;
  LComp: TfrxComponent;
  LPage: TfrxComponent;
begin
  if qProductos.IsEmpty and qTotalesProductos.IsEmpty then
  begin
    ShowMessage('No hay datos pendientes para imprimir.');
    Exit;
  end;

  // 1. Resolver ruta del archivo de plantilla FastReport (.fr3)
  LReportPath := TFormatosImpresionService.ResolverRutaArchivo('productos_pendientes_logistica.fr3');
  if (LReportPath = '') or not FileExists(LReportPath) then
    LReportPath := ExtractFilePath(ParamStr(0)) + 'reportes\productos_pendientes_logistica.fr3';
  if not FileExists(LReportPath) then
    LReportPath := 'reportes\productos_pendientes_logistica.fr3';

  if not FileExists(LReportPath) then
  begin
    ShowMessage('No se ha encontrado la plantilla FastReport en:' + sLineBreak + LReportPath);
    Exit;
  end;

  // 2. Cargar ingredientes para las masas restantes que hay que fabricar
  CargarIngredientesMasas;

  // 3. Asociar frxDBDatasets con los queries activos
  frxDBProductos.DataSet := qProductos;
  frxDBProductos.UserName := 'frxDBpendientes';

  frxDBTotales.DataSet := qTotalesProductos;
  frxDBTotales.UserName := 'frxDBtotales';

  frxDBIngredientes.DataSet := qIngredientesMasas;
  frxDBIngredientes.UserName := 'frxDBingredientes';

  // 4. Configurar frxInforme: Cargar plantilla primero y registrar datasets después
  dmgMain.frxInforme.Clear;
  dmgMain.frxInforme.LoadFromFile(LReportPath);

  dmgMain.frxInforme.DataSets.Clear;
  dmgMain.frxInforme.DataSets.Add(frxDBProductos);
  dmgMain.frxInforme.DataSets.Add(frxDBTotales);
  dmgMain.frxInforme.DataSets.Add(frxDBIngredientes);

  dmgMain.frxInforme.EnabledDataSets.Clear;
  dmgMain.frxInforme.EnabledDataSets.Add(frxDBProductos);
  dmgMain.frxInforme.EnabledDataSets.Add(frxDBTotales);
  dmgMain.frxInforme.EnabledDataSets.Add(frxDBIngredientes);

  // Asegurar enlace directo de las bandas maestras con los datasets
  LComp := dmgMain.frxInforme.FindObject('MasterData1');
  if (LComp <> nil) and (LComp is TfrxMasterData) then
    TfrxMasterData(LComp).DataSet := frxDBProductos;

  LComp := dmgMain.frxInforme.FindObject('MasterData2');
  if (LComp <> nil) and (LComp is TfrxMasterData) then
    TfrxMasterData(LComp).DataSet := frxDBTotales;

  LComp := dmgMain.frxInforme.FindObject('MasterData3');
  if (LComp <> nil) and (LComp is TfrxMasterData) then
    TfrxMasterData(LComp).DataSet := frxDBIngredientes;

  // Controlar visibilidad de las páginas según haya datos en cada dataset
  LPage := dmgMain.frxInforme.FindObject('Page1');
  if (LPage <> nil) and (LPage is TfrxReportPage) then
    TfrxReportPage(LPage).Visible := not qProductos.IsEmpty;

  LPage := dmgMain.frxInforme.FindObject('Page2');
  if (LPage <> nil) and (LPage is TfrxReportPage) then
    TfrxReportPage(LPage).Visible := not qTotalesProductos.IsEmpty;

  LPage := dmgMain.frxInforme.FindObject('Page3');
  if (LPage <> nil) and (LPage is TfrxReportPage) then
    TfrxReportPage(LPage).Visible := not qIngredientesMasas.IsEmpty;

  // 5. Pasar variables de filtros y contexto a FastReport
  dmgMain.frxInforme.Variables['FiltroEmpresa'] := '''' + cbbEmpresa.Text + '''';
  dmgMain.frxInforme.Variables['FiltroFecha'] := '''' + cbbFechaEntrega.Text + '''';
  dmgMain.frxInforme.Variables['FiltroEstado'] := '''' + cbbEstado.Text + '''';
  dmgMain.frxInforme.Variables['FiltroModo'] := '''' + cbbModoVista.Text + '''';
  dmgMain.frxInforme.Variables['FechaHoraEmision'] := '''' + FormatDateTime('dd/mm/yyyy hh:nn', Now) + '''';
  dmgMain.frxInforme.Variables['TotalUdsAFabricar'] := '''' + FormatFloat('#,##0', FTotFabricar) + ' uds''';
  dmgMain.frxInforme.Variables['TotalMasasEstimadas'] := '''' + FormatFloat('#,##0.##', FTotMasas) + ' masas''';
  dmgMain.frxInforme.Variables['TotalPedidosUds'] := '''' + FormatFloat('#,##0', FTotPendientesPedidos) + ' uds''';

  // 6. Invocar diálogo estándar de opciones de impresión (Preview, Imprimir, PDF, Excel)
  TfrmPrintOptions.ShowOptions(
    Self,
    dmgMain.frxInforme,
    dbgProductos,
    'Productos_Pendientes_Logistica_' + FormatDateTime('yyyymmdd_hhnn', Now),
    '',
    '',
    1,
    nil,
    nil,
    'LOGISTICA_PENDIENTES'
  );
end;

end.
