unit frm_AnalisisImportacionFicha;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
  System.StrUtils, System.Math, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
  Vcl.ComCtrls, Vcl.Buttons, System.JSON, System.IOUtils, Data.DB,
  FireDAC.Comp.Client, FireDAC.Stan.Param, Vcl.Imaging.pngimage, Vcl.Imaging.jpeg;

type
  TItemCampoFicha = class
  public
    Clave: string;
    ValorExtraido: string;
    ValorActual: string;
    EsArticulo: Boolean;
  end;

  TfrmAnalisisImportacionFicha = class(TForm)
    pnlHeader: TPanel;
    lblTitulo: TLabel;
    lblSubtitulo: TLabel;
    pnlBottom: TPanel;
    lblResumen: TLabel;
    btnAceptar: TButton;
    btnCancelar: TButton;
    pnlClient: TPanel;
    pnlImagen: TPanel;
    lblTituloImagen: TLabel;
    pnlImgBox: TPanel;
    imgProducto: TImage;
    lblImagenInfo: TLabel;
    chkAplicarImagen: TCheckBox;
    btnBuscarOtraImagen: TButton;
    chkAdjuntarDoc: TCheckBox;
    lblDocAdjuntarInfo: TLabel;
    pnlGrid: TPanel;
    pnlGridToolbar: TPanel;
    btnSeleccionarTodo: TSpeedButton;
    btnDeseleccionarTodo: TSpeedButton;
    lblFiltroInfo: TLabel;
    lvCampos: TListView;
    odBuscarImagen: TOpenDialog;
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure btnSeleccionarTodoClick(Sender: TObject);
    procedure btnDeseleccionarTodoClick(Sender: TObject);
    procedure btnBuscarOtraImagenClick(Sender: TObject);
    procedure lvCamposItemChecked(Sender: TObject; Item: TListItem);
  private
    FJsonObj: TJSONObject;
    FImgPath: string;
    FDocPath: string;
    procedure AgregarFilaCampo(const AClave, ANombreVisible, AValorExtraido, AValorActual: string; AEsArticulo: Boolean);
    function ObtenerValorJson(const AKey: string): string;
    procedure ActualizarContadorResumen;
  public
    procedure InicializarConDatos(AArticuloEditor: TForm; const AJsonStr, ADocPath, AImgPath: string);
    procedure AplicarCambiosAlArticulo(AArticuloEditor: TForm);
    property ImgPath: string read FImgPath write FImgPath;
  end;

var
  frmAnalisisImportacionFicha: TfrmAnalisisImportacionFicha;

implementation

uses
  dmg_Main, frm_ArticulosEditor, frm_FichaTecnicaEditor;

{$R *.dfm}

procedure TfrmAnalisisImportacionFicha.FormCreate(Sender: TObject);
begin
  FJsonObj := nil;
  FImgPath := '';
  FDocPath := '';
end;

procedure TfrmAnalisisImportacionFicha.FormDestroy(Sender: TObject);
var
  i: Integer;
begin
  for i := 0 to lvCampos.Items.Count - 1 do
    if Assigned(lvCampos.Items[i].Data) then
      TObject(lvCampos.Items[i].Data).Free;
  lvCampos.Items.Clear;

  if Assigned(FJsonObj) then
    FreeAndNil(FJsonObj);
end;

function ParseFloatUniversal(const AStr: string): Double;
var
  LStr: string;
  LFS: TFormatSettings;
  LDotPos, LCommaPos: Integer;
begin
  Result := 0.0;
  LStr := Trim(AStr);
  if LStr = '' then Exit;
  LStr := StringReplace(LStr, ' ', '', [rfReplaceAll]);
  LDotPos := LastDelimiter('.', LStr);
  LCommaPos := LastDelimiter(',', LStr);
  if (LDotPos > 0) and (LCommaPos > 0) then
  begin
    if LDotPos > LCommaPos then
      LStr := StringReplace(LStr, ',', '', [rfReplaceAll])
    else
    begin
      LStr := StringReplace(LStr, '.', '', [rfReplaceAll]);
      LStr := StringReplace(LStr, ',', '.', [rfReplaceAll]);
    end;
  end
  else if LCommaPos > 0 then
    LStr := StringReplace(LStr, ',', '.', [rfReplaceAll]);

  LFS := TFormatSettings.Create('en-US');
  LFS.DecimalSeparator := '.';
  if not TryStrToFloat(LStr, Result, LFS) then
    Result := 0.0;
end;

function FormatearNumeroNutricional(const AStr: string): string;
var
  LVal: Double;
  LStr: string;
begin
  LStr := Trim(AStr);
  if (LStr = '') or (LStr = '0') or (LStr = '0.0') or (LStr = '0.00') then
  begin
    Result := '';
    Exit;
  end;
  LVal := ParseFloatUniversal(LStr);
  if LVal <> 0.0 then
    Result := FormatFloat('0.##', LVal)
  else
    Result := '';
end;

function GetFieldSafe(AQry: TFDQuery; const AFieldName: string): string;
var
  LField: TField;
  LVal: Double;
begin
  Result := '';
  if not Assigned(AQry) or not AQry.Active or AQry.IsEmpty then Exit;
  LField := AQry.FindField(AFieldName);
  if not Assigned(LField) then Exit;

  if LField.DataType in [ftFloat, ftCurrency, ftBCD, ftFMTBcd] then
  begin
    LVal := LField.AsFloat;
    if LVal <> 0.0 then
      Result := FormatFloat('0.##', LVal)
    else
      Result := '';
  end
  else
    Result := Trim(LField.AsString);
end;

function TfrmAnalisisImportacionFicha.ObtenerValorJson(const AKey: string): string;
var
  LVal: TJSONValue;
begin
  Result := '';
  if not Assigned(FJsonObj) then Exit;
  LVal := FJsonObj.FindValue(AKey);
  if Assigned(LVal) and not (LVal is TJSONNull) then
  begin
    Result := Trim(LVal.Value);
  end;
end;

procedure TfrmAnalisisImportacionFicha.AgregarFilaCampo(const AClave, ANombreVisible, AValorExtraido, AValorActual: string; AEsArticulo: Boolean);
var
  LItem: TListItem;
  LData: TItemCampoFicha;
  LEstado: string;
  LIsIdentical: Boolean;
  LValExtNum, LValActNum: Double;
begin
  if (Trim(AValorExtraido) = '') and (Trim(AValorActual) = '') then
    Exit;

  LItem := lvCampos.Items.Add;
  LItem.Caption := ANombreVisible;

  // SubItems[0] = Valor Extraído
  LItem.SubItems.Add(AValorExtraido);
  // SubItems[1] = Valor Actual
  LItem.SubItems.Add(AValorActual);

  // Determinar si los valores son idénticos numérica o textualmente
  if AClave.StartsWith('nutricional_') or (AClave = 'peso') then
  begin
    LValExtNum := ParseFloatUniversal(AValorExtraido);
    LValActNum := ParseFloatUniversal(AValorActual);
    LIsIdentical := SameValue(LValExtNum, LValActNum, 0.001);
  end
  else
    LIsIdentical := SameText(Trim(AValorExtraido), Trim(AValorActual));

  if Trim(AValorExtraido) = '' then
    LEstado := 'ℹ️ Sin datos'
  else if Trim(AValorActual) = '' then
    LEstado := '✅ Nuevo'
  else if LIsIdentical then
    LEstado := '✔ Idéntico'
  else
    LEstado := '🔄 Actualizar';

  // SubItems[2] = Estado
  LItem.SubItems.Add(LEstado);

  LData := TItemCampoFicha.Create;
  LData.Clave := AClave;
  LData.ValorExtraido := AValorExtraido;
  LData.ValorActual := AValorActual;
  LData.EsArticulo := AEsArticulo;
  LItem.Data := LData;

  // Marcar por defecto si hay valor extraído y no es idéntico
  LItem.Checked := (Trim(AValorExtraido) <> '') and not LIsIdentical;
end;

procedure TfrmAnalisisImportacionFicha.ActualizarContadorResumen;
var
  i, LCount: Integer;
begin
  LCount := 0;
  for i := 0 to lvCampos.Items.Count - 1 do
    if lvCampos.Items[i].Checked then
      Inc(LCount);

  lblResumen.Caption := Format('%d campos seleccionados listos para aplicar.', [LCount]);
  btnAceptar.Enabled := (LCount > 0) or (chkAplicarImagen.Checked and (FImgPath <> ''));
end;

procedure TfrmAnalisisImportacionFicha.lvCamposItemChecked(Sender: TObject; Item: TListItem);
begin
  ActualizarContadorResumen;
end;

procedure TfrmAnalisisImportacionFicha.btnSeleccionarTodoClick(Sender: TObject);
var
  i: Integer;
begin
  for i := 0 to lvCampos.Items.Count - 1 do
    lvCampos.Items[i].Checked := True;
  ActualizarContadorResumen;
end;

procedure TfrmAnalisisImportacionFicha.btnDeseleccionarTodoClick(Sender: TObject);
var
  i: Integer;
begin
  for i := 0 to lvCampos.Items.Count - 1 do
    lvCampos.Items[i].Checked := False;
  ActualizarContadorResumen;
end;

procedure TfrmAnalisisImportacionFicha.btnBuscarOtraImagenClick(Sender: TObject);
begin
  if odBuscarImagen.Execute then
  begin
    FImgPath := odBuscarImagen.FileName;
    try
      imgProducto.Picture.LoadFromFile(FImgPath);
      lblImagenInfo.Caption := 'Imagen seleccionada manualmente: ' + ExtractFileName(FImgPath);
      chkAplicarImagen.Checked := True;
      ActualizarContadorResumen;
    except
      on E: Exception do
        ShowMessage('Error al cargar la imagen seleccionada: ' + E.Message);
    end;
  end;
end;

procedure TfrmAnalisisImportacionFicha.InicializarConDatos(AArticuloEditor: TForm; const AJsonStr, ADocPath, AImgPath: string);
var
  LEditor: TfrmArticulosEditor;
  LArtId: string;
  QryFicha: TFDQuery;
  LValExt: string;
begin
  FDocPath := ADocPath;
  FImgPath := AImgPath;
  lblSubtitulo.Caption := 'Documento analizado: ' + ExtractFileName(ADocPath);

  if Assigned(FJsonObj) then FreeAndNil(FJsonObj);
  FJsonObj := TJSONObject.ParseJSONValue(AJsonStr) as TJSONObject;
  if not Assigned(FJsonObj) then
  begin
    ShowMessage('El resultado del análisis no contenía un JSON válido.');
    Exit;
  end;

  lvCampos.Items.BeginUpdate;
  try
    for var i := 0 to lvCampos.Items.Count - 1 do
      if Assigned(lvCampos.Items[i].Data) then
        TObject(lvCampos.Items[i].Data).Free;
    lvCampos.Items.Clear;

    LEditor := nil;
    LArtId := '';
    if AArticuloEditor is TfrmArticulosEditor then
    begin
      LEditor := TfrmArticulosEditor(AArticuloEditor);
      LArtId := LEditor.edtCodigo.Text;
    end;

    // 1. CAMPOS DE ARTÍCULO PRINCIPAL
    // Descripción
    LValExt := ObtenerValorJson('descripcion');
    AgregarFilaCampo('descripcion', 'Descripción / Nombre', LValExt, IfThen(Assigned(LEditor), LEditor.edtDescripcion.Text, ''), True);

    // Denominación Legal
    LValExt := ObtenerValorJson('denominacion_legal');
    AgregarFilaCampo('denominacion_legal', 'Denominación Legal', LValExt, IfThen(Assigned(LEditor), LEditor.redtDescripcionEtiqueta.Text, ''), True);

    // EAN
    LValExt := ObtenerValorJson('codigo_barras');
    AgregarFilaCampo('codigo_barras', 'Código de Barras / EAN', LValExt, IfThen(Assigned(LEditor), LEditor.edtEan.Text, ''), True);

    // Peso / Cantidad neta
    LValExt := ObtenerValorJson('peso');
    if (LValExt = '') or (LValExt = '0') or (LValExt = '0.00') then
      LValExt := ObtenerValorJson('cantidad_neta');
    AgregarFilaCampo('peso', 'Peso Neto / Cantidad', LValExt, IfThen(Assigned(LEditor), LEditor.edtPeso.Text, ''), True);

    // Días de vida
    LValExt := ObtenerValorJson('dias_vida');
    if (LValExt = '') or (LValExt = '0') then
      LValExt := ObtenerValorJson('vida_util');
    AgregarFilaCampo('dias_vida', 'Vida Útil / Días', LValExt, IfThen(Assigned(LEditor), LEditor.edtDiasVida.Text, ''), True);

    // Ingredientes
    LValExt := ObtenerValorJson('ingredientes');
    AgregarFilaCampo('ingredientes', 'Ingredientes', LValExt, IfThen(Assigned(LEditor), LEditor.redtIngredientes.Text, ''), True);

    // Alérgenos receta
    LValExt := ObtenerValorJson('alergenos_receta');
    AgregarFilaCampo('alergenos_receta', 'Alérgenos Receta (Contiene)', LValExt, '', True);

    // Alérgenos trazas
    LValExt := ObtenerValorJson('alergenos_trazas');
    AgregarFilaCampo('alergenos_trazas', 'Alérgenos Trazas (Puede contener)', LValExt, '', True);

    // 2. CONSULTAR DATOS ACTUALES DE FICHA TÉCNICA SI EL ARTÍCULO YA EXISTE
    QryFicha := TFDQuery.Create(nil);
    try
      QryFicha.Connection := dmgMain.dbConn;
      if (LArtId <> '') and (StrToIntDef(LArtId, 0) > 0) then
      begin
        QryFicha.SQL.Text := 'SELECT * FROM ge_articulos_fichas_tecnicas WHERE id_articulo = :id LIMIT 1';
        QryFicha.ParamByName('id').AsInteger := StrToIntDef(LArtId, 0);
        QryFicha.Open;
      end;

      // Código y versión de ficha
      AgregarFilaCampo('codigo_ficha', 'Código Ficha Técnica', ObtenerValorJson('codigo_ficha'), GetFieldSafe(QryFicha, 'codigo_ficha'), False);
      AgregarFilaCampo('revision', 'Revisión / Versión', ObtenerValorJson('revision'), GetFieldSafe(QryFicha, 'revision'), False);
      AgregarFilaCampo('fecha_aprobacion', 'Fecha Aprobación', ObtenerValorJson('fecha_aprobacion'), GetFieldSafe(QryFicha, 'fecha_aprobacion'), False);
      AgregarFilaCampo('elaborado_por', 'Elaborado por', ObtenerValorJson('elaborado_por'), GetFieldSafe(QryFicha, 'elaborado_por'), False);
      AgregarFilaCampo('aprobado_por', 'Aprobado por', ObtenerValorJson('aprobado_por'), GetFieldSafe(QryFicha, 'aprobado_por'), False);

      // Operador y registros sanitarios
      AgregarFilaCampo('razon_social_operador', 'Razón Social Operador', ObtenerValorJson('razon_social_operador'), GetFieldSafe(QryFicha, 'razon_social_operador'), False);
      AgregarFilaCampo('direccion_operador', 'Dirección Operador', ObtenerValorJson('direccion_operador'), GetFieldSafe(QryFicha, 'direccion_operador'), False);
      AgregarFilaCampo('rgseaa', 'RGSEAA / Registro Sanitario', ObtenerValorJson('rgseaa'), GetFieldSafe(QryFicha, 'rgseaa'), False);

      // Valores nutricionales por 100g (formateados con decimales limpios)
      AgregarFilaCampo('nutricional_energia_kj', 'Energía (kJ)', FormatearNumeroNutricional(ObtenerValorJson('nutricional_energia_kj')), GetFieldSafe(QryFicha, 'nutricional_energia_kj'), False);
      AgregarFilaCampo('nutricional_energia_kcal', 'Energía (kcal)', FormatearNumeroNutricional(ObtenerValorJson('nutricional_energia_kcal')), GetFieldSafe(QryFicha, 'nutricional_energia_kcal'), False);
      AgregarFilaCampo('nutricional_grasas', 'Grasas Totales (g)', FormatearNumeroNutricional(ObtenerValorJson('nutricional_grasas')), GetFieldSafe(QryFicha, 'nutricional_grasas'), False);
      AgregarFilaCampo('nutricional_grasas_saturadas', 'Grasas Saturadas (g)', FormatearNumeroNutricional(ObtenerValorJson('nutricional_grasas_saturadas')), GetFieldSafe(QryFicha, 'nutricional_grasas_saturadas'), False);
      AgregarFilaCampo('nutricional_hidratos', 'Hidratos de Carbono (g)', FormatearNumeroNutricional(ObtenerValorJson('nutricional_hidratos')), GetFieldSafe(QryFicha, 'nutricional_hidratos'), False);
      AgregarFilaCampo('nutricional_azucares', 'Azúcares (g)', FormatearNumeroNutricional(ObtenerValorJson('nutricional_azucares')), GetFieldSafe(QryFicha, 'nutricional_azucares'), False);
      AgregarFilaCampo('nutricional_fibra', 'Fibra Alimentaria (g)', FormatearNumeroNutricional(ObtenerValorJson('nutricional_fibra')), GetFieldSafe(QryFicha, 'nutricional_fibra'), False);
      AgregarFilaCampo('nutricional_proteinas', 'Proteínas (g)', FormatearNumeroNutricional(ObtenerValorJson('nutricional_proteinas')), GetFieldSafe(QryFicha, 'nutricional_proteinas'), False);
      AgregarFilaCampo('nutricional_sal', 'Sal (g)', FormatearNumeroNutricional(ObtenerValorJson('nutricional_sal')), GetFieldSafe(QryFicha, 'nutricional_sal'), False);

      // Parámetros Físico-Químicos
      AgregarFilaCampo('aw', 'Actividad de Agua (aW)', ObtenerValorJson('aw'), GetFieldSafe(QryFicha, 'aw'), False);
      AgregarFilaCampo('humedad', 'Humedad (%)', ObtenerValorJson('humedad'), GetFieldSafe(QryFicha, 'humedad'), False);
      AgregarFilaCampo('ph', 'pH', ObtenerValorJson('ph'), GetFieldSafe(QryFicha, 'ph'), False);

      // Parámetros Microbiológicos
      AgregarFilaCampo('micro_mohos', 'Mohos', ObtenerValorJson('micro_mohos'), GetFieldSafe(QryFicha, 'micro_mohos'), False);
      AgregarFilaCampo('micro_levaduras', 'Levaduras', ObtenerValorJson('micro_levaduras'), GetFieldSafe(QryFicha, 'micro_levaduras'), False);
      AgregarFilaCampo('micro_aerobios', 'Aerobios Mesófilos', ObtenerValorJson('micro_aerobios'), GetFieldSafe(QryFicha, 'micro_aerobios'), False);
      AgregarFilaCampo('micro_enterobacterias', 'Enterobacterias', ObtenerValorJson('micro_enterobacterias'), GetFieldSafe(QryFicha, 'micro_enterobacterias'), False);
      AgregarFilaCampo('micro_salmonella', 'Salmonella', ObtenerValorJson('micro_salmonella'), GetFieldSafe(QryFicha, 'micro_salmonella'), False);
      AgregarFilaCampo('micro_listeria', 'Listeria Monocytogenes', ObtenerValorJson('micro_listeria'), GetFieldSafe(QryFicha, 'micro_listeria'), False);
      AgregarFilaCampo('micro_ecoli', 'E. Coli', ObtenerValorJson('micro_ecoli'), GetFieldSafe(QryFicha, 'micro_ecoli'), False);

      // Organolépticas
      AgregarFilaCampo('organolepticas_aspecto', 'Aspecto / Color', ObtenerValorJson('organolepticas_aspecto'), GetFieldSafe(QryFicha, 'organolepticas_aspecto'), False);
      AgregarFilaCampo('organolepticas_olor', 'Olor / Aroma', ObtenerValorJson('organolepticas_olor'), GetFieldSafe(QryFicha, 'organolepticas_olor'), False);
      AgregarFilaCampo('organolepticas_textura', 'Textura', ObtenerValorJson('organolepticas_textura'), GetFieldSafe(QryFicha, 'organolepticas_textura'), False);

      // Conservación y uso
      AgregarFilaCampo('condiciones_almacenamiento', 'Condiciones Almacenamiento', ObtenerValorJson('condiciones_almacenamiento'), GetFieldSafe(QryFicha, 'condiciones_almacenamiento'), False);
      AgregarFilaCampo('instrucciones_uso', 'Instrucciones de Uso', ObtenerValorJson('instrucciones_uso'), GetFieldSafe(QryFicha, 'instrucciones_uso'), False);
      AgregarFilaCampo('publico_objetivo', 'Público Objetivo', ObtenerValorJson('publico_objetivo'), GetFieldSafe(QryFicha, 'publico_objetivo'), False);
      AgregarFilaCampo('grupos_vulnerables', 'Grupos Vulnerables', ObtenerValorJson('grupos_vulnerables'), GetFieldSafe(QryFicha, 'grupos_vulnerables'), False);
      AgregarFilaCampo('gestion_lotes', 'Gestión de Lotes', ObtenerValorJson('gestion_lotes'), GetFieldSafe(QryFicha, 'gestion_lotes'), False);
      AgregarFilaCampo('omg', 'Declaración OGM', ObtenerValorJson('omg'), GetFieldSafe(QryFicha, 'omg'), False);
    finally
      QryFicha.Free;
    end;
  finally
    lvCampos.Items.EndUpdate;
  end;

  // Cargar imagen extraída si existe
  imgProducto.Picture := nil;
  if (FImgPath <> '') and FileExists(FImgPath) then
  begin
    try
      imgProducto.Picture.LoadFromFile(FImgPath);
      lblImagenInfo.Caption := 'Fotografía del producto detectada en el documento (' + ExtractFileName(FImgPath) + ')';
      chkAplicarImagen.Enabled := True;
      chkAplicarImagen.Checked := True;
    except
      on E: Exception do
      begin
        lblImagenInfo.Caption := 'Error al visualizar imagen: ' + E.Message;
        chkAplicarImagen.Checked := False;
      end;
    end;
  end
  else
  begin
    lblImagenInfo.Caption := 'No se encontró fotografía del producto en el documento.';
    chkAplicarImagen.Checked := False;
    chkAplicarImagen.Enabled := False;
  end;

  // Configurar estado de adjuntar documento a Documentación del artículo
  if (FDocPath <> '') and FileExists(FDocPath) then
  begin
    chkAdjuntarDoc.Enabled := True;
    chkAdjuntarDoc.Checked := True;
    lblDocAdjuntarInfo.Caption := 'Documento: ' + ExtractFileName(FDocPath);
  end
  else
  begin
    chkAdjuntarDoc.Checked := False;
    chkAdjuntarDoc.Enabled := False;
    lblDocAdjuntarInfo.Caption := 'Sin documento original para adjuntar.';
  end;

  ActualizarContadorResumen;
end;

procedure TfrmAnalisisImportacionFicha.AplicarCambiosAlArticulo(AArticuloEditor: TForm);
var
  LEditor: TfrmArticulosEditor;
  LFichaEditor: TfrmFichaTecnicaEditor;
  i, LArtIdInt: Integer;
  LItem: TListItem;
  LData: TItemCampoFicha;
  LArtId: string;
  QryExec, QryAlg: TFDQuery;
  LSQLSet: string;
  LParamName: string;
  LStream: TMemoryStream;
  LFileName, LExtension: string;
  LAlergReceta, LAlergTrazas: string;
begin
  LEditor := nil;
  LFichaEditor := nil;
  LArtId := '';

  if AArticuloEditor is TfrmArticulosEditor then
  begin
    LEditor := TfrmArticulosEditor(AArticuloEditor);
    LArtId := Trim(LEditor.edtCodigo.Text);
  end
  else if AArticuloEditor is TfrmFichaTecnicaEditor then
  begin
    LFichaEditor := TfrmFichaTecnicaEditor(AArticuloEditor);
    LArtId := IntToStr(LFichaEditor.ArticuloId);
  end;

  LArtIdInt := StrToIntDef(LArtId, 0);

  // 1. ACTUALIZAR CAMPOS VISUALES DEL ARTÍCULO
  for i := 0 to lvCampos.Items.Count - 1 do
  begin
    LItem := lvCampos.Items[i];
    if not LItem.Checked then Continue;
    LData := TItemCampoFicha(LItem.Data);
    if LData = nil then Continue;

    if Assigned(LEditor) and LData.EsArticulo then
    begin
      if LData.Clave = 'descripcion' then
        LEditor.edtDescripcion.Text := LData.ValorExtraido
      else if LData.Clave = 'denominacion_legal' then
        LEditor.redtDescripcionEtiqueta.Text := LData.ValorExtraido
      else if LData.Clave = 'codigo_barras' then
        LEditor.edtEan.Text := LData.ValorExtraido
      else if LData.Clave = 'peso' then
        LEditor.edtPeso.Text := LData.ValorExtraido
      else if LData.Clave = 'dias_vida' then
        LEditor.edtDiasVida.Text := LData.ValorExtraido
      else if LData.Clave = 'ingredientes' then
        LEditor.redtIngredientes.Text := LData.ValorExtraido;
    end;
  end;

  // 2. ACTUALIZAR O INSERTAR FICHA TÉCNICA EN LA BASE DE DATOS
  if LArtIdInt > 0 then
  begin
    QryExec := TFDQuery.Create(nil);
    try
      QryExec.Connection := dmgMain.dbConn;

      // Comprobar si ya existe registro en ge_articulos_fichas_tecnicas
      QryExec.SQL.Text := 'SELECT id_ficha FROM ge_articulos_fichas_tecnicas WHERE id_articulo = :id LIMIT 1';
      QryExec.ParamByName('id').AsInteger := LArtIdInt;
      QryExec.Open;
      var LExiste := not QryExec.IsEmpty;
      QryExec.Close;

      if not LExiste then
      begin
        QryExec.SQL.Text := 'INSERT INTO ge_articulos_fichas_tecnicas (id_articulo) VALUES (:id)';
        QryExec.ParamByName('id').AsInteger := LArtIdInt;
        QryExec.ExecSQL;
      end;

      // Construir UPDATE dinámico con los campos que el usuario ha dejado marcados
      LSQLSet := '';
      for i := 0 to lvCampos.Items.Count - 1 do
      begin
        LItem := lvCampos.Items[i];
        if not LItem.Checked then Continue;
        LData := TItemCampoFicha(LItem.Data);
        if (LData = nil) or (LData.Clave = 'alergenos_receta') or (LData.Clave = 'alergenos_trazas') then Continue;

        // Omitir campos que no pertenecen a ge_articulos_fichas_tecnicas
        if (LData.Clave = 'peso') or (LData.Clave = 'dias_vida') or (LData.Clave = 'descripcion') then
          Continue;

        if LSQLSet <> '' then LSQLSet := LSQLSet + ', ';
        LSQLSet := LSQLSet + LData.Clave + ' = :' + LData.Clave;
      end;

      if LSQLSet <> '' then
      begin
        QryExec.SQL.Text := 'UPDATE ge_articulos_fichas_tecnicas SET ' + LSQLSet + ' WHERE id_articulo = :id_art';
        QryExec.ParamByName('id_art').AsInteger := LArtIdInt;

        for i := 0 to lvCampos.Items.Count - 1 do
        begin
          LItem := lvCampos.Items[i];
          if not LItem.Checked then Continue;
          LData := TItemCampoFicha(LItem.Data);
          if (LData = nil) or (LData.Clave = 'alergenos_receta') or (LData.Clave = 'alergenos_trazas') then Continue;
          if (LData.Clave = 'peso') or (LData.Clave = 'dias_vida') or (LData.Clave = 'descripcion') then Continue;

          LParamName := LData.Clave;
          if QryExec.FindParam(LParamName) <> nil then
          begin
            if LData.Clave.StartsWith('nutricional_') then
              QryExec.ParamByName(LParamName).AsFloat := ParseFloatUniversal(LData.ValorExtraido)
            else
              QryExec.ParamByName(LParamName).AsString := LData.ValorExtraido;
          end;
        end;

        QryExec.ExecSQL;
      end;

      // Si el editor de Ficha Técnica está abierto, reflejar los cambios en sus controles visuales
      if Assigned(LFichaEditor) then
      begin
        for i := 0 to lvCampos.Items.Count - 1 do
        begin
          LItem := lvCampos.Items[i];
          if not LItem.Checked then Continue;
          LData := TItemCampoFicha(LItem.Data);
          if LData = nil then Continue;

          if LData.Clave = 'nutricional_energia_kj' then
            LFichaEditor.edtEnergiaKj.Text := FormatFloat('#,##0.00', ParseFloatUniversal(LData.ValorExtraido))
          else if LData.Clave = 'nutricional_energia_kcal' then
            LFichaEditor.edtEnergiaKcal.Text := FormatFloat('#,##0.00', ParseFloatUniversal(LData.ValorExtraido))
          else if LData.Clave = 'nutricional_grasas' then
            LFichaEditor.edtGrasas.Text := FormatFloat('#,##0.00', ParseFloatUniversal(LData.ValorExtraido))
          else if LData.Clave = 'nutricional_grasas_saturadas' then
            LFichaEditor.edtGrasasSat.Text := FormatFloat('#,##0.00', ParseFloatUniversal(LData.ValorExtraido))
          else if LData.Clave = 'nutricional_hidratos' then
            LFichaEditor.edtHidratos.Text := FormatFloat('#,##0.00', ParseFloatUniversal(LData.ValorExtraido))
          else if LData.Clave = 'nutricional_azucares' then
            LFichaEditor.edtAzucares.Text := FormatFloat('#,##0.00', ParseFloatUniversal(LData.ValorExtraido))
          else if LData.Clave = 'nutricional_fibra' then
            LFichaEditor.edtFibra.Text := FormatFloat('#,##0.00', ParseFloatUniversal(LData.ValorExtraido))
          else if LData.Clave = 'nutricional_proteinas' then
            LFichaEditor.edtProteinas.Text := FormatFloat('#,##0.00', ParseFloatUniversal(LData.ValorExtraido))
          else if LData.Clave = 'nutricional_sal' then
            LFichaEditor.edtSal.Text := FormatFloat('#,##0.00', ParseFloatUniversal(LData.ValorExtraido))
          else if LData.Clave = 'codigo_ficha' then
            LFichaEditor.edtCodigoFicha.Text := LData.ValorExtraido
          else if LData.Clave = 'revision' then
            LFichaEditor.edtRevision.Text := LData.ValorExtraido
          else if LData.Clave = 'elaborado_por' then
            LFichaEditor.edtElaboradoPor.Text := LData.ValorExtraido
          else if LData.Clave = 'revisado_por' then
            LFichaEditor.edtRevisadoPor.Text := LData.ValorExtraido
          else if LData.Clave = 'aprobado_por' then
            LFichaEditor.edtAprobadoPor.Text := LData.ValorExtraido
          else if LData.Clave = 'razon_social_operador' then
            LFichaEditor.edtRazonSocial.Text := LData.ValorExtraido
          else if LData.Clave = 'direccion_operador' then
            LFichaEditor.edtDireccionOperador.Text := LData.ValorExtraido
          else if LData.Clave = 'rgseaa' then
            LFichaEditor.edtRgseaa.Text := LData.ValorExtraido
          else if LData.Clave = 'aw' then
            LFichaEditor.edtAw.Text := LData.ValorExtraido
          else if LData.Clave = 'aw_critica' then
            LFichaEditor.edtAwCritica.Text := LData.ValorExtraido
          else if LData.Clave = 'humedad' then
            LFichaEditor.edtHumedad.Text := LData.ValorExtraido
          else if LData.Clave = 'ph' then
            LFichaEditor.edtPh.Text := LData.ValorExtraido
          else if LData.Clave = 'micro_mohos' then
            LFichaEditor.edtMicroMohos.Text := LData.ValorExtraido
          else if LData.Clave = 'micro_levaduras' then
            LFichaEditor.edtMicroLevaduras.Text := LData.ValorExtraido
          else if LData.Clave = 'micro_aerobios' then
            LFichaEditor.edtMicroAerobios.Text := LData.ValorExtraido
          else if LData.Clave = 'micro_enterobacterias' then
            LFichaEditor.edtMicroEntero.Text := LData.ValorExtraido
          else if LData.Clave = 'micro_salmonella' then
            LFichaEditor.edtMicroSalmonella.Text := LData.ValorExtraido
          else if LData.Clave = 'micro_listeria' then
            LFichaEditor.edtMicroListeria.Text := LData.ValorExtraido
          else if LData.Clave = 'micro_ecoli' then
            LFichaEditor.edtMicroEcoli.Text := LData.ValorExtraido
          else if LData.Clave = 'organolepticas_aspecto' then
            LFichaEditor.memAspecto.Text := LData.ValorExtraido
          else if LData.Clave = 'organolepticas_olor' then
            LFichaEditor.memOlor.Text := LData.ValorExtraido
          else if LData.Clave = 'organolepticas_textura' then
            LFichaEditor.memTextura.Text := LData.ValorExtraido
          else if LData.Clave = 'instrucciones_uso' then
            LFichaEditor.memInstruccionesUso.Text := LData.ValorExtraido
          else if LData.Clave = 'publico_objetivo' then
            LFichaEditor.edtPublicoObjetivo.Text := LData.ValorExtraido
          else if LData.Clave = 'grupos_vulnerables' then
            LFichaEditor.memGruposVulnerables.Text := LData.ValorExtraido
          else if LData.Clave = 'cantidad_neta' then
            LFichaEditor.edtCantidadNeta.Text := LData.ValorExtraido
          else if LData.Clave = 'condiciones_almacenamiento' then
            LFichaEditor.memAlmacenamiento.Text := LData.ValorExtraido
          else if LData.Clave = 'vida_util' then
            LFichaEditor.edtVidaUtil.Text := LData.ValorExtraido
          else if LData.Clave = 'gestion_lotes' then
            LFichaEditor.memGestionLotes.Text := LData.ValorExtraido
          else if LData.Clave = 'condiciones_transporte' then
            LFichaEditor.memTransporte.Text := LData.ValorExtraido
          else if LData.Clave = 'mitigacion_cuerpos_extranos' then
            LFichaEditor.memCuerposExtranos.Text := LData.ValorExtraido
          else if LData.Clave = 'historico_cambios' then
            LFichaEditor.memHistoricoCambios.Text := LData.ValorExtraido;
        end;
      end;

      // 3. PROCESAR ALÉRGENOS SI SE MARCARON
      LAlergReceta := '';
      LAlergTrazas := '';
      for i := 0 to lvCampos.Items.Count - 1 do
      begin
        LItem := lvCampos.Items[i];
        if not LItem.Checked then Continue;
        LData := TItemCampoFicha(LItem.Data);
        if LData = nil then Continue;
        if LData.Clave = 'alergenos_receta' then LAlergReceta := LData.ValorExtraido
        else if LData.Clave = 'alergenos_trazas' then LAlergTrazas := LData.ValorExtraido;
      end;

      if (LAlergReceta <> '') or (LAlergTrazas <> '') then
      begin
        QryAlg := TFDQuery.Create(nil);
        try
          QryAlg.Connection := dmgMain.dbConn;
          QryAlg.SQL.Text := 'SELECT id, nombre FROM ge_alergenos';
          QryAlg.Open;
          while not QryAlg.Eof do
          begin
            var LAlgId := QryAlg.FieldByName('id').AsInteger;
            var LAlgNom := QryAlg.FieldByName('nombre').AsString;
            var LPresencia := '';

            // Buscar si coincide con receta o trazas
            if Pos(LowerCase(LAlgNom), LowerCase(LAlergReceta)) > 0 then
              LPresencia := 'Contiene'
            else if Pos(LowerCase(LAlgNom), LowerCase(LAlergTrazas)) > 0 then
              LPresencia := 'Trazas';

            if LPresencia <> '' then
            begin
              dmgMain.qryExec.Close;
              dmgMain.qryExec.SQL.Text :=
                'INSERT INTO ge_articulos_alergenos (id_articulo, id_alergeno, presencia, calculado_receta, id_user_creator, id_user_update) ' +
                'VALUES (:art, :alg, :pres, 0, :user, :user) ' +
                'ON DUPLICATE KEY UPDATE presencia = VALUES(presencia), id_user_update = VALUES(id_user_update)';
              dmgMain.qryExec.ParamByName('art').AsInteger := LArtIdInt;
              dmgMain.qryExec.ParamByName('alg').AsInteger := LAlgId;
              dmgMain.qryExec.ParamByName('pres').AsString := LPresencia;
              dmgMain.qryExec.ParamByName('user').AsString := dmgMain.CurrentUserId;
              dmgMain.qryExec.ExecSQL;
            end;

            QryAlg.Next;
          end;
        finally
          QryAlg.Free;
        end;

        // Si el editor de artículos está abierto, refrescar su grilla de alérgenos
        if Assigned(LEditor) and LEditor.qryAlergenos.Active then
        begin
          LEditor.qryAlergenos.Close;
          LEditor.qryAlergenos.ParamByName('id_articulo').AsString := LArtId;
          LEditor.qryAlergenos.Open;
        end;
      end;
    finally
      QryExec.Free;
    end;
  end;

  // 4. APLICAR IMAGEN DEL PRODUCTO
  if chkAplicarImagen.Checked and (FImgPath <> '') and FileExists(FImgPath) then
  begin
    if Assigned(LEditor) then
    begin
      try
        LEditor.imgProducto.Picture.LoadFromFile(FImgPath);
      except
        // Ignorar si el formato no es compatible directamente con TImage
      end;
    end;

    if LArtIdInt > 0 then
    begin
      LStream := TMemoryStream.Create;
      try
        LStream.LoadFromFile(FImgPath);
        LStream.Position := 0;

        LExtension := LowerCase(ExtractFileExt(FImgPath));
        if LExtension.StartsWith('.') then
          LExtension := Copy(LExtension, 2, MaxInt);

        QryExec := TFDQuery.Create(nil);
        try
          QryExec.Connection := dmgMain.dbConn;
          QryExec.SQL.Text := 'SELECT id FROM ge_documentos WHERE id_articulo = :id_art AND descripcion = ''IMAGEN_PRODUCTO'' LIMIT 1';
          QryExec.ParamByName('id_art').AsString := LArtId;
          QryExec.Open;

          if QryExec.IsEmpty then
          begin
            QryExec.Close;
            QryExec.SQL.Text :=
              'INSERT INTO ge_documentos (id_empresa, fecha, descripcion, archivo, nombre_archivo, extension, id_articulo, id_user_creator, id_user_update) ' +
              'VALUES (:id_empresa, :fecha, ''IMAGEN_PRODUCTO'', :archivo, :nombre_archivo, :extension, :id_articulo, :user, :user)';
            QryExec.ParamByName('id_empresa').AsString := dmgMain.CurrentCompanyId;
            QryExec.ParamByName('id_articulo').AsString := LArtId;
          end
          else
          begin
            LFileName := QryExec.FieldByName('id').AsString;
            QryExec.Close;
            QryExec.SQL.Text :=
              'UPDATE ge_documentos SET fecha = :fecha, archivo = :archivo, nombre_archivo = :nombre_archivo, ' +
              '  extension = :extension, id_user_update = :user, update_at = CURRENT_TIMESTAMP ' +
              'WHERE id = :id';
            QryExec.ParamByName('id').AsString := LFileName;
          end;

          QryExec.ParamByName('fecha').AsDate := Date;
          QryExec.ParamByName('archivo').LoadFromStream(LStream, ftBlob);
          QryExec.ParamByName('nombre_archivo').AsString := ExtractFileName(FImgPath);
          QryExec.ParamByName('extension').AsString := LExtension;
          QryExec.ParamByName('user').AsString := dmgMain.CurrentUserId;
          QryExec.ExecSQL;
        finally
          QryExec.Free;
        end;
      finally
        LStream.Free;
      end;
    end;
  end;

  // 5. AÑADIR FICHA TÉCNICA A LA DOCUMENTACIÓN DEL ARTÍCULO (ge_documentos)
  if chkAdjuntarDoc.Checked and (FDocPath <> '') and FileExists(FDocPath) and (LArtIdInt > 0) then
  begin
    var LDocFileName := ExtractFileName(FDocPath);
    var LDocExt := LowerCase(ExtractFileExt(FDocPath));
    if LDocExt.StartsWith('.') then
      LDocExt := Copy(LDocExt, 2, MaxInt);

    var LFileDocStream := TFileStream.Create(FDocPath, fmOpenRead or fmShareDenyNone);
    try
      LStream := TMemoryStream.Create;
      try
        LStream.CopyFrom(LFileDocStream, 0);
        LStream.Position := 0;

        QryExec := TFDQuery.Create(nil);
        try
          QryExec.Connection := dmgMain.dbConn;
          // Buscar si ya existe este archivo o un documento marcado como Ficha Técnica para este artículo
          QryExec.SQL.Text :=
            'SELECT id FROM ge_documentos ' +
            'WHERE id_articulo = :id_art AND (nombre_archivo = :nom OR descripcion = ''Ficha Técnica'') ' +
            'ORDER BY id DESC LIMIT 1';
          QryExec.ParamByName('id_art').AsString := LArtId;
          QryExec.ParamByName('nom').AsString := LDocFileName;
          QryExec.Open;

          if QryExec.IsEmpty then
          begin
            QryExec.Close;
            QryExec.SQL.Text :=
              'INSERT INTO ge_documentos (id_empresa, fecha, descripcion, archivo, nombre_archivo, extension, id_articulo, id_user_creator, id_user_update) ' +
              'VALUES (:id_empresa, :fecha, ''Ficha Técnica'', :archivo, :nombre_archivo, :extension, :id_articulo, :user, :user)';
            QryExec.ParamByName('id_empresa').AsString := dmgMain.CurrentCompanyId;
            QryExec.ParamByName('id_articulo').AsString := LArtId;
          end
          else
          begin
            var LDocIdExistente := QryExec.FieldByName('id').AsString;
            QryExec.Close;
            QryExec.SQL.Text :=
              'UPDATE ge_documentos SET ' +
              '  fecha = :fecha, ' +
              '  descripcion = ''Ficha Técnica'', ' +
              '  archivo = :archivo, ' +
              '  nombre_archivo = :nombre_archivo, ' +
              '  extension = :extension, ' +
              '  id_user_update = :user, ' +
              '  update_at = CURRENT_TIMESTAMP ' +
              'WHERE id = :id';
            QryExec.ParamByName('id').AsString := LDocIdExistente;
          end;

          QryExec.ParamByName('fecha').AsDate := Date;
          QryExec.ParamByName('archivo').LoadFromStream(LStream, ftBlob);
          QryExec.ParamByName('nombre_archivo').AsString := LDocFileName;
          QryExec.ParamByName('extension').AsString := LDocExt;
          QryExec.ParamByName('user').AsString := dmgMain.CurrentUserId;
          QryExec.ExecSQL;
        finally
          QryExec.Free;
        end;
      finally
        LStream.Free;
      end;
    finally
      LFileDocStream.Free;
    end;

    // Si el editor de artículos está abierto, recargar su pestaña de documentos
    if Assigned(LEditor) then
      LEditor.LoadDocuments;
  end;

  // Si se llamó desde el editor de fichas técnicas, refrescar sus datos
  if Assigned(LFichaEditor) then
  begin
    LFichaEditor.LoadData;
  end;
end;

end.
