Heray-Was-Here
Server : Apache
System : Linux mail.lomejor.cr 6.8.0-1059-azure #65~22.04.1-Ubuntu SMP Thu May 28 16:59:19 UTC 2026 x86_64
User : www-data ( 33)
PHP Version : 8.2.31
Disable Function : NONE
Directory :  /var/www/erp/htdocs/custom/crfact/class/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /var/www/erp/htdocs/custom/crfact/class/actions_crfact.class.php
<?php
/* Copyright (C) ---Put here your own copyright and developer email---
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

/**
 * \file    htdocs/modulebuilder/template/class/actions_mymodule.class.php
 * \ingroup mymodule
 * \brief   Example hook overload.
 *
 * Put detailed description here.
 */

use Beta\Microsoft\Graph\Model\UnitOfMeasure;

include_once( DOL_DOCUMENT_ROOT .'/custom/crfact/class/crfact.class.php');
require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';

define('ERROR_NO_VALID_USER', -300);
define('ERROR_USER_WRONG_LOGIN_INFO', -301);
define('ERROR_USER_NO_VALID_SESSION', -302);
define('ERROR_USER_ACCESS_DENIED', -303);
define('ERROR_USER_EXISTS', -304);
define('ERROR_DB_NO_RESULTS_FOUND', -200);
define('ERROR_BAD_REQUEST', "-1");

define('ERROR_CLAVE_REQUEST', -140);
define('ERROR_CONSULTAR_REQUEST', -150);
define('ERROR_FACTURADOR_REQUEST', -180);
define('ERROR_FACTURADORcompany_get_env_REQUEST', -181);
define('ERROR_FACTURADORget_credentials_REQUEST', -182);
define('ERROR_FACTURADORcompanny_add_voucher_REQUEST', -183);
define('ERROR_FILEUPLOADER_REQUEST', -190);
define('ERROR_GENXML_REQUEST', -191);
define('ERROR_SEND_REQUEST', -193);
define('ERROR_SIGNXML_REQUEST', -195);
define('ERROR_TOKEN_REQUEST', -196);
define('ERROR_MH_REQUEST', -201);
define('ERROR_MH_TIMEOUT', -202);
define('ERROR_MH_ERROR', -203);

/**
 * Class ActionsMyModule
 */
class ActionsCRFact
{
	/**
	 * @var DoliDB Database handler.
	 */
	public $db;

	/**
	 * @var string Error code (or message)
	 */
	public $error = '';

	/**
	 * @var array Errors
	 */
	public $errors = array();


	/**
	 * @var array Hook results. Propagated to $hookmanager->resArray for later reuse
	 */
	public $results = array();

	/**
	 * @var string String displayed by executeHook() immediately after return
	 */
	public $resprints;


	/**
	 * Constructor
	 *
	 *  @param		DoliDB		$db      Database handler
	 */
	public function __construct($db)
	{
		$this->db = $db;
	}


	/**
	 * Execute action
	 *
	 * @param	array			$parameters		Array of parameters
	 * @param	CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param	string			$action      	'add', 'update', 'view'
	 * @return	int         					<0 if KO,
	 *                           				=0 if OK but we want to process standard actions too,
	 *                            				>0 if OK and we want to replace standard actions.
	 */
	public function getNomUrl($parameters, &$object, &$action)
	{
		global $db, $langs, $conf, $user;
		$this->resprints = '';
		return 0;
	}

	/**
	 * Overloading the doActions function : replacing the parent's function with the one below
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
	 */
	public function doActions($parameters, &$object, &$action, $hookmanager)
	{
		global $conf, $user, $langs;

		$error = 0; // Error counter

		/* print_r($parameters); print_r($object); echo "action: " . $action; */
		if (in_array($parameters['currentcontext'], array('admincompany'))) {	    // do something only for the context 'somecontext1' or 'somecontext2'
			if ( $action == 'update' ){
				$id  = GETPOST("siren", 'alphanohtml');
				$curl = curl_init();
				curl_setopt_array($curl, array(
				CURLOPT_URL => "https://api.hacienda.go.cr/fe/ae?identificacion=".$id ,
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_ENCODING => "",
				CURLOPT_USERAGENT => 'Mozilla Chrome Safari',
				CURLOPT_MAXREDIRS => 10,
				CURLOPT_TIMEOUT => 0,
				CURLOPT_FOLLOWLOCATION => false,
				CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
				CURLOPT_CUSTOMREQUEST => "GET",
				));

				$responseMH = curl_exec($curl);
				$err = curl_error($curl);
				curl_close($curl);

				if ($err) {
					echo "cURL Error #:" . $err;
				} else {
					$response = json_decode($responseMH);
					$_POST["nom"] = $response->nombre;
					$_POST["forme_juridique_code"] = $response->tipoIdentificacion;
					foreach ($response->actividades as $Actividad => $linea) {
						if ( ($linea->estado == "A" ) ){
							$codigo = $linea->codigo;
							$descripcion = $linea->descripcion;
							$estado = $linea->estado;
							$sql = "SELECT codigo FROM ". MAIN_DB_PREFIX . "crfact_actividades WHERE codigo ='".$codigo."';";
							$resp = $this->db->query($sql);
							if ($resp){
								$num = $this->db->num_rows($resp);
								if ($num <= 0 ){
									$sql = "INSERT INTO  ". MAIN_DB_PREFIX . "crfact_actividades 
									( date_creation, codigo, descripcion, estado) VALUES
									(now(), '". $codigo ."','". $descripcion ."','". $estado."')";
									$resp = $this->db->query($sql);
								}
							}
							
						}
					}
					$_POST["MAIN_INFO_TVAINTRA"] = $codigo;
					$_POST["MAIN_INFO_PROFID6"] = $codigo;
					dolibarr_set_const($this->db, "MAIN_INFO_ACCOUNTANT_CODE", $codigo, 'chaine', 0, '', $conf->entity);
				}
			}
		}
		if (in_array($parameters['currentcontext'], array('invoicecard'))) {	    // do something only for the context 'somecontext1' or 'somecontext2'
			if ($action == 'confirm_modif' ){
				if ( strlen(trim($object->array_options['options_crlibre_clave']) ) > 0 ){
					setEventMessages($langs->trans("NOsepuedemodificarunaFacturaEnviadaHacienda"), null, 'errors');
					return 1;
				}else{
					return 0;
				}
			}elseif ($action == 'confirm_delete' ){
				if ( strlen(trim($object->array_options['options_crlibre_clave']) ) > 0){
					setEventMessages($langs->trans("NOsepuedemodificarunaFacturaEnviadaHacienda"), null, 'errors');
					return 1;
				}else{
					return 0;
				}
			}
		}
		if (in_array($parameters['currentcontext'], array('invoicesuppliercard'))) {	    // do something only for the context 'somecontext1' or 'somecontext2'
			if ($action == 'confirm_modif' ){
				if ( strlen(trim($object->array_options['options_crlibreconfirm']) ) > 0 ){
					setEventMessages($langs->trans("NOsepuedemodificarunaFacturaEnviadaHacienda"), null, 'errors');
					return 1;
				}else{
					return 0;
				}
			}elseif ($action == 'confirm_delete' ){
				if ( strlen(trim($object->array_options['options_crlibreconfirm']) ) > 0){
					setEventMessages($langs->trans("NOsepuedemodificarunaFacturaEnviadaHacienda"), null, 'errors');
					return 1;
				}else{
					return 0;
				}
			}elseif ($action == 'mh_accept' ){
				
				if ( ( strlen(trim($object->array_options['options_crlibre_clave']) ) > 0) && ( strlen(trim($object->array_options['options_crlibre_claveconfirm']) ) == 0)  ){
					$CRFact = new crfact($this->db);
					$clave = $object->array_options['options_crlibre_clave'];
					$fecha_emision = str_replace(" ","T",date('Y-m-d H:i:s'));
					$emi_tipoIdentificacion = str_pad( $object->thirdparty->forme_juridique_code,2,"0", STR_PAD_LEFT);
					$emi_numeroIdentificacion = $object->thirdparty->idprof1;
					$recp_tipoIdentificacion = str_pad( $conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE,2,"0", STR_PAD_LEFT);
					$recp_numeroIdentificacion = $conf->global->MAIN_INFO_SIREN;
					$tipoDocumento = GETPOST('idtipoaceptacion', 'int');
					$consecutivo = str_pad($object->id, 10, "0", STR_PAD_LEFT);
					$numero_consecutivo_receptor = $conf->global->CRFACT_IDSUCURSAL . $conf->global->CRFACT_IDTERMINAL . $tipoDocumento .$consecutivo;
					
					if ( $tipoDocumento == '05') {
						$tipoDoc = "CCE";
						$mensaje = '1';
					} else if ( $tipoDocumento == '06') {
						$tipoDoc = "CPCE";
						$mensaje = '2';
					} else if ( $tipoDocumento == '07') {
						$tipoDoc = "RCE";
						$mensaje = '3';
					}

					$crfactparam = array(
						'userName' => $conf->global->CRFACT_IDENDUSR,
						'pwd' => $conf->global->CRFACT_IDENDPWD,
						'idMasterUser' => $conf->global->CRFACT_MASTERID
					);
					setEventMessages($langs->trans("Conectando al API de Facturacion..."), null);
					$response = $CRFact->Request('facturador','companny_users_logMeIn',$crfactparam,$conf->global->CRFACT_URL);

					if ( $response->resp == ERROR_USER_WRONG_LOGIN_INFO ){
						setEventMessages($langs->trans("ERROR_USER_WRONG_LOGIN_INFO"), null, 'errors');
						dol_syslog("Trigger for action '$action' launched. companny_users_logMeIn=".$response);
						return ERROR_USER_WRONG_LOGIN_INFO;
					}else{
						$userName = $response->resp->userName;
						$sessionKey = $response->resp->sessionKey;
                    	
						$crfactparam = array(
							'clave' => $clave ,
							'codigo_actividad' => empty($object->thirdparty->idprof6) ? $object->thirdparty->tva_intra : $object->thirdparty->idprof6  ,
							'numero_cedula_emisor' => $emi_tipoIdentificacion.$emi_numeroIdentificacion,
							'fecha_emision_doc'	=> $fecha_emision,
							'mensaje' => $mensaje,
							'detalle_mensaje' => GETPOST('txtdetalle', 'alphanohtml'),
							'monto_total_impuesto' => $object->total_tva,
							'total_factura' =>$object->total_ttc,
							'numero_cedula_receptor' => $recp_tipoIdentificacion.$recp_numeroIdentificacion,
							'numero_consecutivo_receptor' => $numero_consecutivo_receptor
						);
						setEventMessages($langs->trans("Conectando al API de Facturacion..."), null);
						$response = $CRFact->Request('genXML','gen_xml_mr',$crfactparam,$conf->global->CRFACT_URL);
                    
						if ( !empty($response->resp->xml)) {	
							$xml = $response->resp->xml;
							$crfactparam = array(
								'iam' => $userName,
								'sessionKey' => $sessionKey,
								'idMasterUser' => $conf->global->CRFACT_MASTERID
							);
							setEventMessages($langs->trans("Adquiriendo paramentros del ambiente..."), null);
							$response = $CRFact->Request('facturador','company_get_env',$crfactparam,$conf->global->CRFACT_URL);

							if ( is_null($response->resp) ){
								setEventMessages($langs->trans("ERROR_FACTURADORcompany_get_env_REQUEST"), null, 'errors');
								dol_syslog("Trigger for action '$action' launched. company_get_env=".$response);
								return ERROR_FACTURADORcompany_get_env_REQUEST;
							}else{
								if ($response->resp[0]->env === "api-stag") {
									$client_id = "api-stag";
								} else if ($response->resp[0]->env === "api-prod") {
									$client_id = "api-prod";
								}
								if ($client_id == 'api-stag') {
									$r = 'get_stag_companny_credentials';
								} else if ($client_id == 'api-prod') {
									$r = 'get_prod_companny_credentials';
								}
								$crfactparam = array(
									'iam' => $userName,
									'sessionKey' => $sessionKey,
									'idMasterUser' => $conf->global->CRFACT_MASTERID
								);
								setEventMessages($langs->trans("Configurando paramentros del ambiente..."), null);
								$response = $CRFact->Request('facturador',$r,$crfactparam,$conf->global->CRFACT_URL);

								if ( is_null($response->resp) ){
									setEventMessages($langs->trans("'$r'"), null, 'errors');
									dol_syslog("Trigger for action '$action' launched. '$r'=".$response);
									return ERROR_FACTURADORget_credentials_REQUEST;
								}else{
									$usuario = $response->resp[0]->value;
									$pass = $response->resp[1]->value;
									$p12Code = $response->resp[2]->value;
									$pin = $response->resp[3]->value;
									$crfactparam = array(
										'username' => $usuario,
										'password' => $pass,
										'client_id' => $client_id,
										'grant_type' => 'password'
									);
									setEventMessages($langs->trans("Adquiriendo token del acceso MH..."), null);
									$response = $CRFact->Request('token','gettoken',$crfactparam,$conf->global->CRFACT_URL);
									
									if ( is_null($response->resp) ){
                                    
										setEventMessages($langs->trans("ERROR_TOKEN_REQUEST".json_encode($response)), null, 'errors');
										dol_syslog("Trigger for action '$action' launched. gettoken=".json_encode($response));
										return ERROR_TOKEN_REQUEST;
									}else{
										$token = $response->resp->access_token;
										$crfactparam = array(
											'p12Url' => $p12Code,
											'pinP12' => $pin,
											'inXml' => $xml,
											'tipodoc' => $tipoDoc
										);
										setEventMessages($langs->trans("Firmando XML Respuesta..."), null);
										$response = $CRFact->Request('signXML','signFE',$crfactparam,$conf->global->CRFACT_URL);
										
										if ( $response->resp == ERROR_USER_WRONG_LOGIN_INFO ){
											setEventMessages($langs->trans("ERROR_SIGNXML_REQUEST"), null, 'errors');
											dol_syslog("Trigger for action '$action' launched. signFE=".$response);
											return ERROR_SIGNXML_REQUEST;
										}else{
											$xmlFirmado = $response->resp->xmlFirmado;
											$crfactparam = array(
												'token' => $token,
												'clave' => $clave,
												'fecha' => $fecha_emision,
												'emi_tipoIdentificacion' => str_pad( $conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE,2,"0", STR_PAD_LEFT),
												'emi_numeroIdentificacion' => $conf->global->MAIN_INFO_SIREN,
												'recp_tipoIdentificacion' => str_pad( $object->forme_juridique_code,2,"0", STR_PAD_LEFT),
												'recp_numeroIdentificacion' => $object->thirdparty->idprof1,
												'client_id' => $client_id,
												'consecutivoReceptor' => $numero_consecutivo_receptor,
												'comprobanteXml' => $xmlFirmado,
											);
											setEventMessages($langs->trans("Enviando XML factura..."), null);
											$response = $CRFact->Request('send','sendMensaje',$crfactparam,$conf->global->CRFACT_URL);
											if ($response->resp->Status == 202) {
												setEventMessages($langs->trans("Actualizando comprobantes..."), null);
												$crfactparam = array(
													'idMasterUser' => $conf->global->CRFACT_MASTERID,
													'tipoDocumento' => $tipoDoc,
													'env' => $client_id
												);
												$response = $CRFact->Request('facturador','companny_updateConsecutive',$crfactparam,$conf->global->CRFACT_URL);
												if ( $response->resp == ERROR_USER_WRONG_LOGIN_INFO ){
													setEventMessages($langs->trans("ERROR_FACTURADORcompanny_add_voucher_REQUEST"), null, 'errors');
													dol_syslog("Trigger for action '$action' launched. companny_add_voucher=".$response);
													return ERROR_FACTURADORcompanny_add_voucher_REQUEST;
												}else{
													$object->array_options['options_crlibre_detalle'] =  GETPOST('txtdetalle', 'alphanohtml');
													$object->updateExtraField('crlibre_detalle');
													$object->array_options['options_crlibreconfirm'] =  $tipoDoc;
													$object->updateExtraField('crlibreconfirm');
													$object->array_options['options_crlibre_claveconfirm'] =  $clave;
													$object->updateExtraField('crlibre_claveconfirm');
													$objectref = dol_sanitizeFileName($object->ref);
													$objectrefsupplier = dol_sanitizeFileName($object->ref_supplier);
													$dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$objectref;
													$file = $dir."/".$clave.'.xml';
													if (!empty($conf->global->SUPPLIER_REF_IN_NAME)) {
														$file = $dir."/".($objectrefsupplier ? "_".$objectrefsupplier : "").$clave.'.xml';
													}

													if (!file_exists($dir)) {
														if (dol_mkdir($dir) < 0) {
															setEventMessages('Error en el registro de los documentos, no se pudo agregar el directorio' , null, 'errors');
															return -1 ;
														}
													}
													if (file_exists($dir)) {
                                                    	$text = mb_convert_encoding(base64_decode($xmlFirmado), 'UTF-8', 'auto');
														$result = file_put_contents($file, $text, FILE_APPEND | LOCK_EX);
														if (!empty($conf->global->MAIN_UMASK)) {
															@chmod($file, octdec($conf->global->MAIN_UMASK));
														}
														if ($result ===false){
															setEventMessages('Error en el registro de los documentos' , null, 'errors');
															return -1 ;
														}
													}
													$destfull =$file;
													$rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
													
													include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
													$ecmfile = new EcmFiles($this->db);
													$result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$file);

													if ($result > 0) {
														$ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
														$ecmfile->fullpath_orig = '';
														$ecmfile->gen_or_uploaded = 'uploaded';
														$ecmfile->description = ''; // indexed content
														$ecmfile->keywords = ''; // keyword content
														$result = $ecmfile->update($user);
														if ($result < 0) {
															setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
															return -1 ;
														}
													} else {
														$ecmfile->entity = $conf->entity;
														$ecmfile->filepath = $rel_dir;
														$ecmfile->filename = $file;
														$ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
														$ecmfile->fullpath_orig = '';
														$ecmfile->gen_or_uploaded = 'uploaded';
														$ecmfile->description = ''; // indexed content
														$ecmfile->keywords = ''; // keyword content
														$ecmfile->src_object_type = $object->table_element;	// $this->table_name is 'myobject' or 'mymodule_myobject'.
														$ecmfile->src_object_id   = $object->id;

														$result = $ecmfile->create($user);
														if ($result < 0) {
															setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
															return -1 ;
														}else{
															$sql = 'UPDATE '.MAIN_DB_PREFIX.$object->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath.'/'.$ecmfile->filename)."'";
															$sql .= ' WHERE rowid = '.$object->id;

															$resql = $this->db->query($sql);
															if (!$resql) {
																setEventMessages('Error en la actualizacion de last document', 'warnings');
																dol_print_error($this->db);
																return -1 ;
															} else {
																$object->last_main_doc = $ecmfile->filename;
															}
														}
													}

												}
											}else{
												$mhmensaje = json_encode($response);
												setEventMessages($mhmensaje, null, 'errors');
												dol_syslog("Trigger for action '$action' launched. consultarCom=".$mhmensaje);
												return ERROR_CONSULTAR_REQUEST;
											}
										}
									}
								}
							}
						}else{
							setEventMessages('Error en los datos enviados.'  , null, 'errors');
							return -1 ;
						}
					}	
					return -1;
				}else{
					setEventMessages('La confirmacion ya fue enviada.'  , null, 'errors');
					return -1 ;
				}
			
            }elseif ($action == 'loadxml' ){
				if ( empty($object->array_options['options_crlibreconfirm'])){
					
					$xmldata = GETPOST('filename_content', 'alpha');

					if (empty($xmldata)){
						setEventMessages('No se cargo el contenido del archivo.' , null, 'errors');
						return -1 ;
					}
					try { 
						$comprobante = new SimpleXMLElement(base64_decode($xmldata));
					} catch (Exception $e) {
						setEventMessages( json_encode($e) , null, 'errors');
						return -1 ;
					}
						
					if (($comprobante->getName() === 'FacturaElectronica') || ($comprobante->getName() === 'TiqueteElectronico')){
						$sql = "SELECT fk_object rowid from ". MAIN_DB_PREFIX . "facture_fourn_extrafields where 
						crlibre_clave = '". $comprobante->Clave ."' ;";
						$rs = $this->db->query($sql);
						$valrs = $this->db->fetch_object($rs);

						if (!is_null($valrs)){
							setEventMessages('El documento '.$comprobante->Clave.' ya fue importado' , null, 'errors');
							return -1 ;
						}
						
						if ( $comprobante->Receptor->Identificacion->Numero != $conf->global->MAIN_INFO_SIREN ){
							setEventMessages('El documento '.$comprobante->Clave.' no corresponde a esta empresa' , null, 'errors');
							return -1 ;
						}
						$thirdpartystatic = new Societe($this->db);
						if (strlen($comprobante->Emisor->NombreComercial) > 0 )
							$thirdpartystatic->name = (string) $comprobante->Emisor->NombreComercial;
						else
							$thirdpartystatic->name = (string)  $comprobante->Emisor->Nombre ;
						
						$thirdpartystatic->name_alias =(string)  $comprobante->Emisor->Nombre;

						$sql = "SELECT id, code from ". MAIN_DB_PREFIX . "c_typent where code = '".$comprobante->Emisor->Identificacion->Tipo."';";
						$resp = $this->db->query($sql);

						$typent = $this->db->fetch_object($resp);
						$thirdpartystatic->typent_code= (int) $typent->code;
						//$thirdpartystatic->typent_id = $typent->id;
						$thirdpartystatic->pays = 75;
						$thirdpartystatic->country = 'Costa Rica';
						$thirdpartystatic->country_code = 'CR';
						$thirdpartystatic->country_id = 75;
						$thirdpartystatic->multicurrency_code = (string) $comprobante->ResumenFactura->CodigoTipoMoneda->CodigoMoneda;
						$thirdpartystatic->forme_juridique_code =strval((intval($comprobante->Emisor->Identificacion->Tipo)));
						$thirdpartystatic->tva_intra = (string)$comprobante->CodigoActividad;
						$thirdpartystatic->idprof1 = (string) $comprobante->Emisor->Identificacion->Numero;
						$thirdpartystatic->idprof6 = (string) $comprobante->CodigoActividad;
						$thirdpartystatic->zip = (string) $comprobante->Emisor->Ubicacion->Provincia.$comprobante->Emisor->Ubicacion->Canton.$comprobante->Emisor->Ubicacion->Distrito.$comprobante->Emisor->Ubicacion->Barrio;
						$sql = "SELECT rowid, nom from ". MAIN_DB_PREFIX . "c_departements where code_departement = ".$comprobante->Emisor->Ubicacion->Provincia.";";
						$resp = $this->db->query($sql);
						$town = $this->db->fetch_object($resp);
						$thirdpartystatic->town = (string) $town->nom;
						$thirdpartystatic->address = (string) $comprobante->Emisor->Ubicacion->OtrasSenas;
						$thirdpartystatic->phone = (string) $comprobante->Emisor->Telefono->CodigoPais.$comprobante->Emisor->Telefono->NumTelefono;
						$thirdpartystatic->fax = (string) $comprobante->Emisor->Fax->CodigoPais.$comprobante->Emisor->Fax->NumTelefono;
						$thirdpartystatic->email =(string)  $comprobante->Emisor->CorreoElectronico;
						$thirdpartystatic->code_fournisseur = 'auto';
						$thirdpartystatic->fournisseur = 1;
						$thirdpartystatic->note_public = 'Importado por el Colector de email '. date('d-m-Y').'.';

						$thirdpartycontact = new Contact($this->db);
						$thirdpartycontact->entity = $conf->entity;
						if ( strlen($comprobante->Emisor->Nombre) >50){
							$thirdpartycontact->firstname = substr($comprobante->Emisor->Nombre,0,50);
							$thirdpartycontact->lastname = substr($comprobante->Emisor->Nombre,51,100);
						}else{
							$thirdpartycontact->firstname = (string) $comprobante->Emisor->Nombre;
						}
						$thirdpartycontact->address = (string) $comprobante->Emisor->Ubicacion->OtrasSenas;
						$thirdpartycontact->zip = (string) $comprobante->Emisor->Ubicacion->Provincia.$comprobante->Emisor->Ubicacion->Canton.$comprobante->Emisor->Ubicacion->Distrito.$comprobante->Emisor->Ubicacion->Barrio;
						$thirdpartycontact->town = (string) $town->nom;
						$thirdpartycontact->state_id = (string) $town->rowid;
						$thirdpartycontact->phone_pro =(string)$comprobante->Emisor->Telefono->CodigoPais.$comprobante->Emisor->Telefono->NumTelefono;
						$thirdpartycontact->email = $parameters["from"];
						$thirdpartycontact->priv = 0;
						$thirdpartycontact->note_public = 'Importado por el Colector de email '. date('d-m-Y').'.';


						$sql = "SELECT rowid, code_client, client from ". MAIN_DB_PREFIX . "societe where 
						idprof4 = '".$comprobante->Emisor->Identificacion->Numero."'
						or idprof5 = '".$comprobante->Emisor->Identificacion->Numero."'
						or siren = '".$comprobante->Emisor->Identificacion->Numero."'
						or siret = '".$comprobante->Emisor->Identificacion->Numero."' ;";
						$rs = $this->db->query($sql);

						$thirdpartyrs = $this->db->fetch_object($rs);
						if ( is_null( $thirdpartyrs) ) {
							
							$thirdpartyid = $thirdpartystatic->create($user);
							if ($thirdpartyid >= 0) {
								//Crea contacto de facturacion electronica.
								$thirdpartycontact->socid = $thirdpartyid;
								$thirdpartycontactid = $thirdpartycontact->create($user);
							}else{
								setEventMessages('1. Error en el registro del proveedor '.json_encode($thirdpartystatic->errors) , null, 'errors');
								return -1 ;
							}
						}else{
							$thirdpartystatic->code_client = $thirdpartyrs->code_client;
							$thirdpartystatic->client = $thirdpartyrs->client;
							$thirdpartyid = $thirdpartystatic->update($thirdpartyrs->rowid, $user, 0,0,0,'update');
							if ( $thirdpartyid >=0 ){
								//$resultc = $thirdpartycontact->fetch($comprobante->Emisor->CorreoElectronico);
								$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "socpeople where 
								email = '". $parameters["from"] ."' ;";
								$rs = $this->db->query($sql);
								$contactrs = $this->db->fetch_object($rs);
								if ( is_null($contactrs)) {
									//Crea contacto de facturacion electronica.
									$thirdpartycontact->socid = $thirdpartyrs->rowid;
									$thirdpartycontactid = $thirdpartycontact->create($user);
								}else{
									$thirdpartycontactid = $thirdpartycontact->update($contactrs->rowid, $user,0,'update');
								}
							}else{
								setEventMessages('Error en la actualizacion del contacto del proveedor '. json_encode($thirdpartystatic->errors) , null, 'errors');
								return -1 ;
							}
							$thirdpartyid = $thirdpartyrs->rowid;
						}
						
						if ($thirdpartycontactid <= 0){
							setEventMessages('Error en el registro del contacto del proveedor '.$thirdpartycontact->error  , null, 'errors');
							return -1 ;
						}
						
						if (is_null($ffrs)){
							$invoice = new FactureFournisseur($this->db);
							$dateinvoice = dol_mktime(12, 0, 0, date('m'), date('d'), date('Y'));
							$invoice->socid = $thirdpartyid;
							$emision = new DateTime( str_replace("T"," ",$comprobante->FechaEmision));

							$invoice->date = dol_mktime(12, 0, 0, $emision->format('m'), $emision->format('d'), $emision->format('Y'));
							
							if ($comprobante->PlazoCredito > 0 ){
								$emision->modify('+'.$comprobante->PlazoCredito.' day') ;
								$invoice->date_echeance = $emision->format('Y-m-d');
							}

							$invoice->date_pointoftax = $invoice->date ;
							$invoice->note_public = 'Importado por el Colector de email '. date('d-m-Y').'.';
							// We do not copy the private note
							$invoice->ref_supplier	= $comprobante->NumeroConsecutivo;
							
							$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "c_payment_term where code = '". str_pad( $comprobante->CondicionVenta,2,"0", STR_PAD_LEFT) ."';";
							$resp = $this->db->query($sql);
							$payterm = $this->db->fetch_object($resp);
							$invoice->cond_reglement_id	= $payterm->rowid;
							
							$sql = "SELECT id from ". MAIN_DB_PREFIX . "c_paiement where code = '". str_pad( $comprobante->MedioPago,2,"0", STR_PAD_LEFT) ."';";
							$resp = $this->db->query($sql);
							$pay = $this->db->fetch_object($resp);
							$invoice->mode_reglement_id	= $pay->id;
							
							
							if (!empty($comprobante->ResumenFactura->CodigoTipoMoneda->CodigoMoneda[0]) ){
								$invoice->multicurrency_code = (string)  $comprobante->ResumenFactura->CodigoTipoMoneda->CodigoMoneda[0];
							}else{
								$invoice->multicurrency_code ='CRC';
							}
							
							if ( $comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio >0){
                                //$invoice->multicurrency_tx = 1/floatval($comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio);
                                list($fk_multicurrency, $multicurrency_tx) = MultiCurrency::getIdAndTxFromCode( $this->db, $invoice->multicurrency_code, $dateinvoice);
                            	$invoice->multicurrency_tx = $multicurrency_tx;
                            }
							
							if ($invoice->multicurrency_code == $conf->global->MAIN_MONNAIE){
								$invoice->tva = $comprobante->ResumenFactura->TotalImpuesto;
								$invoice->total_tva = $comprobante->ResumenFactura->TotalImpuesto;
								$invoice->total_ht = $comprobante->ResumenFactura->TotalVentaNeta;
								$invoice->total_ttc = $comprobante->ResumenFactura->TotalComprobante;
								$invoice->remise = $comprobante->ResumenFactura->TotalDescuentos;
							}else{
								
								$invoice->tva = $comprobante->ResumenFactura->TotalImpuesto / $invoice->multicurrency_tx;
								$invoice->total_tva = $comprobante->ResumenFactura->TotalImpuesto / $invoice->multicurrency_tx;
								$invoice->total_ht = $comprobante->ResumenFactura->TotalVentaNeta / $invoice->multicurrency_tx;
								$invoice->total_ttc = $comprobante->ResumenFactura->TotalComprobante / $invoice->multicurrency_tx;
								$invoice->remise = $comprobante->ResumenFactura->TotalDescuentos / $invoice->multicurrency_tx;
                            	$invoice->fk_multicurrency = $fk_multicurrency;
								$invoice->multicurrency_total_tva = $comprobante->ResumenFactura->TotalImpuesto;
								$invoice->multicurrency_total_ht = $comprobante->ResumenFactura->TotalVentaNeta;
								$invoice->multicurrency_total_ttc = $comprobante->ResumenFactura->TotalComprobante;
							}
							$invoice->statut == FactureFournisseur::STATUS_DRAFT;
							
							if ($invoice->multicurrency_code == $conf->global->MAIN_MONNAIE){
								$invoice->libelle = 'Importado por el Colector de email '. date('d-m-Y').'.';
							}else{
								$invoice->libelle = 'Importado por el Colector de email '. date('d-m-Y').'. Modena original del documento {'.$comprobante->ResumenFactura->CodigoTipoMoneda->CodigoMoneda.'}-Tipo de Cambio ['.$invoice->multicurrency_tx.'].';
							}
							// Proprietes particulieres a facture avoir
							$invoice->type = FactureFournisseur::TYPE_STANDARD;
						
							$invoiceid = $invoice->create($user);
							
							if ($invoiceid < 0) {
								setEventMessages('Error en la creacion de la factura'.$invoice->error  , null, 'errors');
								return -1 ;
							} else {
								
								$invoice->array_options = array(
									'options_crlibre_clave' => (string) $comprobante->Clave
								);
								$invoice->updateExtraField('crlibre_clave');
								// copy internal contacts
								if ($invoice->copy_linked_contact($thirdpartystatic, 'internal') < 0) {
									$error++;
								} elseif ($object->socid == $invoice->socid) {
									// copy external contacts if same company
									if ($invoice->copy_linked_contact($thirdpartystatic, 'external') < 0) {
										$error++;
									}
								}
							}
							//Create details
							$Product = new Product($this->db);
							
							foreach ($comprobante->DetalleServicio->LineaDetalle as $LineaDetalle => $item) {
								if (!isset($item->Codigo) ){
									setEventMessages('Error en los datos de la factura, no posee codigo de producto CaByS', null, 'errors');
									return -1 ;
								}
								//Crea/Actualiza el producto 
								if ( intval( substr($item->Codigo,0,1)) <= 4 ){
									//Producto
									$Product->type  =  Product::TYPE_PRODUCT;
								}else{
									//Servicio
									$Product->type  =  Product::TYPE_SERVICE;
								}
								$Product->note = $item->Codigo;
								if (is_null($item->CodigoComercial->Codigo)){
									$Product->ref = $item->Codigo;
								}else{
									$Product->ref = $item->CodigoComercial->Codigo;
								}

								$Product->description = $item->Detalle;
								$Product->label = $item->Detalle;
								$Product->note_private   = 'Creado apartir de la factura '.$comprobante->clave;
								$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "c_units where code = '".substr($item->UnidadMedida,0,4) ."';";
								$resp = $this->db->query($sql);
								$unidad = $this->db->fetch_object($resp);
								if (is_null($unidad)){
									$sql = "INSERT INTO ".MAIN_DB_PREFIX."c_units 
									( code, scale, label, short_label, unit_type, active) values
									('". substr($item->UnidadMedida,0,4) ."',1,'". $item->UnidadMedida ."','". $item->UnidadMedida ."','qty',1)";
									$resql = $this->db->query($sql);
									if (!$resql) {
										setEventMessages('Error en la creacion del Unidad de medida '. $item->UnidadMedida .'-'.$this->db->lasterror() , null, 'errors');
										return -1 ;
									}else{
										$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "c_units where code = '".substr($item->UnidadMedida,0,4) ."';";
										$resp = $this->db->query($sql);
										$unidad = $this->db->fetch_object($resp);
										$Product->fk_unit  =  $unidad->rowid;
									}
									
								}else{
									$Product->fk_unit  =  $unidad->rowid;
								}
								
								$Product->finished = 1;

								//$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "product where 
								//note = '".  $item->Codigo ."' or ref = '".  $item->Codigo ."' or ref = '".  $item->CodigoComercial->Tipo.'-'.$item->CodigoComercial->Codigo ."' or ref = '".  $item->CodigoComercial->Codigo ."' order by rowid;";
								if (is_null($item->CodigoComercial->Codigo)){
									$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "product where 
									ref = '".   $item->Codigo ."' order by rowid;";
								}else{
									$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "product where 
									ref = '".  $item->CodigoComercial->Codigo ."' order by rowid;";
								}

								$rs = $this->db->query($sql);
								
								$Productrs = $this->db->fetch_object($rs);
								$omitecrearprodserv =false;
								if (is_null($Productrs)){
									$Product->price_base_type = 'HT';
									$Product->price = $item->PrecioUnitario;
									$Product->price_ttc = $item->PrecioUnitario + ($item->PrecioUnitario * ($item->Impuesto->Tarifa/100));
									$Product->cost_price = (double )$item->PrecioUnitario;
									
									$Product->default_vat_code = $item->Impuesto->CodigoTarifa;
									$Product->tva_tx = $item->Impuesto->Tarifa;
									$Productid = $Product->create($user,1);
									
									if ($Productid >0){
										
										//if ((strlen($item->Codigo) >= 12 ) && !empty($item->Impuesto->CodigoTarifa) ){
											$sqlinsert = "INSERT INTO ".MAIN_DB_PREFIX.$Product->table_element."_extrafields 
											(fk_object,crlibre_ti,crlibre_c1,crlibre_c2,crlibre_c3,crlibre_c4,crlibre_c5,crlibre_c6,crlibre_c7,crlibre_c8,crlibre_c9,crlibre_cabys) values
											(".$Productid .",'". $item->Impuesto->CodigoTarifa ."','". substr($item->Codigo,0,1)."','".substr($item->Codigo,0,2) ."','".substr($item->Codigo,0,3) ."',
											'".substr($item->Codigo,0,4) ."','".substr($item->Codigo,0,5) ."',
											'".substr($item->Codigo,0,7) ."','".substr($item->Codigo,0,9)."','".substr($item->Codigo,0,11)."','".$item->Codigo."','".$item->Codigo."')";
											
											$resql = $this->db->query($sqlinsert);
											
											if (!$resql) {
												setEventMessages('Error en la creacion del CaByS '.$this->db->lasterror() , null, 'errors');
												return -1 ;
											}
										//}
										//$Productrs->rowid = $Productid;
										
									}else{
										$omitecrearprodserv =true;
										
										 setEventMessages($comprobante->Clave.' Error en la creacion del producto '.$item->Codigo.' '.json_encode($Product->errors ) , null, 'errors');
										 return -1 ;
									}
									
								}else{
									$Product->fetch($Productrs->rowid);
								}

								
								if (!$omitecrearprodserv){
									$Product->add_fournisseur($user,$thirdpartyid, $item->Codigo, $item->Cantidad);
									if (is_null($Productrs->rowid)){
										$Productid = $Product->update($Productid ,$user,true,'update');
									}else{
										$Productid = $Product->update($Productrs->rowid ,$user,true,'update');
									}
									if ($Productid >0){
										//setEventMessages('Actualizacion del producto ' , null,'mesgs' );
									}else{
										setEventMessages('Error en la Actualizacion del producto '. json_encode($Product->errors)  , null, 'errors');
										return -1 ;
									}
								}else{
									$Productrs->rowid = 0;
								}

								// echo 'id prod'.$Productrs->rowid;
								// return -1;
								// die;
								//Crea linea de detalle de la factura
								$product_desc = $item->Detalle;
								if ($invoice->multicurrency_code == $conf->global->MAIN_MONNAIE ){
									$pu_ht = $item->PrecioUnitario;
								}else{
									$pu_ht = $item->PrecioUnitario / $invoice->multicurrency_tx;;
								}
								$tva_tx = $item->Impuesto->Tarifa;
								$localtax1_tx = 0;
								$localtax2_tx = 0;
								$qty = $item->Cantidad;
								$fk_product =$Productrs->rowid;
								if ( !empty($item->Descuento->MontoDescuento) ) {
									$remise_percent = ($item->Descuento->MontoDescuento/ $item->MontoTotal) * 100;
								}else{
									$remise_percent = 0;
								}
								$date_start = null;
								$date_end = null;
								$ventil ='0';
								$info_bits = '';
								$price_base_type = 'HT';
								$type = $Product->type;
								$rang = $item->NumeroLinea;
								$notrigger =0;
								$array_options = 0;
								$fk_unit = $Product->fk_unit;
								$origin_id =0;
								$pu_ht_devise = 0;
								$ref_supplier = $item->Codigo;
								$special_code = $item->CodigoComercial->Tipo.'-'.$item->CodigoComercial->Codigo;
								$fk_parent_line =0;
								$fk_remise_except =0;

								$result = $invoice->addline($product_desc, $pu_ht, $tva_tx, $localtax1_tx, $localtax2_tx, $qty, $fk_product , $remise_percent, $date_start, $date_end, $ventil, $info_bits, $price_base_type, $type, $rang, $notrigger, $array_options, $fk_unit, $origin_id, $pu_ht_devise, $ref_supplier,$special_code,$fk_parent_line,$fk_remise_except);
								
								if ($result < 0) {
									setEventMessages('Error en la creacion del detalle factura '.$comprobante->Clave.' '.$invoice->error  , null, 'errors');
									return -1 ;
								} else{
									if ( $comprobante->ResumenFactura->TotalIVADevuelto > 0){
										$amount_ht = $comprobante->ResumenFactura->TotalIVADevuelto;
										$desc ='IVA Devuelto';
										$tva_tx = 0; //tipo impuesto es 0% exento
										$discount_type =1;
										$discountid = $thirdpartystatic->set_remise_except($amount_ht, $user, $desc, $tva_tx, $discount_type);
										
										if ($discountid > 0) {
											$result = $invoice->insert_discount($discountid);
											if ($result < 0) {
												setEventMessages('Error aplicando la devolucion del IVA', $invoice->errors, 'errors');
												return -1 ;
												die ;
											}
										}else{
											setEventMessages('Error en la devolucion del IVA', $thirdpartystatic->errors, 'errors');
											return -1 ;
										}
									}
								}
							}
                        
							foreach ($comprobante->OtrosCargos as $OtrosCargos => $oc) {

								$Product->type  =  Product::TYPE_SERVICE;
							
								//Crea linea de detalle de la factura
								$product_desc = $oc->Detalle;
								if ($invoice->multicurrency_code == $conf->global->MAIN_MONNAIE ){
									$pu_ht = $oc->MontoCargo;
								}else{
									$pu_ht = $oc->MontoCargo / $invoice->multicurrency_tx;;
								}
								$tva_tx = 0;
								$localtax1_tx = 0;
								$localtax2_tx = 0;
								$qty = 1;
								$fk_product =null;
								if ( !empty($item->Descuento->MontoDescuento) ) {
									$remise_percent = ($item->Descuento->MontoDescuento/ $item->MontoTotal) * 100;
								}else{
									$remise_percent = 0;
								}
								$date_start = null;
								$date_end = null;
								$ventil ='0';
								$info_bits = '';
								$price_base_type = 'HT';
								$type = $Product->type;
								$rang = null;
								$notrigger =0;
								$array_options = 0;
								$fk_unit = null;
								$origin_id =0;
								$pu_ht_devise = 0;
								$ref_supplier = null;
								$special_code =null;
								$fk_parent_line =0;
								$fk_remise_except =0;

								$result = $invoice->addline($product_desc, $pu_ht, $tva_tx, $localtax1_tx, $localtax2_tx, $qty, $fk_product , $remise_percent, $date_start, $date_end, $ventil, $info_bits, $price_base_type, $type, $rang, $notrigger, $array_options, $fk_unit, $origin_id, $pu_ht_devise, $ref_supplier,$special_code,$fk_parent_line,$fk_remise_except);
								
								if ($result < 0) {
									setEventMessages('Error en la creacion del detalle factura '.$comprobante->Clave.' '.$invoice->error  , null, 'errors');
									return -1 ;
								} 
							}
						}else{
							//setEventMessages('Error en el registro del documento: '.$comprobante->NumeroConsecutivo , null, 'errors');
							//return -1 ;
						}

					}
					if ($comprobante->getName() === 'NotaCreditoElectronica'){

						$sql = "SELECT fk_object rowid from ". MAIN_DB_PREFIX . "facture_fourn_extrafields where 
						crlibre_clave = '". $comprobante->Clave ."' ;";
						$rs = $this->db->query($sql);
						$valrs = $this->db->fetch_object($rs);

						if (!is_null($valrs)){
							setEventMessages('El documento '.$comprobante->Clave.' ya fue importado' , null, 'errors');
							return -1 ;
						}
						
						if ( $comprobante->Receptor->Identificacion->Numero != $conf->global->MAIN_INFO_SIREN ){
							setEventMessages('El documento '.$comprobante->Clave.' no corresponde a esta empresa' , null, 'errors');
							return -1 ;
						}
						$thirdpartystatic = new Societe($this->db);
						
						if (strlen($comprobante->Emisor->NombreComercial) > 0 )
							$thirdpartystatic->name = $comprobante->Emisor->NombreComercial;
						else
							$thirdpartystatic->name =  $comprobante->Emisor->Nombre ;
						
						$thirdpartystatic->name_alias = $comprobante->Emisor->Nombre;

						// $sql = "SELECT id, code from ". MAIN_DB_PREFIX . "c_typent where code = '".$comprobante->Emisor->Identificacion->Tipo."';";
						// $resp = $this->db->query($sql);
						// $typent = $this->db->fetch_object($resp);
						//$thirdpartystatic->typent_code= $typent->code;
						//$thirdpartystatic->typent_id = $typent->id;
						$thirdpartystatic->pays = 75;
						$thirdpartystatic->country = 'Costa Rica';
						$thirdpartystatic->country_code = 'CR';
						$thirdpartystatic->country_id = 75;
						$thirdpartystatic->multicurrency_code = $comprobante->ResumenFactura->CodigoTipoMoneda->CodigoMoneda;
						$thirdpartystatic->forme_juridique_code =strval((intval($comprobante->Emisor->Identificacion->Tipo)));
						$thirdpartystatic->tva_intra = $comprobante->CodigoActividad;
						$thirdpartystatic->idprof1 = $comprobante->Emisor->Identificacion->Numero;
						$thirdpartystatic->idprof6 = $comprobante->CodigoActividad;
						$thirdpartystatic->zip = $comprobante->Emisor->Ubicacion->Provincia.$comprobante->Emisor->Ubicacion->Canton.$comprobante->Emisor->Ubicacion->Distrito.$comprobante->Emisor->Ubicacion->Barrio;
						$sql = "SELECT rowid, nom from ". MAIN_DB_PREFIX . "c_departements where code_departement = ".$comprobante->Emisor->Ubicacion->Provincia.";";
						$resp = $this->db->query($sql);
						$town = $this->db->fetch_object($resp);
						$thirdpartystatic->town = $town->nom;
						$thirdpartystatic->address = $comprobante->Emisor->Ubicacion->OtrasSenas;
						$thirdpartystatic->phone = $comprobante->Emisor->Telefono->CodigoPais.$comprobante->Emisor->Telefono->NumTelefono;
						$thirdpartystatic->fax = $comprobante->Emisor->Fax->CodigoPais.$comprobante->Emisor->Fax->NumTelefono;
						$thirdpartystatic->email = $comprobante->Emisor->CorreoElectronico;
						$thirdpartystatic->code_fournisseur = 'auto';
						$thirdpartystatic->fournisseur = 1;
						$thirdpartystatic->multicurrency_code = $comprobante->ResumenFactura->CodigoTipoMoneda->CodigoMoneda;
						$thirdpartystatic->note_public = 'Importado por el Colector de email '. date('d-m-Y').'.';

						$thirdpartycontact = new Contact($this->db);
						$thirdpartycontact->entity = $conf->entity;
						if ( strlen($comprobante->Emisor->Nombre) >50){
							$thirdpartycontact->firstname = substr($comprobante->Emisor->Nombre,0,50);
							$thirdpartycontact->lastname = substr($comprobante->Emisor->Nombre,51,100);
						}else{
							$thirdpartycontact->firstname = $comprobante->Emisor->Nombre;
						}
						$thirdpartycontact->address = $comprobante->Emisor->Ubicacion->OtrasSenas;
						$thirdpartycontact->zip = $comprobante->Emisor->Ubicacion->Provincia.$comprobante->Emisor->Ubicacion->Canton.$comprobante->Emisor->Ubicacion->Distrito.$comprobante->Emisor->Ubicacion->Barrio;
						$thirdpartycontact->town = $town->nom;
						$thirdpartycontact->state_id = $town->rowid;
						$thirdpartycontact->phone_pro = $comprobante->Emisor->Telefono->CodigoPais.$comprobante->Emisor->Telefono->NumTelefono;
						$thirdpartycontact->email = $parameters["from"];
						$thirdpartycontact->priv = 0;
						$thirdpartycontact->note_public = 'Importado por el Colector de email '. date('d-m-Y').'.';


						$sql = "SELECT rowid, code_client, client from ". MAIN_DB_PREFIX . "societe where 
						idprof4 = '".$comprobante->Emisor->Identificacion->Numero."'
						or idprof5 = '".$comprobante->Emisor->Identificacion->Numero."'
						or siren = '".$comprobante->Emisor->Identificacion->Numero."'
						or siret = '".$comprobante->Emisor->Identificacion->Numero."' ;";
						$rs = $this->db->query($sql);
						$thirdpartyrs = $this->db->fetch_object($rs);
						if ( is_null( $thirdpartyrs) ) {
							
							$thirdpartyid = $thirdpartystatic->create($user);
							if ($thirdpartyid >= 0) {
								//Crea contacto de facturacion electronica.
								$thirdpartycontact->socid = $thirdpartyid;
								$thirdpartycontactid = $thirdpartycontact->create($user);
							}else{
								setEventMessages('Error en el registro del proveedor '.json_encode($thirdpartystatic->errors)  , null, 'errors');
								return -1 ;
							}
						}else{
							$thirdpartystatic->code_client = $thirdpartyrs->code_client;
							$thirdpartystatic->client = $thirdpartyrs->client;
							$thirdpartyid = $thirdpartystatic->update($thirdpartyrs->rowid, $user, 0,0,0,'update');

							if ( $thirdpartyid >=0 ){
								//$resultc = $thirdpartycontact->fetch($comprobante->Emisor->CorreoElectronico);
								$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "socpeople where 
								email = '". $parameters["from"] ."' ;";
								$rs = $this->db->query($sql);
								$contactrs = $this->db->fetch_object($rs);
								if ( is_null($contactrs)) {
									//Crea contacto de facturacion electronica.
									$thirdpartycontact->socid = $thirdpartyrs->rowid;
									$thirdpartycontactid = $thirdpartycontact->create($user);
								}else{
									$thirdpartycontactid = $thirdpartycontact->update($contactrs->rowid, $user,0,'update');
								}
							}else{
								setEventMessages('Error en la actualizacion del contacto del proveedor '. json_encode($thirdpartystatic->errors) , null, 'errors');
								return -1 ;
							}
							$thirdpartyid = $thirdpartyrs->rowid;
						}
						if ($thirdpartycontactid <= 0){
							setEventMessages('Error en el registro del contacto del proveedor '.$thirdpartycontact->error  , null, 'errors');
							return -1 ;
						}
						//Valida documento a importar
						$sql = "SELECT fk_object rowid from ". MAIN_DB_PREFIX . "facture_fourn_extrafields where 
						crlibre_clave = '". $comprobante->Clave ."' ;";
						$rs = $this->db->query($sql);
						$ffrs = $this->db->fetch_object($rs);
						if (is_null($ffrs)){
							$invoice = new FactureFournisseur($this->db);
							$dateinvoice = dol_mktime(12, 0, 0, date('m'), date('d'), date('Y'));
							$invoice->socid = $thirdpartyid;
							str_replace(" ","T",date('Y-m-d H:i:s'));
							$emision = new DateTime( str_replace("T"," ",$comprobante->FechaEmision));
							$invoice->date = dol_mktime(12, 0, 0, $emision->format('m'), $emision->format('d'), $emision->format('Y'));
							if ($comprobante->PlazoCredito > 0 ){
								$emision->modify('+'.$comprobante->PlazoCredito.' day') ;
								$invoice->date_echeance = $emision->format('Y-m-d');
							}
							$invoice->date_pointoftax = $invoice->date;
							$invoice->note_public = $comprobante->InformacionReferencia->Razon .' Importado por el Colector de email '. date('d-m-Y').'.';
							$invoice->note_private = $comprobante->InformacionReferencia->Razon ;
							// We do not copy the private note
							$invoice->ref_supplier	= $comprobante->NumeroConsecutivo;
							
							$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "c_payment_term where code = '". str_pad( $comprobante->CondicionVenta,2,"0", STR_PAD_LEFT) ."';";
							$resp = $this->db->query($sql);
							$payterm = $this->db->fetch_object($resp);
							$invoice->cond_reglement_id	= $payterm->rowid;

							$sql = "SELECT id from ". MAIN_DB_PREFIX . "c_paiement where code = '". str_pad( $comprobante->MedioPago,2,"0", STR_PAD_LEFT) ."';";
							$resp = $this->db->query($sql);
							$pay = $this->db->fetch_object($resp);
							$invoice->mode_reglement_id	= $pay->id;

							$invoice->multicurrency_code =  (string)  $comprobante->ResumenFactura->CodigoTipoMoneda->CodigoMoneda[0];
                            if ( $comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio >0){
                                //$invoice->multicurrency_tx = 1/floatval($comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio);
                            	list($fk_multicurrency, $multicurrency_tx) = MultiCurrency::getIdAndTxFromCode( $this->db, $invoice->multicurrency_code, $dateinvoice);
                            	$invoice->multicurrency_tx = $multicurrency_tx;
                            }
                        
							if ($invoice->multicurrency_code == $conf->global->MAIN_MONNAIE){
								$invoice->tva = $comprobante->ResumenFactura->TotalImpuesto;
								$invoice->total_tva = $comprobante->ResumenFactura->TotalImpuesto;
								$invoice->total_ht = $comprobante->ResumenFactura->TotalVentaNeta;
								$invoice->total_ttc = $comprobante->ResumenFactura->TotalComprobante;
								$invoice->remise = $comprobante->ResumenFactura->TotalDescuentos;
							}else{
								$invoice->tva = $comprobante->ResumenFactura->TotalImpuesto / $invoice->multicurrency_tx;
								$invoice->total_tva = $comprobante->ResumenFactura->TotalImpuesto / $invoice->multicurrency_tx;
								$invoice->total_ht = $comprobante->ResumenFactura->TotalVentaNeta / $invoice->multicurrency_tx;
								$invoice->total_ttc = $comprobante->ResumenFactura->TotalComprobante / $invoice->multicurrency_tx;
								$invoice->remise = $comprobante->ResumenFactura->TotalDescuentos / $invoice->multicurrency_tx;
                            	$invoice->fk_multicurrency =$fk_multicurrency;
								$invoice->multicurrency_total_tva = $comprobante->ResumenFactura->TotalImpuesto;
								$invoice->multicurrency_total_ht = $comprobante->ResumenFactura->TotalVentaNeta;
								$invoice->multicurrency_total_ttc = $comprobante->ResumenFactura->TotalComprobante;
							}
							$invoice->statut == FactureFournisseur::STATUS_DRAFT;

							//Documento de referencia en la NC
							$sql = "SELECT fk_object rowid from ". MAIN_DB_PREFIX . "facture_fourn_extrafields where 
							crlibre_clave = '". $comprobante->InformacionReferencia->Numero ."' ;";
							$rs = $this->db->query($sql);
							$frrs = $this->db->fetch_object($rs);
							if ( ! is_null($frrs)){
								$invoice->fk_facture_source = $frrs->rowid;
							}else{
								setEventMessages('No existe factura de referencia para la creacion de la Nota de credito'.$invoice->error  , null, 'errors');
								return -1 ;
							}
							if ($invoice->multicurrency_code == $conf->global->MAIN_MONNAIE){
								$invoice->libelle = $comprobante->InformacionReferencia->Razon .' Importado por el Colector de email '. date('d-m-Y').'.';
							}else{
								$invoice->libelle = $comprobante->InformacionReferencia->Razon .' Importado por el Colector de email '. date('d-m-Y').'. Modena original del documento {'.$comprobante->ResumenFactura->CodigoTipoMoneda->CodigoMoneda.'}-Tipo de Cambio ['.$invoice->multicurrency_tx.'].';
							}
							// Proprietes particulieres a facture avoir
							$invoice->type = FactureFournisseur::TYPE_CREDIT_NOTE;
							
							$invoiceid = $invoice->create($user);
							if ($invoiceid < 0) {
								setEventMessages('Error en la creacion de la factura'.$invoice->error  , null, 'errors');
								return -1 ;
							} else {
								$invoice->array_options = array(
									'options_crlibre_clave' => $comprobante->Clave
								);
								$invoice->updateExtraField('crlibre_clave');
								// copy internal contacts
								if ($invoice->copy_linked_contact($thirdpartystatic, 'internal') < 0) {
									$error++;
								} elseif ($object->socid == $invoice->socid) {
									// copy external contacts if same company
									if ($invoice->copy_linked_contact($thirdpartystatic, 'external') < 0) {
										$error++;
									}
								}
							}
							//Create details
							$Product = new Product($this->db);
							
							foreach ($comprobante->DetalleServicio->LineaDetalle as $LineaDetalle => $item) {
								if (!isset($item->Codigo) ){
									setEventMessages('Error en los datos de la factura, no posee codigo de producto CaByS', null, 'errors');
									return -1 ;
								}
								//Crea/Actualiza el producto 
								if ( intval( substr($item->Codigo,0,1)) <= 4 ){
									//Producto
									$Product->type  =  Product::TYPE_PRODUCT;
								}else{
									//Servicio
									$Product->type  =  Product::TYPE_SERVICE;
								}
								$Product->note = $item->Codigo;
								if (is_null($item->CodigoComercial->Codigo)){
									$Product->ref = $item->Codigo;
								}else{
									$Product->ref = $item->CodigoComercial->Tipo.'-'.$item->CodigoComercial->Codigo;
								}
								$Product->description = $item->Detalle;
								$Product->label = $item->Detalle;
								$Product->note_private   = 'Creado apartir de la factura '.$comprobante->clave;
								$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "c_units where code = '".substr($item->UnidadMedida,0,4) ."';";
								$resp = $this->db->query($sql);
								$unidad = $this->db->fetch_object($resp);
								if (is_null($unidad)){
									$sql = "INSERT INTO ".MAIN_DB_PREFIX."c_units 
									( code, scale, label, short_label, unit_type, active) values
									('". substr($item->UnidadMedida,0,4) ."',1,'". $item->UnidadMedida ."','". $item->UnidadMedida ."','qty',1)";
									$resql = $this->db->query($sql);
									if (!$resql) {
										setEventMessages('Error en la creacion del Unidad de medida '. $item->UnidadMedida .'-'.$this->db->lasterror() , null, 'errors');
										return -1 ;
									}else{
										$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "c_units where code = '".substr($item->UnidadMedida,0,4) ."';";
										$resp = $this->db->query($sql);
										$unidad = $this->db->fetch_object($resp);
										$Product->fk_unit  =  $unidad->rowid;
									}
									
								}else{
									$Product->fk_unit  =  $unidad->rowid;
								}
								$Product->finished = 1;
								$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "product where 
								note = '".  $item->Codigo ."' ;";
								$rs = $this->db->query($sql);
								$Productrs = $this->db->fetch_object($rs);
								if (is_null($Productrs)){
									$Product->price_base_type = 'HT';
									$Product->price = $item->PrecioUnitario;
									$Product->price_ttc = $item->PrecioUnitario + ($item->PrecioUnitario * ($item->Impuesto->Tarifa/100));
									$Product->cost_price = $item->PrecioUnitario;
									$Product->default_vat_code = $item->Impuesto->CodigoTarifa;
									$Product->tva_tx = $item->Impuesto->Tarifa;
									$Productid = $Product->create($user,1);
									if ($Productid >0){
										
										if ((strlen($item->Codigo) >= 12 ) && !empty($item->Impuesto->CodigoTarifa) ){
											$sqlinsert = "INSERT INTO ".MAIN_DB_PREFIX.$Product->table_element."_extrafields 
											(fk_object,crlibre_ti,crlibre_c1,crlibre_c2,crlibre_c3,crlibre_c4,crlibre_c5,crlibre_c6,crlibre_c7,crlibre_c8,crlibre_c9) values
											(".$Productid .",'". $item->Impuesto->CodigoTarifa ."','". substr($item->Codigo,0,1)."','".substr($item->Codigo,0,2) ."','".substr($item->Codigo,0,3) ."',
											'".substr($item->Codigo,0,4) ."','".substr($item->Codigo,0,5) ."',
											'".substr($item->Codigo,0,7) ."','".substr($item->Codigo,0,9)."','".substr($item->Codigo,0,11)."','".$item->Codigo."')";
											$resql = $this->db->query($sqlinsert);
											if (!$resql) {
												setEventMessages('Error en la creacion del CaByS '.$this->db->lasterror() , null, 'errors');
												return -1 ;
											}
										}
										$Productrs->rowid = $Productid;
									}else{
										$omitecrearprodserv =true;
										// setEventMessages($comprobante->Clave.' Error en la creacion del producto '.$item->Codigo.' '.$Product->error  , null, 'errors');
										// return -1 ;
									}
								}else{
									$Product->fetch($Productrs->rowid);
								}
								if (!$omitecrearprodserv){
									$Product->add_fournisseur($user,$thirdpartyid, $item->Codigo, $item->Cantidad);
									$Productid = $Product->update($Productrs->rowid ,$user,false,'update');
									if ($Productid >0){
										//setEventMessages('Actualizacion del producto ' , null,'mesgs' );
									}else{
										setEventMessages('Error en la Actualizacion del producto '.$Product->error  , null, 'errors');
										return -1 ;
									}
								}else{
									$fk_product =$Productrs->rowid;
								}
								//Crea linea de detalle de la factura
								$product_desc = $item->Detalle;
								if ($invoice->multicurrency_code == $conf->global->MAIN_MONNAIE ){
									$pu_ht = $item->PrecioUnitario;
								}else{
									$pu_ht = $item->PrecioUnitario / $invoice->multicurrency_tx ;
								}
								$tva_tx = $item->Impuesto->Tarifa;
								$localtax1_tx = 0;
								$localtax2_tx = 0;
								$qty = $item->Cantidad;
								$fk_product =$Productrs->rowid;
								if ( !empty($item->Descuento->MontoDescuento) ) {
									$remise_percent = ($item->Descuento->MontoDescuento/ $item->MontoTotal) * 100;
								}else{
									$remise_percent = 0;
								}
								$date_start = null;
								$date_end = null;
								$ventil ='0';
								$info_bits = '';
								$price_base_type = 'HT';
								$type = $Product->type;
								$rang = $item->NumeroLinea;
								$notrigger =0;
								$array_options = 0;
								$fk_unit = $Product->fk_unit;
								$origin_id =0;
								$pu_ht_devise = 0;
								$ref_supplier = $item->Codigo;
								$special_code = $item->CodigoComercial->Tipo.'-'.$item->CodigoComercial->Codigo;
								$fk_parent_line =0;
								$fk_remise_except =0;

								$result = $invoice->addline($product_desc, $pu_ht, $tva_tx, $localtax1_tx, $localtax2_tx, $qty, $fk_product , $remise_percent, $date_start, $date_end, $ventil, $info_bits, $price_base_type, $type, $rang, $notrigger, $array_options, $fk_unit, $origin_id, $pu_ht_devise, $ref_supplier,$special_code,$fk_parent_line,$fk_remise_except);
								
								if ($result < 0) {
									setEventMessages('Error en la creacion del detalle factura '.$comprobante->Clave.' '.$invoice->error  , null, 'errors');
									return -1 ;
								} else{
									if ( $comprobante->ResumenFactura->TotalIVADevuelto > 0){
										$amount_ht = $comprobante->ResumenFactura->TotalIVADevuelto;
										$desc ='IVA Devuelto';
										$tva_tx = 0; //tipo impuesto es 0% exento
										$discount_type =1;
										$discountid = $thirdpartystatic->set_remise_except($amount_ht, $user, $desc, $tva_tx, $discount_type);
										if ($discountid > 0) {
											$result = $invoice->insert_discount($discountid);
											if ($result < 0) {
												setEventMessages('Error aplicando la devolucion del IVA', $invoice->errors, 'errors');
												return -1 ;
												die ;
											}
										}else{
											setEventMessages('Error en la devolucion del IVA', $thirdpartystatic->errors, 'errors');
											return -1 ;
										}
									}
								}
							}
						}else{
							//setEventMessages('Error en el registro del documento: '.$comprobante->NumeroConsecutivo , null, 'errors');
							//return -1 ;
						}
						
					}
					if ($invoiceid > 0) {
						$attachments = $parameters["attachments"];
						foreach ($attachments as $attachment => $content) {
							$objectref = dol_sanitizeFileName($invoice->ref);
							$objectrefsupplier = dol_sanitizeFileName($invoice->ref_supplier);
							$dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($invoice->id, 2, 0, 0, $invoice, 'invoice_supplier').$objectref;
							$file = $dir."/".$attachment;
							if (!empty($conf->global->SUPPLIER_REF_IN_NAME)) {
								$file = $dir."/".($objectrefsupplier ? "_".$objectrefsupplier : "").$attachment;
							}

							if (!file_exists($dir)) {
								if (dol_mkdir($dir) < 0) {
									setEventMessages('Error en el registro de los documentos, no se pudo agregar el directorio' , null, 'errors');
									return -1 ;
								}
							}
							if (file_exists($dir)) {
								$content = mb_convert_encoding($content, 'UTF-8', 'auto');
								$result = file_put_contents($file, $content, FILE_APPEND | LOCK_EX);
								if (!empty($conf->global->MAIN_UMASK)) {
									@chmod($file, octdec($conf->global->MAIN_UMASK));
								}
								if ($result ===false){
									setEventMessages('Error en el registro de los documentos' , null, 'errors');
									return -1 ;
								}
							}
							$destfull =$file;
							$upload_dir = dirname($destfull);
							$destfile = basename($destfull);
							$rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);

							include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
							$ecmfile = new EcmFiles($this->db);
							$result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$file);

							if ($result > 0) {
								$ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
								$ecmfile->fullpath_orig = '';
								$ecmfile->gen_or_uploaded = 'uploaded';
								$ecmfile->description = ''; // indexed content
								$ecmfile->keywords = ''; // keyword content
								$result = $ecmfile->update($user);
								if ($result < 0) {
									setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
									return -1 ;
								}
							} else {
								$ecmfile->entity = $conf->entity;
								$ecmfile->filepath = $rel_dir;
								$ecmfile->filename = $file;
								$ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
								$ecmfile->fullpath_orig = '';
								$ecmfile->gen_or_uploaded = 'uploaded';
								$ecmfile->description = ''; // indexed content
								$ecmfile->keywords = ''; // keyword content
								$ecmfile->src_object_type = $invoice->table_element;	// $this->table_name is 'myobject' or 'mymodule_myobject'.
								$ecmfile->src_object_id   = $invoice->id;

								$result = $ecmfile->create($user);
								if ($result < 0) {
									setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
									return -1 ;
								}else{
									$sql = 'UPDATE '.MAIN_DB_PREFIX.$invoice->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath.'/'.$ecmfile->filename)."'";
									$sql .= ' WHERE rowid = '.$invoice->id;

									$resql = $this->db->query($sql);
									if (!$resql) {
										setEventMessages('Error en la actualizacion de last document', 'warnings');
										dol_print_error($this->db);
										return -1 ;
									} else {
										$invoice->last_main_doc = $ecmfile->filename;
									}
								}
							}
							
						}
					}
					if ($invoiceid > 0) {
						$loc = DOL_URL_ROOT.'/fourn/facture/card.php?id='.$invoiceid;
					} 
					header('Location: '.$loc);
				}else{
					setEventMessages($langs->trans("NOsepuedemodificarunaFacturaEnviadaHacienda"), null, 'errors');
					return 1;
				}
			
            }elseif ($action == 'confirm_loadxml' ){
				$form = new Form($this->db);
				$numref = $object->ref_supplier;
				$text = 'Debe cargar el archivo XML.';
	
				$formquestion = array(
					array('type' => 'file', 'name' => 'filename', 'label' => 'Archivo XML', 'morecss' => 'minwidth350', 'moreattr' => 'maxlength="150"'),
					array('type' => 'hidden', 'name' => 'filename_content'),
				);
				print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('Carga de XML.'), $text, 'loadxml', $formquestion, 1, 0, 300, 500);


				$jscript ='<script type="text/javascript">'."\n ";
				$jscript .='if (window.File && window.FileReader && window.FileList && window.Blob) {
					document.getElementById(\'filename\').addEventListener(\'change\', handleFileSelect, false);
				} else {
					alert("The File APIs are not fully supported in this browser.");
				}
				function handleFileSelect(evt) {
					var f = evt.target.files[0]; // FileList object
					var reader = new FileReader();
					// Closure to capture the file information.
					reader.onload = (function(theFile) {
					return function(e) {
						var binaryData = e.target.result;
						//Converting Binary Data to base 64
						var base64String = window.btoa(binaryData);
						//showing file converted to base64
						
						document.getElementById(\'filename_content\').value = base64String;
						//debugger;
						console.log ( document.getElementById(\'filename_content\').value );
					};
					})(f);
					// Read in the image file as a data URL.
					reader.readAsBinaryString(f);
				}</script>';
				print $jscript;
			}
		}
		if (in_array($parameters['currentcontext'], array('thirdpartycard'))) {	    // do something only for the context 'somecontext1' or 'somecontext2'
			if ($action == 'mhconsulta' ){
				if ( !empty($object->idprof1) ){
					if ($object->forme_juridique_code == 1 ){
						$id = (int) filter_var($object->idprof1, FILTER_SANITIZE_NUMBER_INT); 
					}else{
						$id = (int) filter_var($object->idprof1, FILTER_SANITIZE_NUMBER_INT); 
					}
					$curl = curl_init();

					curl_setopt_array($curl, array(
					CURLOPT_URL => "https://api.hacienda.go.cr/fe/ae?identificacion=".$id ,
					CURLOPT_RETURNTRANSFER => true,
					CURLOPT_ENCODING => "",
					CURLOPT_USERAGENT => 'Mozilla Chrome Safari',
					CURLOPT_MAXREDIRS => 10,
					CURLOPT_TIMEOUT => 0,
					CURLOPT_FOLLOWLOCATION => false,
					CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
					CURLOPT_CUSTOMREQUEST => "GET",
					));

					$responseMH = curl_exec($curl);
					$err = curl_error($curl);

					curl_close($curl);

					if ($err) {
						echo "cURL Error #:" . $err;
					} else {
						$response = json_decode($responseMH);
						//var_dump($response);
						if ( is_null($response->nombre) ){
							setEventMessages('No se encontraron datos con la cedula registrada '.$id, null, 'errors');
							return -1;
						}else{
							$object->name = $response->nombre;
							$object->name_alias = $response->nombre;
							// $sql = "SELECT id, code from ". MAIN_DB_PREFIX . "c_typent where code = '". $response->tipoIdentificacion."';";
							// $resp = $this->db->query($sql);
							// $typent = $this->db->fetch_object($resp);
							// $object->typent_code= $typent->code;
							//var_DUmp($typent->id );
							//$object->typent_id = $typent->id;
							$object->country = 'Costa Rica';
							$object->country_code = 'CR';
							$object->country_id = 75;
							$object->forme_juridique_code =strval((intval($response->tipoIdentificacion)));
                        	$object->array_options = array(
                            	'options_estado_mh' => $responseMH,
								'options_regimenmh' => $response->regimen->descripcion,
                            	'options_situacionmora' => $response->situacion->moroso,
                            	'options_omisomh' => $response->situacion->omiso,
                            	'options_statusmh' => $response->situacion->estado,
                            	'options_administraciontributaria' => $response->situacion->administracionTributaria
							);
                        	$object->updateExtraField('regimenmh');
							$object->updateExtraField('situacionmora');
							$object->updateExtraField('omisomh');
							$object->updateExtraField('statusmh');
							$object->updateExtraField('administraciontributaria');
							// if ( ( $response->situacion->estado == "Inscrito" ) || ( $response->situacion->estado == "Inscrito de Oficio" )){
							// 	$object->setStatut(1);
							// }else{
							// 	setEventMessages('El estado '.$response->situacion->estado. ' no es valido!', null, 'errors');
							// 	$object->setStatut(0);
							// }
							foreach ($response->actividades as $Actividad => $linea) {
								if ( ($linea->estado== "A" ) && ($linea->tipo== "P" ) ){
									$object->idprof6 = $linea->codigo;
									$object->tva_intra = $linea->codigo;
								}
							}

							$response = $object->updateExtraField('estado_mh');
							$response = $object->update($object->id, $user, 0,0,0,'update');
							

							if ($response > 0 ){
								setEventMessages('Datos actualizados con respecto al Ministerio de Hacienda', null, 'mesgs');
							}else{
								setEventMessages('Error en la actualizacion del tercero' . json_encode($object->errors)  , null, 'errors');
								return -1 ;
							}
							
						}
						
					}

					return 0;
				}else{
					setEventMessages('Se requiere el numero de cedula', null, 'errors');
					return -1;
				}
			}
		}
		if (in_array($parameters['currentcontext'], array('invoicecard'))) {	    // do something only for the context 'somecontext1' or 'somecontext2'
			
        	$confirm = GETPOST('confirm', 'alpha');

        	if ($action == 'confirm_valid' && $confirm == 'yes'  ){

				if ($object->type == Facture::TYPE_CREDIT_NOTE ){
             		if ($object->array_options['options_ind_returninv'] == 1 ){
							$object->fetchObjectLinked('', 'shipping' , $object->fk_facture_source, 'facture');
							if (is_array($object->linkedObjects['shipping']) && count($object->linkedObjects['shipping']) >= 1) {
								$disablestockchangeforsubproduct = 0;
								$origin_element = 'facture';
								$origin_id = $object->id;
								$Pobject = new Product($this->db);
                            	$i=0;
								foreach($object->lines as $lineadetalle){
									$Pobject->fetch($lineadetalle->fk_product);
	
									$sql= "SELECT fk_entrepot, buy_price_ht, e.qty - (SELECT IFNULL(sum(qty),0) qty FROM  " . MAIN_DB_PREFIX . "facture f inner join  " . MAIN_DB_PREFIX . "facturedet fd on (f.rowid = fd.fk_facture)  WHERE f.fk_statut >0 and f.fk_facture_source = ". $object->fk_facture_source ." AND fk_product =  ".$lineadetalle->fk_product.") qty ";
									$sql .= " FROM " . MAIN_DB_PREFIX . "expeditiondet e INNER JOIN " . MAIN_DB_PREFIX . "commandedet c on (e.fk_origin_line = c.rowid ) ";
									$sql .= " WHERE e.fk_expedition in (SELECT fk_source FROM " . MAIN_DB_PREFIX . "element_element WHERE fk_target = ". $object->fk_facture_source ." and sourcetype = 'shipping')  ";
									$sql .= " AND fk_product = ".$lineadetalle->fk_product." ";
									$result = $this->db->query($sql);									

									if ($result) {
										$obj = $this->db->fetch_object($result);
                                    	$nbpiece = price2num($lineadetalle->qty ); 
										$priceunit = price2num( abs(round($Pobject->pmp ,2)));
										$nbpiece = price2num($lineadetalle->qty ); //Genera el movimiento en negativo
                                    
										if (    $nbpiece <= $obj->qty  ){
											
										}else {
											setEventMessages('La cantidad a devolver es mayor a la cantidad disponible. Linea :'.($i+1), $Pobject->errors, 'errors');
											return -1;
										}
										if ($result > 0) {
											//var_dump($result);
										} else {
											setEventMessages($Pobject->error, $Pobject->errors, 'errors');
											return -1;
										}
									} else {
										setEventMessages('Error en consulta...',  $this->db->error, 'errors');
										return -1;
									}
                                	$i++;
								}
                            	$i=0;
								foreach($object->lines as $lineadetalle){
									$Pobject->fetch($lineadetalle->fk_product);
	
									$sql= "SELECT fk_entrepot, buy_price_ht, e.qty - (SELECT IFNULL(sum(qty),0) qty FROM  " . MAIN_DB_PREFIX . "facture f inner join  " . MAIN_DB_PREFIX . "facturedet fd on (f.rowid = fd.fk_facture)  WHERE f.fk_statut >0 and f.fk_facture_source = ". $object->fk_facture_source ." AND fk_product =  ".$lineadetalle->fk_product.") qty ";
									$sql .= " FROM " . MAIN_DB_PREFIX . "expeditiondet e INNER JOIN " . MAIN_DB_PREFIX . "commandedet c on (e.fk_origin_line = c.rowid ) ";
									$sql .= " WHERE e.fk_expedition in (SELECT fk_source FROM " . MAIN_DB_PREFIX . "element_element WHERE fk_target = ". $object->fk_facture_source ." and sourcetype = 'shipping')  ";
									$sql .= " AND fk_product = ".$lineadetalle->fk_product." ";
									$result = $this->db->query($sql);									

									if ($result) {
										$obj = $this->db->fetch_object($result);
                               
                                    	$nbpiece = price2num($lineadetalle->qty ); 
										$priceunit = price2num( abs(round($Pobject->pmp ,2)));
										$nbpiece = price2num($lineadetalle->qty ); //Genera el movimiento en negativo
                                    
										if (    $nbpiece <= $obj->qty  ){
											if ($Pobject->hasbatch()) {
												$result = $Pobject->correct_stock_batch(
													$user,
													$obj->fk_entrepot,
													$nbpiece,
													0,
													'Devolucion mediante '.$object->newref, // label movement
													$priceunit,
													$d_eatby,
													$d_sellby,
													$batchnumber,
													dol_print_date(dol_now(), '%Y%m%d%H%M%S'),
													$origin_element,
													$origin_id,
													$disablestockchangeforsubproduct
												); // We do not change value of stock for a correction
											} else {
												$result = $Pobject->correct_stock(
													$user,
													$obj->fk_entrepot,
													$nbpiece,
													0,
													'Devolucion mediante '.$object->newref, // label movement
													$priceunit,
													dol_print_date(dol_now(), '%Y%m%d%H%M%S'),
													$origin_element,
													$origin_id,
													$disablestockchangeforsubproduct
												); // We do not change value of stock for a correction
											}
										}else {
											setEventMessages('La cantidad a devolver es mayor a la cantidad disponible. Linea :'.($i+1), $Pobject->errors, 'errors');
											return -1;
										}
										
										if ($result > 0) {
											//var_dump($result);
										} else {
											setEventMessages($Pobject->error, $Pobject->errors, 'errors');
											return -1;
										}
									} else {
										setEventMessages('Error en consulta...',  $this->db->error, 'errors');
										return -1;
									}
                                	$i++;
								}
							} else {
								setEventMessages('La factura origen, no registra envío para realizar la devolución de mercadería',  $this->db->error, 'errors');
								return -1;
							}
						}
                }
			//	if (($object->type == Facture::TYPE_STANDARD)) { // empty should not happened, but when it occurs, the test save life
					$mask = '';
					if ( ($object->array_options['options_crlibre_tipodocto'] == 4 ) || ($object->array_options['options_crlibre_tipodocto'] == 9 ) ){
						if ($object->array_options['options_crlibre_tipodocto'] == 4) {
							$prefix = 'TE';
							$mask = $conf->global->CRFACT_MASK_INVOICE_TE;
						} elseif ($object->array_options['options_crlibre_tipodocto'] == 9) {
							$prefix = 'FE';
							$mask = $conf->global->CRFACT_MASK_INVOICE_FEE;
						}
					}else{
						
						if (is_object($object) && $object->type == 1) {
							$mask = $conf->global->FACTURE_MERCURE_MASK_REPLACEMENT;
							if (!$mask) {
								$mask = $conf->global->FACTURE_MERCURE_MASK_INVOICE;
							}
						} elseif (is_object($object) && $object->type == 2) {
							$mask = $conf->global->FACTURE_MERCURE_MASK_CREDIT;
						} elseif (is_object($object) && $object->type == 3) {
							$mask = $conf->global->FACTURE_MERCURE_MASK_DEPOSIT;
						} else {
							$mask = $conf->global->FACTURE_MERCURE_MASK_INVOICE;
						}
					}

					$where = '';
					$mode = 'next';
					$entity = getEntity('invoicenumber', 1, $object);
					$numFinal = get_next_value($this->db, $mask, 'facture', 'ref', $where, $object->thirdparty, $object->date, $mode, false, null, $entity);

					$object->ref = dol_sanitizeFileName($numFinal);
					$id = $object->id;

					// Classify to validated
					$idwarehouse = GETPOST('idwarehouse', 'int');

					$ret = $object->fetch($id);
					$object->fetch_thirdparty();

					$result = $object->validate($user, $numFinal, $idwarehouse);
					
					if ($result >= 0) {
						// Define output language
						if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
							$outputlangs = $langs;
							$newlang = '';
							if (!empty($conf->global->MAIN_MULTILANGS) && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
								$newlang = GETPOST('lang_id', 'aZ09');
							}
							if (!empty($conf->global->MAIN_MULTILANGS) && empty($newlang)) {
								$newlang = $object->thirdparty->default_lang;
							}
							if (!empty($newlang)) {
								$outputlangs = new Translate("", $conf);
								$outputlangs->setDefaultLang($newlang);
								$outputlangs->load('products');
							}
							$model = $object->model_pdf;

							$ret = $object->fetch($id); // Reload to get new records

							$result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
							if ($result < 0) {
								setEventMessages($object->error, $object->errors, 'errors');
							}
						}
						if ( strlen(trim($object->array_options['options_crlibre_clave']) ) > 0){
							$text = $langs->trans('ConfirmValidateBill', $object->ref);


							if (!empty($conf->notification->enabled)) {
								require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php';
								$notify = new Notify($this->db);
								$text .= '<br>';
								$text .= $notify->confirmMessage('BILL_VALIDATE', $object->socid, $object);
								$notify->send('BILL_VALIDATE', $object );
							}
						}
					} else {
						if (count($object->errors)) {
							setEventMessages(null, $object->errors, 'errors');
						} else {
							setEventMessages($object->error, $object->errors, 'errors');
						}
					}
					return 1;
					
				//} 
            }
			if ($action == 'add'){
				if ( isset($_POST['options_crlibre_tipodocto']) && $_POST['type'] == 0){
					if ($_POST['options_crlibre_tipodocto'] == 9 )
						$object->array_options['options_crlibre_tipodocto'] = 9;
					if ($_POST['options_crlibre_tipodocto'] == 4 )
						$object->array_options['options_crlibre_tipodocto'] = 4;
				}elseif($_POST['type'] == 0 ){
					$_POST['options_crlibre_tipodocto'] = 1;
				}elseif($_POST['type'] == 2 ){
					$_POST['options_crlibre_tipodocto'] = 3;
				}

			}
        	if ($action == 'xmlquery' ){
				$CRFact = new crfact($this->db);

				$crfactparam = array(
					'userName' => $conf->global->CRFACT_IDENDUSR,
					'pwd' => $conf->global->CRFACT_IDENDPWD,
					'idMasterUser' => $conf->global->CRFACT_MASTERID
				);
				$response = $CRFact->Request('facturador','companny_users_logMeIn',$crfactparam,$conf->global->CRFACT_URL);
				if ( $response->resp == ERROR_USER_WRONG_LOGIN_INFO ){
					setEventMessages($langs->trans("ERROR_USER_WRONG_LOGIN_INFO"), null, 'errors');
					$return = ERROR_USER_WRONG_LOGIN_INFO;
				}else{
					$userName = $response->resp->userName;
					$sessionKey = $response->resp->sessionKey;
					$crfactparam = array(
						'iam' => $userName,
						'sessionKey' => $sessionKey,
						'idMasterUser' => $conf->global->CRFACT_MASTERID
					);
					$response = $CRFact->Request('facturador','company_get_env',$crfactparam,$conf->global->CRFACT_URL);
					if ( is_null($response->resp) ){
						setEventMessages($langs->trans("ERROR_FACTURADORcompany_get_env_REQUEST"), null, 'errors');
						$return = ERROR_FACTURADORcompany_get_env_REQUEST;
					}else{
                   
						if ($response->resp[0]->env === "api-stag") {
							$client_id = "api-stag";
						} else if ($response->resp[0]->env === "api-prod") {
							$client_id = "api-prod";
						}
						if ($client_id == 'api-stag') {
							$r = 'get_stag_companny_credentials';
						} else if ($client_id == 'api-prod') {
							$r = 'get_prod_companny_credentials';
						}
						$crfactparam = array(
							'iam' => $userName,
							'sessionKey' => $sessionKey,
							'idMasterUser' => $conf->global->CRFACT_MASTERID
						);
						$response = $CRFact->Request('facturador',$r,$crfactparam,$conf->global->CRFACT_URL);
						if ( is_null($response->resp) ){
							setEventMessages($langs->trans("'$r'"), null, 'errors');
							$return = ERROR_FACTURADORget_credentials_REQUEST;
						}else{
							$usuario = $response->resp[0]->value;
							$pass = $response->resp[1]->value;
							$crfactparam = array(
								'username' => $usuario,
								'password' => $pass,
								'client_id' => $client_id,
								'grant_type' => 'password'
							);
							setEventMessages($langs->trans("Adquiriendo token del acceso MH..."), null);
							$response = $CRFact->Request('token','gettoken',$crfactparam,$conf->global->CRFACT_URL);
                        //var_dump($response);
							dol_syslog("Trigger for action '$action' launched. gettoken=".json_encode($response));
							if ( is_null($response->resp) ){
                            
								setEventMessages($langs->trans("ERROR_TOKEN_REQUEST".json_encode($response)), null, 'errors');
								$return = ERROR_TOKEN_REQUEST;
							}else{
								$token = $response->resp->access_token;
								$crfactparam = array(
									'token' => $token,
									'clave' => $object->array_options['options_crlibre_clave'],
									'client_id' => $client_id
								);
								setEventMessages($langs->trans("Recibiendo respuesta MH..."), null);
								$response = $CRFact->Request('consultar','consultarCom',$crfactparam,$conf->global->CRFACT_URL);
                            // var_dump($response);
								dol_syslog("Trigger for action '$action' launched. consultarCom=".json_encode($response));
								if ( $response->resp === null ){
									setEventMessages($langs->trans("ERROR_CONSULTAR_REQUEST".json_encode($response)), null, 'errors');
									$return = ERROR_CONSULTAR_REQUEST;
								}else{
									$MHresponse = (array) $response->resp;
									$descargaXMLFirmado = $MHresponse['xml'];
									$descargaXMLClave = $MHresponse['clave'];
									$responseXML = $MHresponse['respuesta-xml'];
									if ($MHresponse['ind-estado'] === "aceptado") {
										$text=utf8_encode(base64_decode($responseXML));
										$filename = DOL_DATA_ROOT.'/facture/'.$object->ref.'/'.$object->ref.'_respuesta.xml';
										unlink($filename);
                                    	mb_internal_encoding('UTF-8');
                                    	$text = mb_convert_encoding($text, 'UTF-8', 'auto');
										file_put_contents($filename, $text, FILE_APPEND | LOCK_EX);
									}else{
                                    	setEventMessages($langs->trans("Comprobante no ha sido aceptado".json_encode($MHresponse['ind-estado'].' '.base64_decode( $MHresponse['respuesta-xml'] ))), null, 'errors');
                                   		$text=utf8_encode(base64_decode($responseXML));
										$filename = DOL_DATA_ROOT.'/facture/'.$object->ref.'/'.$object->ref.'_respuesta.xml';
										unlink($filename);
                                    	mb_internal_encoding('UTF-8');
                                    	$text = mb_convert_encoding($text, 'UTF-8', 'auto');
										file_put_contents($filename, $text, FILE_APPEND | LOCK_EX);
                                    }
								}
							}
						}
					}
				}
			}
			if ($action == 'create'){
			?>
				<script type="text/javascript">
					function readyFn( jQuery ) {
						var elem = document.getElementById('radio_standard');
						if ( elem !== null){
							var options = [TD0 = {'label':'Factura Exportación', 'cod':'9'} , TD1 = {'label':'Tiquete Electrónico', 'cod':'4'}];
							options.forEach(function(tipodoc, index) {
								$(elem).closest('table').append(`<tr><td class="row-index text-center"></td>
          						<td class="row-index text-center">
									<input type="checkbox" class="mhck" id="`+tipodoc.cod+`" name="options_crlibre_tipodocto" value="`+tipodoc.cod+`" >
									<label for="`+tipodoc.cod+`">`+tipodoc.label+`</label>
								</td>
          						</tr>`);
							});
						}
						$('input[class="mhck"]').click(function() {
							if ( $('#radio_standard').is(':checked') ){
								$('input[class="mhck"]').not(this).prop("checked", false);
							}else{
								$('input[class="mhck"]').prop("checked", false);
							}
						});
						$('input[type="radio"]').click(function() {
							var id = $(this).attr('id');
							if (id != 'radio_standard'){
								$('input[class="mhck"]').prop("checked", false);
								$('mhck').hide();
							}
						});
					}
					window.onload = function() {
					readyFn();
					};
				</script>
			<?php
			}
		}
		if (!$error) {
			//$this->results = array('myreturn' => 999);
			//$this->resprints = 'A text to show';
			//return 0; // or return 1 to replace standard code
		} else {
			//$this->errors[] = 'Error message';
			//return -1;
		}
	}


	/**
	 * Overloading the doMassActions function : replacing the parent's function with the one below
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
	 */
	public function doMassActions($parameters, &$object, &$action, $hookmanager)
	{
		global $conf, $user, $langs;

		$error = 0; // Error counter

		/* print_r($parameters); print_r($object); echo "action: " . $action; */
		if (in_array($parameters['currentcontext'], array('productcard', 'somecontext2'))) {		// do something only for the context 'somecontext1' or 'somecontext2'
			foreach ($parameters['toselect'] as $objectid) {
				// Do action on each object id
			}
		}

		if (!$error) {
			$this->results = array('myreturn' => 999);
			$this->resprints = 'A text to show';
			return 0; // or return 1 to replace standard code
		} else {
			$this->errors[] = 'Error message';
			return -1;
		}
	}


	/**
	 * Overloading the addMoreActionsButtons function : replacing the parent's function with the one below
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
	 */
	public function addMoreActionsButtons($parameters, &$object, &$action, $hookmanager)
	{
		global $conf, $user, $langs;
		$error = 0; // Error counter
		/* print_r($parameters); print_r($object); echo "action: " . $action; */
		if (in_array($parameters['currentcontext'], array('invoicesuppliercard'))) {		// do something only for the context 'somecontext1' or 'somecontext2'
			// Validate
			
			//if (($object->statut == FactureFournisseur::STATUS_VALIDATED )) {
				if (empty($object->array_options['options_crlibre_claveconfirm'])){
					$usercanvalidate = ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($usercancreate)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->supplier_invoice_advance->validate)));
					if (count($object->lines)) {
						if ($usercanvalidate) {
							print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=mhaceptacion"';
							print '>'.$langs->trans('MH Aceptacion').'</a>';
						} else {
							print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'"';
							print '>'.$langs->trans('MH Aceptacion').'</a>';
						}
					}
				}
        		// if (($object->statut == FactureFournisseur::STATUS_DRAFT )) {
				// 	$usercancreate = ( !empty($user->rights->fournisseur->facture->creer));
				// 	if (count($object->lines) == 0 ) {
				// 		if ($usercancreate) {
				// 			print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=confirm_loadxml"';
				// 			print '>'.$langs->trans('Carga XML').'</a>';
				// 		} 
				// 	}
				// }
			//}
		}

		if (in_array($parameters['currentcontext'], array('thirdpartycard'))) {		// do something only for the context 'somecontext1' or 'somecontext2'
			if ($conf->crfact->enabled) {
				print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=mhconsulta"';
				print '>'.$langs->trans('MH Consulta').'</a>';
			}
		}

		if (in_array($parameters['currentcontext'], array('invoicecard'))) {		// do something only for the context 'somecontext1' or 'somecontext2'
			if ($conf->crfact->enabled && !empty($object->array_options['options_crlibre_clave']) ) {
				print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=xmlquery"';
				print '>'.$langs->trans('XML Query').'</a>';
			}
		}

		// if (!$error) {
		// 	$this->results = array('myreturn' => 999);
		// 	$this->resprints = 'A text to show';
		// 	return 0; // or return 1 to replace standard code
		// } else {
		// 	$this->errors[] = 'Error message';
		// 	return -1;
		// }
	}
	
	/**
	 * Overloading the addMoreMassActions function : replacing the parent's function with the one below
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
	 */
	public function addMoreMassActions($parameters, &$object, &$action, $hookmanager)
	{
		global $conf, $user, $langs;

		$error = 0; // Error counter
		$disabled = 0;

		//print_r($parameters); print_r($object); echo "action: " . $action; 
		if (in_array($parameters['currentcontext'], array('somecontext1', 'somecontext2'))) {		// do something only for the context 'somecontext1' or 'somecontext2'
			//$this->resprints = '<option value="loadxml"'.($disabled ? ' disabled="disabled"' : '').'>'.$langs->trans("Carga XML").'</option>';
		}

		if (!$error) {
			return 0; // or return 1 to replace standard code
		} else {
			$this->errors[] = 'Error message';
			return -1;
		}
	}
	/**
	 * Execute action printPDFline
	 *
	 * @param	array	$parameters     Array of parameters
	 * @param   Object	$object		   	Object output on PDF
	 * @param   string	$action     	'add', 'update', 'view'
	 * @return  int 		        	<0 if KO,
	 *                          		=0 if OK but we want to process standard actions too,
	 *  	                            >0 if OK and we want to replace standard actions.
	 */
	public function printPDFline($parameters, &$object, &$action)
	{
		global $conf, $user, $langs, $hookmanager;

		$outputlangs = $langs;

		$ret = 0; $deltemp = array();
		dol_syslog(get_class($this).'::executeHooks action='.$action);

		$error = 0; // Error counter
		$context = explode(':', $parameters['context']);

		if (in_array('pdfgeneration', $context)) {

			if ($parameters["object"]->element == 'facture'){
				$style4 = array('L' => 0, 'T' => 0, 'R' => 0,  'B' => 0);
				$parameters["pdf"]->Rect(100, 5, 110, 12.5, 'DF',$style4, array(255, 255, 255));
				
				switch ($parameters["object"]->array_options['options_crlibre_tipodocto']) {
					case 1:	
						$title = 'Factura Electrónica';
						break;
					case 3:	
						$title = 'Nota de Crédito Electrónica';
						break;
					case 4:	
						$title = 'Tiquete Electrónico';
						break;
					case 9:	
						$title = 'Factura Electrónica Exportación';
						break;
					default:
						break;
				}
				$title .= ' '.$outputlangs->convToOutputCharset($parameters["object"]->ref);
				$default_font_size = pdf_getPDFFontSize($outputlangs);
				$parameters["pdf"]->SetFont('', 'B', $default_font_size + 3);
				$parameters["pdf"]->SetXY(99, 7);
				$parameters["pdf"]->SetTextColor(0, 0, 60);
				$parameters["pdf"]->MultiCell($w, 3, $title, '', 'R');

				$parameters["pdf"]->SetFont('', '', $default_font_size - 2);
				$parameters["pdf"]->SetXY(99, 14);
				$parameters["pdf"]->SetTextColor(0, 0, 60);
				$title = $outputlangs->transnoentities("DateInvoice");
				if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && is_object($outputlangsbis)) {
					$title .= ' - '.$outputlangsbis->transnoentities("DateInvoice");
				}
				$parameters["pdf"]->MultiCell($w, 3, $title." :  ".dol_print_date($parameters["object"]->date, "dayhour", false, $outputlangs, true), '', 'R');
			}

			$sql = " SELECT share FROM ".MAIN_DB_PREFIX."ecm_files";
			$sql .= " WHERE entity = ".$conf->entity;
			$sql .= " AND src_object_type = '". $parameters["object"]->element ."' and src_object_id = ".$parameters["object"]->id." ";
			$sql .= " AND share IS NOT NULL ORDER BY rowid DESC LIMIT 1";

			$resql = $this->db->query($sql);
        
			if ($resql) {
				$xobj = $this->db->fetch_object($resql);
				$share = 'https://'.$_SERVER['SERVER_NAME'].'/document.php?hashp='.$xobj->share;
				$style = array(
					'border' => 0,
					'vpadding' => 'auto',
					'hpadding' => 'auto',
					'fgcolor' => array(76, 76, 84),
					'bgcolor' => false, //array(255,255,255)
					'module_width' => 1, // width of a single module in points
					'module_height' => 1 // height of a single module in points
				);
				if ($share){
					// QRCODE,L : QR-CODE Low error correction
					$parameters["pdf"]->write2DBarcode( $share, 'QRCODE,M', 111, 13, 15, 15, $style, 'N');
				}
			}

		}
		return $ret;
	}
	/**
	 * Execute action beforePDFCreation
	 *
	 * @param	array	$parameters     Array of parameters
	 * @param   Object	$object		   	Object output on PDF
	 * @param   string	$action     	'add', 'update', 'view'
	 * @return  int 		        	<0 if KO,
	 *                          		=0 if OK but we want to process standard actions too,
	 *  	                            >0 if OK and we want to replace standard actions.
	 */
	public function beforePDFCreation($parameters, &$object, &$action)
	{
		global $conf, $user, $langs, $hookmanager;

		$outputlangs = $langs;

		$ret = 0; $deltemp = array();
		dol_syslog(get_class($this).'::executeHooks action='.$action);

		$error = 0; // Error counter
		$context = explode(':', $parameters['context']);

		if (in_array('pdfgeneration', $context)) {
			$object->date = $object->date_validation;

		}
		
		return $ret;
	}
	/**
	 * Overloading the loadDataForCustomReports function : returns data to complete the customreport tool
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
	 */
	public function loadDataForCustomReports($parameters, &$action, $hookmanager)
	{
		global $conf, $user, $langs;

		$langs->load("mymodule@mymodule");

		$this->results = array();

		$head = array();
		$h = 0;

		if ($parameters['tabfamily'] == 'mymodule') {
			$head[$h][0] = dol_buildpath('/module/index.php', 1);
			$head[$h][1] = $langs->trans("Home");
			$head[$h][2] = 'home';
			$h++;

			$this->results['title'] = $langs->trans("MyModule");
			$this->results['picto'] = 'mymodule@mymodule';
		}

		$head[$h][0] = 'customreports.php?objecttype='.$parameters['objecttype'].(empty($parameters['tabfamily']) ? '' : '&tabfamily='.$parameters['tabfamily']);
		$head[$h][1] = $langs->trans("CustomReports");
		$head[$h][2] = 'customreports';

		$this->results['head'] = $head;

		return 1;
	}
	/**
	 * Overloading the restrictedArea function : check permission on an object
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int 		      			  	<0 if KO,
	 *                          				=0 if OK but we want to process standard actions too,
	 *  	                            		>0 if OK and we want to replace standard actions.
	 */
	public function restrictedArea($parameters, &$action, $hookmanager)
	{
		global $user;

		if ($parameters['features'] == 'myobject') {
			if ($user->rights->mymodule->myobject->read) {
				$this->results['result'] = 1;
				return 1;
			} else {
				$this->results['result'] = 0;
				return 1;
			}
		}

		return 0;
	}
	/**
	 * Execute action completeTabsHead
	 *
	 * @param   array           $parameters     Array of parameters
	 * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          $action         'add', 'update', 'view'
	 * @param   Hookmanager     $hookmanager    hookmanager
	 * @return  int                             <0 if KO,
	 *                                          =0 if OK but we want to process standard actions too,
	 *                                          >0 if OK and we want to replace standard actions.
	 */
	public function completeTabsHead(&$parameters, &$object, &$action, $hookmanager)
	{
		global $langs, $conf, $user;

		if (!isset($parameters['object']->element)) {
			return 0;
		}
		if ($parameters['mode'] == 'remove') {
			// utilisé si on veut faire disparaitre des onglets.
			return 0;
		} elseif ($parameters['mode'] == 'add') {
			$langs->load('mymodule@mymodule');
			// utilisé si on veut ajouter des onglets.
			$counter = count($parameters['head']);
			$element = $parameters['object']->element;
			$id = $parameters['object']->id;
			// verifier le type d'onglet comme member_stats où ça ne doit pas apparaitre
			// if (in_array($element, ['societe', 'member', 'contrat', 'fichinter', 'project', 'propal', 'commande', 'facture', 'order_supplier', 'invoice_supplier'])) {
			if (in_array($element, ['context1', 'context2'])) {
				$datacount = 0;

				$parameters['head'][$counter][0] = dol_buildpath('/mymodule/mymodule_tab.php', 1) . '?id=' . $id . '&amp;module='.$element;
				$parameters['head'][$counter][1] = $langs->trans('MyModuleTab');
				if ($datacount > 0) {
					$parameters['head'][$counter][1] .= '<span class="badge marginleftonlyshort">' . $datacount . '</span>';
				}
				$parameters['head'][$counter][2] = 'mymoduleemails';
				$counter++;
			}
			if ($counter > 0 && (int) DOL_VERSION < 14) {
				$this->results = $parameters['head'];
				// return 1 to replace standard code
				return 1;
			} else {
				// en V14 et + $parameters['head'] est modifiable par référence
				return 0;
			}
		}
	}
	/**
	 * Overloading the formConfirm function : replacing the parent's function with the one below
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
	 */
	public function formConfirm($parameters, &$object, &$action, $hookmanager)
	{
		global $conf, $user, $langs;

		$error = 0; // Error counter

		if (in_array($parameters['currentcontext'], array('invoicecard'))) {
			if ( ($object->array_options['options_crlibre_tipodocto'] == 4 ) || 
			($object->array_options['options_crlibre_tipodocto'] == 9 ) ){
				$oldnumref = $object->getNextNumRef($soc);
				// we check object has a draft number
				$objectref = substr($object->ref, 1, 4);
				if ($objectref == 'PROV') {
					if (($object->type == Facture::TYPE_STANDARD) && !empty( $object->array_options['options_crlibre_tipodocto']) ) { // empty should not happened, but when it occurs, the test save life
						if ($object->array_options['options_crlibre_tipodocto'] == 4) {
							$prefix = 'TE';
							$mask = $conf->global->CRFACT_MASK_INVOICE_TE;
						} elseif ($object->array_options['options_crlibre_tipodocto'] == 9) {
							$prefix = 'FE';
							$mask = $conf->global->CRFACT_MASK_INVOICE_FEE;
						}
						$where = '';
						$mode = 'next';
						$entity = getEntity('invoicenumber', 1, $object);
	
						$numFinal = get_next_value($this->db, $mask, 'facture', 'ref', $where, $object->thirdparty, $object->date, $mode, false, null, $entity);
	
						$numref = dol_sanitizeFileName($numFinal);
					} 
					// $object->date=$savdate;
				} else {
					$numref = $object->ref;
				}
				$this->resprints = str_replace ($oldnumref,$numref,$parameters['formConfirm']);
				return 1;
			}
		}
		//print_r($parameters); print_r($object); echo "action: " . $action; 
		if (in_array($parameters['currentcontext'], array('invoicesuppliercard'))) {	    // do something only for the context 'somecontext1' or 'somecontext2'
			
			if ($action == 'mhaceptacion'){
				$form = new Form($this->db);
				$numref = $object->ref_supplier;
				$text = 'Desea enviar confirmacion del documento '.$numref.' al Ministerio de Hacienda ?';
	
				$tipoaceptacion = array(
					'05' => 'Aceptacion',
					'06' => 'Aceptacion Parcial',
					'07' => 'Rechazo'
				);
	
				$formquestion = array(
					array('type' => 'text', 'name' => 'numconsec', 'label' => 'Consecutivo de Aceptacion', 'value' => str_pad($object->id, 10, "0", STR_PAD_LEFT),'moreattr' => 'disabled'),
					array('type' => 'select', 'name' => 'idtipoaceptacion', 'label' => 'Tipo de Mensaje de Aceptacion', 'values' => $tipoaceptacion),
					array('type' => 'text', 'name' => 'txtdetalle', 'label' => 'Detalle de Aceptacion', 'value' => ' ', 'morecss' => 'minwidth350', 'moreattr' => 'maxlength="150"'),
				);
				print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('MHAceptacion'), $text, 'mh_accept', $formquestion, 1, 1, 300, 500);
			}
			if ($action == 'confirm_loadxml'){
				
				$form = new Form($this->db);
				$numref = $object->ref_supplier;
				$text = 'Debe cargar el archivo XML.';
	
				$formquestion = array(
					
					array('type' => 'file', 'name' => 'filename', 'label' => 'Archivo XML', 'morecss' => 'minwidth350', 'moreattr' => 'maxlength="150"'),
					array('type' => 'hidden', 'name' => 'filename_content'),
				);
				print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('Carga de XML.'), $text, 'loadxml', $formquestion, 1, 0, 300, 500);


				$jscript ='<script type="text/javascript">'."\n ";
				$jscript .='if (window.File && window.FileReader && window.FileList && window.Blob) {
					document.getElementById(\'filename\').addEventListener(\'change\', handleFileSelect, false);
				} else {
					alert("The File APIs are not fully supported in this browser.");
				}
				function handleFileSelect(evt) {
					var f = evt.target.files[0]; // FileList object
					var reader = new FileReader();
					// Closure to capture the file information.
					reader.onload = (function(theFile) {
					return function(e) {
						var binaryData = e.target.result;
						//Converting Binary Data to base 64
						var base64String = window.btoa(binaryData);
						//showing file converted to base64
						document.getElementById(\'filename_content\').value = base64String;
					};
					})(f);
					// Read in the image file as a data URL.
					reader.readAsBinaryString(f);
				}</script>';
				print $jscript;
			}
		}

		if (!$error) {
			$this->results = array('myreturn' => 999);
			//$this->resprints = 'A text to show';
			return 0; // or return 1 to replace standard code
		} else {
			$this->errors[] = 'Error message';
			return -1;
		}
	}
	/**
	 * Overloading the addMoreMassActions function : replacing the parent's function with the one below
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
	 */
	public function addMoreActionsEmailCollector($parameters, &$object, &$action, $hookmanager)
	{
		global $conf, $user, $langs;
		$error = 0; // Error counter
		$disabled = 1;

		/* print_r($parameters); print_r($object); echo "action: " . $action; */
		if (in_array($parameters['currentcontext'], array('emailcollectorcard'))) {		// do something only for the context 'somecontext1' or 'somecontext2'
			//VAR_DUMP($parameters);
			if ($conf->crfact->enabled) {
				$arrayoftypes['hookfacture'] = 'ImportFactureundProvider';
			}
			//echo '<br>';
			//VAR_DUMP($parameters);
		}

		if (!$error) {
			$this->results = $arrayoftypes;
			return 0; // or return 1 to replace standard code
		} else {
			$this->errors[] = 'Error message';
			return -1;
		}
	}
	/**
	 * Overloading the addMoreMassActions function : replacing the parent's function with the one below
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
	 */
	public function doCollectOneCollector($parameters, &$object, &$action, $hookmanager)
	{
		global $conf, $user, $langs;
		$error = 0; // Error counter
		$disabled = 1;
		
		if ($action == 'hookfacture' ){
			
			if (in_array($parameters['currentcontext'], array('emailcollectorcard'))) {		// do something only for the context 'somecontext1' or 'somecontext2'
				//var_dump($parameters["from"]);
				
				if ($conf->crfact->enabled) {
					$attachments = $parameters["attachments"];
					foreach ($attachments as $attachment => $content) {
						
						if (strpos( strtoupper( $attachment),'.XML') !== false ){
							$comprobante = new SimpleXMLElement($content);
							
							
							if ($comprobante->getName() === 'FacturaElectronica'){
								
								$sql = "SELECT fk_object rowid from ". MAIN_DB_PREFIX . "facture_fourn_extrafields where 
								crlibre_clave = '". $comprobante->Clave ."' ;";
								$rs = $this->db->query($sql);
								$valrs = $this->db->fetch_object($rs);

								if (!is_null($valrs)){
									setEventMessages('El documento '.$comprobante->Clave.' ya fue importado' , null, 'errors');
									return -1 ;
								}
								
								if ( $comprobante->Receptor->Identificacion->Numero != $conf->global->MAIN_INFO_SIREN ){
									setEventMessages('El documento '.$comprobante->Clave.' no corresponde a esta empresa' , null, 'errors');
									return -1 ;
								}
								$thirdpartystatic = new Societe($this->db);
								
								if (strlen($comprobante->Emisor->NombreComercial) > 0 )
									$thirdpartystatic->name = $comprobante->Emisor->NombreComercial;
								else
									$thirdpartystatic->name =  $comprobante->Emisor->Nombre ;
								
								$thirdpartystatic->name_alias = $comprobante->Emisor->Nombre;

								$sql = "SELECT id, code from ". MAIN_DB_PREFIX . "c_typent where code = '".$comprobante->Emisor->Identificacion->Tipo."';";
								$resp = $this->db->query($sql);
								$typent = $this->db->fetch_object($resp);
								$thirdpartystatic->typent_code= $typent->code;
								//$thirdpartystatic->typent_id = $typent->id;
								$thirdpartystatic->pays = 75;
								$thirdpartystatic->country = 'Costa Rica';
								$thirdpartystatic->country_code = 'CR';
								$thirdpartystatic->country_id = 75;
								$thirdpartystatic->multicurrency_code = $comprobante->ResumenFactura->CodigoTipoMoneda->CodigoMoneda;
								$thirdpartystatic->forme_juridique_code =strval((intval($comprobante->Emisor->Identificacion->Tipo)));
								$thirdpartystatic->tva_intra = $comprobante->CodigoActividad;
								$thirdpartystatic->idprof1 = $comprobante->Emisor->Identificacion->Numero;
								$thirdpartystatic->idprof6 = $comprobante->CodigoActividad;
								$thirdpartystatic->zip = $comprobante->Emisor->Ubicacion->Provincia.$comprobante->Emisor->Ubicacion->Canton.$comprobante->Emisor->Ubicacion->Distrito.$comprobante->Emisor->Ubicacion->Barrio;
								$sql = "SELECT rowid, nom from ". MAIN_DB_PREFIX . "c_departements where code_departement = ".$comprobante->Emisor->Ubicacion->Provincia.";";
								$resp = $this->db->query($sql);
								$town = $this->db->fetch_object($resp);
								$thirdpartystatic->town = $town->nom;
								$thirdpartystatic->address = $comprobante->Emisor->Ubicacion->OtrasSenas;
								$thirdpartystatic->phone = $comprobante->Emisor->Telefono->CodigoPais.$comprobante->Emisor->Telefono->NumTelefono;
								$thirdpartystatic->fax = $comprobante->Emisor->Fax->CodigoPais.$comprobante->Emisor->Fax->NumTelefono;
								$thirdpartystatic->email = $comprobante->Emisor->CorreoElectronico;
								$thirdpartystatic->code_fournisseur = 'auto';
								$thirdpartystatic->fournisseur = 1;
								$thirdpartystatic->multicurrency_code = $comprobante->ResumenFactura->CodigoTipoMoneda->CodigoMoneda;
								$thirdpartystatic->note_public = 'Importado por el Colector de email '. date('d-m-Y').'.';

								$thirdpartycontact = new Contact($this->db);
								$thirdpartycontact->entity = $conf->entity;
								if ( strlen($comprobante->Emisor->Nombre) >50){
									$thirdpartycontact->firstname = substr($comprobante->Emisor->Nombre,0,50);
									$thirdpartycontact->lastname = substr($comprobante->Emisor->Nombre,51,100);
								}else{
									$thirdpartycontact->firstname = $comprobante->Emisor->Nombre;
								}
								$thirdpartycontact->address = $comprobante->Emisor->Ubicacion->OtrasSenas;
								$thirdpartycontact->zip = $comprobante->Emisor->Ubicacion->Provincia.$comprobante->Emisor->Ubicacion->Canton.$comprobante->Emisor->Ubicacion->Distrito.$comprobante->Emisor->Ubicacion->Barrio;
								$thirdpartycontact->town = $town->nom;
								$thirdpartycontact->state_id = $town->rowid;
								$thirdpartycontact->phone_pro = $comprobante->Emisor->Telefono->CodigoPais.$comprobante->Emisor->Telefono->NumTelefono;
								$thirdpartycontact->email = $parameters["from"];
								$thirdpartycontact->priv = 0;
								$thirdpartycontact->note_public = 'Importado por el Colector de email '. date('d-m-Y').'.';


								$sql = "SELECT rowid, code_client, client from ". MAIN_DB_PREFIX . "societe where 
								idprof4 = '".$comprobante->Emisor->Identificacion->Numero."'
								or idprof5 = '".$comprobante->Emisor->Identificacion->Numero."'
								or siren = '".$comprobante->Emisor->Identificacion->Numero."'
								or siret = '".$comprobante->Emisor->Identificacion->Numero."' ;";
								$rs = $this->db->query($sql);
								$thirdpartyrs = $this->db->fetch_object($rs);
								if ( is_null( $thirdpartyrs) ) {
									
									$thirdpartyid = $thirdpartystatic->create($user);
									if ($thirdpartyid >= 0) {
										//Crea contacto de facturacion electronica.
										$thirdpartycontact->socid = $thirdpartyid;
										$thirdpartycontactid = $thirdpartycontact->create($user);
									}else{
										setEventMessages('Error en el registro del proveedor '.json_encode($thirdpartystatic->errors) , null, 'errors');
										return -1 ;
									}
								}else{
									$thirdpartystatic->code_client = $thirdpartyrs->code_client;
									$thirdpartystatic->client = $thirdpartyrs->client;
									$thirdpartyid = $thirdpartystatic->update($thirdpartyrs->rowid, $user, 0,0,0,'update');

									if ( $thirdpartyid >=0 ){
										//$resultc = $thirdpartycontact->fetch($comprobante->Emisor->CorreoElectronico);
										$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "socpeople where 
										email = '". $parameters["from"] ."' ;";
										$rs = $this->db->query($sql);
										$contactrs = $this->db->fetch_object($rs);
										if ( is_null($contactrs)) {
											//Crea contacto de facturacion electronica.
											$thirdpartycontact->socid = $thirdpartyrs->rowid;
											$thirdpartycontactid = $thirdpartycontact->create($user);
										}else{
											$thirdpartycontactid = $thirdpartycontact->update($contactrs->rowid, $user,0,'update');
										}
									}else{
										setEventMessages('Error en la actualizacion del contacto del proveedor '. json_encode($thirdpartystatic->errors)  , null, 'errors');
										return -1 ;
									}
									$thirdpartyid = $thirdpartyrs->rowid;
								}
								if ($thirdpartycontactid <= 0){
									setEventMessages('Error en el registro del contacto del proveedor '.$thirdpartycontact->error  , null, 'errors');
									return -1 ;
								}
								//Valida documento a importar
								$sql = "SELECT fk_object rowid from ". MAIN_DB_PREFIX . "facture_fourn_extrafields where 
								crlibre_clave = '". $comprobante->Clave ."' ;";
								$rs = $this->db->query($sql);
								$ffrs = $this->db->fetch_object($rs);
								if (is_null($ffrs)){
									$invoice = new FactureFournisseur($this->db);
									$dateinvoice = dol_mktime(12, 0, 0, date('m'), date('d'), date('Y'));
									$invoice->socid = $thirdpartyid;
									str_replace(" ","T",date('Y-m-d H:i:s'));
									$emision = new DateTime( str_replace("T"," ",$comprobante->FechaEmision));
									
									$invoice->date = dol_mktime(12, 0, 0, $emision->format('m'), $emision->format('d'), $emision->format('Y'));
									if ($comprobante->PlazoCredito > 0 ){
										$emision->modify('+'.$comprobante->PlazoCredito.' day') ;
										$invoice->date_echeance = $emision->format('Y-m-d');
									}

									$invoice->date_pointoftax = $invoice->date;
									$invoice->note_public = 'Importado por el Colector de email '. date('d-m-Y').'.';
									// We do not copy the private note
									$invoice->ref_supplier	= $comprobante->NumeroConsecutivo;

									$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "c_payment_term where code = '". str_pad( $comprobante->CondicionVenta,2,"0", STR_PAD_LEFT) ."';";
									$resp = $this->db->query($sql);
									$payterm = $this->db->fetch_object($resp);
									$invoice->cond_reglement_id	= $payterm->rowid;

									$sql = "SELECT id from ". MAIN_DB_PREFIX . "c_paiement where code = '". str_pad( $comprobante->MedioPago,2,"0", STR_PAD_LEFT) ."';";
									$resp = $this->db->query($sql);
									$pay = $this->db->fetch_object($resp);
									$invoice->mode_reglement_id	= $pay->id;

									if ( $comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio >0){
										$invoice->multicurrency_tx = 1/floatval($comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio);
									}
									
									$invoice->multicurrency_code = $comprobante->ResumenFactura->CodigoTipoMoneda->CodigoMoneda;
									if ($invoice->multicurrency_code == 'CRC'){
										$invoice->tva = $comprobante->ResumenFactura->TotalImpuesto;
										$invoice->total_tva = $comprobante->ResumenFactura->TotalImpuesto;
										$invoice->total_ht = $comprobante->ResumenFactura->TotalVentaNeta;
										$invoice->total_ttc = $comprobante->ResumenFactura->TotalComprobante;
										$invoice->remise = $comprobante->ResumenFactura->TotalDescuentos;
									}else{
										$invoice->tva = $comprobante->ResumenFactura->TotalImpuesto * $comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio;
										$invoice->total_tva = $comprobante->ResumenFactura->TotalImpuesto * $comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio;
										$invoice->total_ht = $comprobante->ResumenFactura->TotalVentaNeta * $comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio;
										$invoice->total_ttc = $comprobante->ResumenFactura->TotalComprobante * $comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio;
										$invoice->remise = $comprobante->ResumenFactura->TotalDescuentos * $comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio;
										$invoice->multicurrency_total_tva = $comprobante->ResumenFactura->TotalImpuesto;
										$invoice->multicurrency_total_ht = $comprobante->ResumenFactura->TotalVentaNeta;
										$invoice->multicurrency_total_ttc = $comprobante->ResumenFactura->TotalComprobante;
									}
									$invoice->statut == FactureFournisseur::STATUS_DRAFT;
									if ($invoice->multicurrency_code == 'CRC'){
										$invoice->libelle = 'Importado por el Colector de email '. date('d-m-Y').'.';
									}else{
										$invoice->libelle = 'Importado por el Colector de email '. date('d-m-Y').'. Modena original del documento {'.$comprobante->ResumenFactura->CodigoTipoMoneda->CodigoMoneda.'}-Tipo de Cambio ['.$comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio.'].';
									}
									// Proprietes particulieres a facture avoir
									$invoice->type = FactureFournisseur::TYPE_STANDARD;
									
									$invoiceid = $invoice->create($user);
									if ($invoiceid < 0) {
										setEventMessages('Error en la creacion de la factura'.$invoice->error  , null, 'errors');
										return -1 ;
									} else {
										$invoice->array_options = array(
											'options_crlibre_clave' => $comprobante->Clave
										);
										$invoice->updateExtraField('crlibre_clave');
										// copy internal contacts
										if ($invoice->copy_linked_contact($thirdpartystatic, 'internal') < 0) {
											$error++;
										} elseif ($object->socid == $invoice->socid) {
											// copy external contacts if same company
											if ($invoice->copy_linked_contact($thirdpartystatic, 'external') < 0) {
												$error++;
											}
										}
									}
									//Create details
									$Product = new Product($this->db);
									
									foreach ($comprobante->DetalleServicio->LineaDetalle as $LineaDetalle => $item) {
										if (!isset($item->Codigo) ){
											setEventMessages('Error en los datos de la factura, no posee codigo de producto CaByS', null, 'errors');
											return -1 ;
										}
										//Crea/Actualiza el producto 
										if ( intval( substr($item->Codigo,0,1)) <= 4 ){
											//Producto
											$Product->type  =  Product::TYPE_PRODUCT;
										}else{
											//Servicio
											$Product->type  =  Product::TYPE_SERVICE;
										}
										$Product->note = $item->Codigo;
										if (is_null($item->CodigoComercial->Codigo)){
											$Product->ref = $item->Codigo;
										}else{
											$Product->ref = $item->CodigoComercial->Tipo.'-'.$item->CodigoComercial->Codigo;
										}

										$Product->description = $item->Detalle;
										$Product->label = $item->Detalle;
										$Product->note_private   = 'Creado apartir de la factura '.$comprobante->clave;
										$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "c_units where code = '".substr($item->UnidadMedida,0,4) ."';";
										$resp = $this->db->query($sql);
										$unidad = $this->db->fetch_object($resp);
										if (is_null($unidad)){
											$sql = "INSERT INTO ".MAIN_DB_PREFIX."c_units 
											( code, scale, label, short_label, unit_type, active) values
											('". substr($item->UnidadMedida,0,4) ."',1,'". $item->UnidadMedida ."','". $item->UnidadMedida ."','qty',1)";
											$resql = $this->db->query($sql);
											if (!$resql) {
												setEventMessages('Error en la creacion del Unidad de medida '. $item->UnidadMedida .'-'.$this->db->lasterror() , null, 'errors');
												return -1 ;
											}else{
												$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "c_units where code = '".substr($item->UnidadMedida,0,4) ."';";
												$resp = $this->db->query($sql);
												$unidad = $this->db->fetch_object($resp);
												$Product->fk_unit  =  $unidad->rowid;
											}
											
										}else{
											$Product->fk_unit  =  $unidad->rowid;
										}
										
										$Product->finished = 1;

										$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "product where 
										note = '".  $item->Codigo ."' or ref = '".  $item->Codigo ."' or ref = '".  $item->CodigoComercial->Tipo.'-'.$item->CodigoComercial->Codigo ."' ;";
										
										$rs = $this->db->query($sql);
										$Productrs = $this->db->fetch_object($rs);
										$omitecrearprodserv =false;
										if (is_null($Productrs)){
											$Product->price_base_type = 'HT';
											$Product->price = $item->PrecioUnitario;
											$Product->price_ttc = $item->PrecioUnitario + ($item->PrecioUnitario * ($item->Impuesto->Tarifa/100));
											$Product->cost_price = $item->PrecioUnitario;
											$Product->default_vat_code = $item->Impuesto->CodigoTarifa;
											$Product->tva_tx = $item->Impuesto->Tarifa;
											$Productid = $Product->create($user,1);
											if ($Productid >0){
												
												if ((strlen($item->Codigo) >= 12 ) && !empty($item->Impuesto->CodigoTarifa) ){
													$sqlinsert = "INSERT INTO ".MAIN_DB_PREFIX.$Product->table_element."_extrafields 
													(fk_object,crlibre_ti,crlibre_c1,crlibre_c2,crlibre_c3,crlibre_c4,crlibre_c5,crlibre_c6,crlibre_c7,crlibre_c8,crlibre_c9) values
													(".$Productid .",'". $item->Impuesto->CodigoTarifa ."','". substr($item->Codigo,0,1)."','".substr($item->Codigo,0,2) ."','".substr($item->Codigo,0,3) ."',
													'".substr($item->Codigo,0,4) ."','".substr($item->Codigo,0,5) ."',
													'".substr($item->Codigo,0,7) ."','".substr($item->Codigo,0,9)."','".substr($item->Codigo,0,11)."','".$item->Codigo."')";
													$resql = $this->db->query($sqlinsert);
													if (!$resql) {
														setEventMessages('Error en la creacion del CaByS '.$this->db->lasterror() , null, 'errors');
														return -1 ;
													}
												}
												$Productrs->rowid = $Productid;
											}else{
												$omitecrearprodserv =true;
												
												//  setEventMessages($comprobante->Clave.' Error en la creacion del producto '.$item->Codigo.' '.$Product->error  , null, 'errors');
												//  return -1 ;
											}
											
										}else{
											$Product->fetch($Productrs->rowid);
										}
										if (!$omitecrearprodserv){
											$Product->add_fournisseur($user,$thirdpartyid, $item->Codigo, $item->Cantidad);
											$Productid = $Product->update($Productrs->rowid ,$user,false,'update');
											if ($Productid >0){
												//setEventMessages('Actualizacion del producto ' , null,'mesgs' );
											}else{
												setEventMessages('Error en la Actualizacion del producto '.$Product->error  , null, 'errors');
												return -1 ;
											}
										}else{
											$Productrs->rowid = 0;
										}

										// echo 'id prod'.$Productrs->rowid;
										// return -1;
										// die;
										//Crea linea de detalle de la factura
										$product_desc = $item->Detalle;
										if ($invoice->multicurrency_code == 'CRC'){
											$pu_ht = $item->PrecioUnitario;
										}else{
											$pu_ht = $item->PrecioUnitario * $comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio;
										}
										$tva_tx = $item->Impuesto->Tarifa;
										$localtax1_tx = 0;
										$localtax2_tx = 0;
										$qty = $item->Cantidad;
										$fk_product =$Productrs->rowid;
										if ( !empty($item->Descuento->MontoDescuento) ) {
											$remise_percent = ($item->Descuento->MontoDescuento/ $item->MontoTotal) * 100;
										}else{
											$remise_percent = 0;
										}
										$date_start = null;
										$date_end = null;
										$ventil ='0';
										$info_bits = '';
										$price_base_type = 'HT';
										$type = $Product->type;
										$rang = $item->NumeroLinea;
										$notrigger =0;
										$array_options = 0;
										$fk_unit = $Product->fk_unit;
										$origin_id =0;
										$pu_ht_devise = 0;
										$ref_supplier = $item->Codigo;
										$special_code = $item->CodigoComercial->Tipo.'-'.$item->CodigoComercial->Codigo;
										$fk_parent_line =0;
										$fk_remise_except =0;

										$result = $invoice->addline($product_desc, $pu_ht, $tva_tx, $localtax1_tx, $localtax2_tx, $qty, $fk_product , $remise_percent, $date_start, $date_end, $ventil, $info_bits, $price_base_type, $type, $rang, $notrigger, $array_options, $fk_unit, $origin_id, $pu_ht_devise, $ref_supplier,$special_code,$fk_parent_line,$fk_remise_except);
										
										if ($result < 0) {
											setEventMessages('Error en la creacion del detalle factura '.$comprobante->Clave.' '.$invoice->error  , null, 'errors');
											return -1 ;
										} else{
											if ( $comprobante->ResumenFactura->TotalIVADevuelto > 0){
												$amount_ht = $comprobante->ResumenFactura->TotalIVADevuelto;
												$desc ='IVA Devuelto';
												$tva_tx = 0; //tipo impuesto es 0% exento
												$discount_type =1;
												$discountid = $thirdpartystatic->set_remise_except($amount_ht, $user, $desc, $tva_tx, $discount_type);
												if ($discountid > 0) {
													$result = $invoice->insert_discount($discountid);
													if ($result < 0) {
														setEventMessages('Error aplicando la devolucion del IVA', $invoice->errors, 'errors');
														return -1 ;
														die ;
													}
												}else{
													setEventMessages('Error en la devolucion del IVA', $thirdpartystatic->errors, 'errors');
													return -1 ;
												}
											}
										}
									}
								}else{
									setEventMessages('Error en el registro del documento: '.$comprobante->NumeroConsecutivo , null, 'errors');
									return -1 ;
								}
								
							}
							if ($comprobante->getName() === 'NotaCreditoElectronica'){

								$sql = "SELECT fk_object rowid from ". MAIN_DB_PREFIX . "facture_fourn_extrafields where 
								crlibre_clave = '". $comprobante->Clave ."' ;";
								$rs = $this->db->query($sql);
								$valrs = $this->db->fetch_object($rs);

								if (!is_null($valrs)){
									setEventMessages('El documento '.$comprobante->Clave.' ya fue importado' , null, 'errors');
									return -1 ;
								}
								
								if ( $comprobante->Receptor->Identificacion->Numero != $conf->global->MAIN_INFO_SIREN ){
									setEventMessages('El documento '.$comprobante->Clave.' no corresponde a esta empresa' , null, 'errors');
									return -1 ;
								}
								$thirdpartystatic = new Societe($this->db);
								
								if (strlen($comprobante->Emisor->NombreComercial) > 0 )
									$thirdpartystatic->name = $comprobante->Emisor->NombreComercial;
								else
									$thirdpartystatic->name =  $comprobante->Emisor->Nombre ;
								
								$thirdpartystatic->name_alias = $comprobante->Emisor->Nombre;

								// $sql = "SELECT id, code from ". MAIN_DB_PREFIX . "c_typent where code = '".$comprobante->Emisor->Identificacion->Tipo."';";
								// $resp = $this->db->query($sql);
								// $typent = $this->db->fetch_object($resp);
								//$thirdpartystatic->typent_code= $typent->code;
								//$thirdpartystatic->typent_id = $typent->id;
								$thirdpartystatic->pays = 75;
								$thirdpartystatic->country = 'Costa Rica';
								$thirdpartystatic->country_code = 'CR';
								$thirdpartystatic->country_id = 75;
								$thirdpartystatic->multicurrency_code = $comprobante->ResumenFactura->CodigoTipoMoneda->CodigoMoneda;
								$thirdpartystatic->forme_juridique_code =strval((intval($comprobante->Emisor->Identificacion->Tipo)));
								$thirdpartystatic->tva_intra = $comprobante->CodigoActividad;
								$thirdpartystatic->idprof1 = $comprobante->Emisor->Identificacion->Numero;
								$thirdpartystatic->idprof6 = $comprobante->CodigoActividad;
								$thirdpartystatic->zip = $comprobante->Emisor->Ubicacion->Provincia.$comprobante->Emisor->Ubicacion->Canton.$comprobante->Emisor->Ubicacion->Distrito.$comprobante->Emisor->Ubicacion->Barrio;
								$sql = "SELECT rowid, nom from ". MAIN_DB_PREFIX . "c_departements where code_departement = ".$comprobante->Emisor->Ubicacion->Provincia.";";
								$resp = $this->db->query($sql);
								$town = $this->db->fetch_object($resp);
								$thirdpartystatic->town = $town->nom;
								$thirdpartystatic->address = $comprobante->Emisor->Ubicacion->OtrasSenas;
								$thirdpartystatic->phone = $comprobante->Emisor->Telefono->CodigoPais.$comprobante->Emisor->Telefono->NumTelefono;
								$thirdpartystatic->fax = $comprobante->Emisor->Fax->CodigoPais.$comprobante->Emisor->Fax->NumTelefono;
								$thirdpartystatic->email = $comprobante->Emisor->CorreoElectronico;
								$thirdpartystatic->code_fournisseur = 'auto';
								$thirdpartystatic->fournisseur = 1;
								$thirdpartystatic->multicurrency_code = $comprobante->ResumenFactura->CodigoTipoMoneda->CodigoMoneda;
								$thirdpartystatic->note_public = 'Importado por el Colector de email '. date('d-m-Y').'.';

								$thirdpartycontact = new Contact($this->db);
								$thirdpartycontact->entity = $conf->entity;
								if ( strlen($comprobante->Emisor->Nombre) >50){
									$thirdpartycontact->firstname = substr($comprobante->Emisor->Nombre,0,50);
									$thirdpartycontact->lastname = substr($comprobante->Emisor->Nombre,51,100);
								}else{
									$thirdpartycontact->firstname = $comprobante->Emisor->Nombre;
								}
								$thirdpartycontact->address = $comprobante->Emisor->Ubicacion->OtrasSenas;
								$thirdpartycontact->zip = $comprobante->Emisor->Ubicacion->Provincia.$comprobante->Emisor->Ubicacion->Canton.$comprobante->Emisor->Ubicacion->Distrito.$comprobante->Emisor->Ubicacion->Barrio;
								$thirdpartycontact->town = $town->nom;
								$thirdpartycontact->state_id = $town->rowid;
								$thirdpartycontact->phone_pro = $comprobante->Emisor->Telefono->CodigoPais.$comprobante->Emisor->Telefono->NumTelefono;
								$thirdpartycontact->email = $parameters["from"];
								$thirdpartycontact->priv = 0;
								$thirdpartycontact->note_public = 'Importado por el Colector de email '. date('d-m-Y').'.';


								$sql = "SELECT rowid, code_client, client from ". MAIN_DB_PREFIX . "societe where 
								idprof4 = '".$comprobante->Emisor->Identificacion->Numero."'
								or idprof5 = '".$comprobante->Emisor->Identificacion->Numero."'
								or siren = '".$comprobante->Emisor->Identificacion->Numero."'
								or siret = '".$comprobante->Emisor->Identificacion->Numero."' ;";
								$rs = $this->db->query($sql);
								$thirdpartyrs = $this->db->fetch_object($rs);
								if ( is_null( $thirdpartyrs) ) {
									
									$thirdpartyid = $thirdpartystatic->create($user);
									if ($thirdpartyid >= 0) {
										//Crea contacto de facturacion electronica.
										$thirdpartycontact->socid = $thirdpartyid;
										$thirdpartycontactid = $thirdpartycontact->create($user);
									}else{
										setEventMessages('Error en el registro del proveedor '.json_encode($thirdpartystatic->errors) , null, 'errors');
										return -1 ;
									}
								}else{
									$thirdpartystatic->code_client = $thirdpartyrs->code_client;
									$thirdpartystatic->client = $thirdpartyrs->client;
									$thirdpartyid = $thirdpartystatic->update($thirdpartyrs->rowid, $user, 0,0,0,'update');

									if ( $thirdpartyid >=0 ){
										//$resultc = $thirdpartycontact->fetch($comprobante->Emisor->CorreoElectronico);
										$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "socpeople where 
										email = '". $parameters["from"] ."' ;";
										$rs = $this->db->query($sql);
										$contactrs = $this->db->fetch_object($rs);
										if ( is_null($contactrs)) {
											//Crea contacto de facturacion electronica.
											$thirdpartycontact->socid = $thirdpartyrs->rowid;
											$thirdpartycontactid = $thirdpartycontact->create($user);
										}else{
											$thirdpartycontactid = $thirdpartycontact->update($contactrs->rowid, $user,0,'update');
										}
									}else{
										setEventMessages('Error en la actualizacion del contacto del proveedor '. json_encode($thirdpartystatic->errors)   , null, 'errors');
										return -1 ;
									}
									$thirdpartyid = $thirdpartyrs->rowid;
								}
								if ($thirdpartycontactid <= 0){
									setEventMessages('Error en el registro del contacto del proveedor '.$thirdpartycontact->error  , null, 'errors');
									return -1 ;
								}
								//Valida documento a importar
								$sql = "SELECT fk_object rowid from ". MAIN_DB_PREFIX . "facture_fourn_extrafields where 
								crlibre_clave = '". $comprobante->Clave ."' ;";
								$rs = $this->db->query($sql);
								$ffrs = $this->db->fetch_object($rs);
								if (is_null($ffrs)){
									$invoice = new FactureFournisseur($this->db);
									$dateinvoice = dol_mktime(12, 0, 0, date('m'), date('d'), date('Y'));
									$invoice->socid = $thirdpartyid;
									str_replace(" ","T",date('Y-m-d H:i:s'));
									$emision = new DateTime( str_replace("T"," ",$comprobante->FechaEmision));
									$invoice->date = dol_mktime(12, 0, 0, $emision->format('m'), $emision->format('d'), $emision->format('Y'));
									if ($comprobante->PlazoCredito > 0 ){
										$emision->modify('+'.$comprobante->PlazoCredito.' day') ;
										$invoice->date_echeance = $emision->format('Y-m-d');
									}
									$invoice->date_pointoftax = $invoice->date;
									$invoice->note_public = $comprobante->InformacionReferencia->Razon .' Importado por el Colector de email '. date('d-m-Y').'.';
									$invoice->note_private = $comprobante->InformacionReferencia->Razon ;
									// We do not copy the private note
									$invoice->ref_supplier	= $comprobante->NumeroConsecutivo;
									
									$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "c_payment_term where code = '". str_pad( $comprobante->CondicionVenta,2,"0", STR_PAD_LEFT) ."';";
									$resp = $this->db->query($sql);
									$payterm = $this->db->fetch_object($resp);
									$invoice->cond_reglement_id	= $payterm->rowid;

									$sql = "SELECT id from ". MAIN_DB_PREFIX . "c_paiement where code = '". str_pad( $comprobante->MedioPago,2,"0", STR_PAD_LEFT) ."';";
									$resp = $this->db->query($sql);
									$pay = $this->db->fetch_object($resp);
									$invoice->mode_reglement_id	= $pay->id;

									if ( $comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio >0){
										$invoice->multicurrency_tx = 1/floatval($comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio);
									}
									
									$invoice->multicurrency_code = $comprobante->ResumenFactura->CodigoTipoMoneda->CodigoMoneda;
									if ($invoice->multicurrency_code == 'CRC'){
										$invoice->tva = $comprobante->ResumenFactura->TotalImpuesto;
										$invoice->total_tva = $comprobante->ResumenFactura->TotalImpuesto;
										$invoice->total_ht = $comprobante->ResumenFactura->TotalVentaNeta;
										$invoice->total_ttc = $comprobante->ResumenFactura->TotalComprobante;
										$invoice->remise = $comprobante->ResumenFactura->TotalDescuentos;
									}else{
										$invoice->tva = $comprobante->ResumenFactura->TotalImpuesto * $comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio;
										$invoice->total_tva = $comprobante->ResumenFactura->TotalImpuesto * $comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio;
										$invoice->total_ht = $comprobante->ResumenFactura->TotalVentaNeta * $comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio;
										$invoice->total_ttc = $comprobante->ResumenFactura->TotalComprobante * $comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio;
										$invoice->remise = $comprobante->ResumenFactura->TotalDescuentos * $comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio;
										$invoice->multicurrency_total_tva = $comprobante->ResumenFactura->TotalImpuesto;
										$invoice->multicurrency_total_ht = $comprobante->ResumenFactura->TotalVentaNeta;
										$invoice->multicurrency_total_ttc = $comprobante->ResumenFactura->TotalComprobante;
									}
									$invoice->statut == FactureFournisseur::STATUS_DRAFT;

									//Documento de referencia en la NC
									$sql = "SELECT fk_object rowid from ". MAIN_DB_PREFIX . "facture_fourn_extrafields where 
									crlibre_clave = '". $comprobante->InformacionReferencia->Numero ."' ;";
									$rs = $this->db->query($sql);
									$frrs = $this->db->fetch_object($rs);
									if (is_null($frrs)){
										$invoice->fk_facture_source = $frrs->rowid;
									}else{
										setEventMessages('No existe factura de referencia para la creacion de la Nota de credito'.$invoice->error  , null, 'errors');
										return -1 ;
									}
									if ($invoice->multicurrency_code == 'CRC'){
										$invoice->libelle = $comprobante->InformacionReferencia->Razon .' Importado por el Colector de email '. date('d-m-Y').'.';
									}else{
										$invoice->libelle = $comprobante->InformacionReferencia->Razon .' Importado por el Colector de email '. date('d-m-Y').'. Modena original del documento {'.$comprobante->ResumenFactura->CodigoTipoMoneda->CodigoMoneda.'}-Tipo de Cambio ['.$comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio.'].';
									}
									// Proprietes particulieres a facture avoir
									$invoice->type = FactureFournisseur::TYPE_CREDIT_NOTE;
									
									$invoiceid = $invoice->create($user);
									if ($invoiceid < 0) {
										setEventMessages('Error en la creacion de la factura'.$invoice->error  , null, 'errors');
										return -1 ;
									} else {
										$invoice->array_options = array(
											'options_crlibre_clave' => $comprobante->Clave
										);
										$invoice->updateExtraField('crlibre_clave');
										// copy internal contacts
										if ($invoice->copy_linked_contact($thirdpartystatic, 'internal') < 0) {
											$error++;
										} elseif ($object->socid == $invoice->socid) {
											// copy external contacts if same company
											if ($invoice->copy_linked_contact($thirdpartystatic, 'external') < 0) {
												$error++;
											}
										}
									}
									//Create details
									$Product = new Product($this->db);
									
									foreach ($comprobante->DetalleServicio->LineaDetalle as $LineaDetalle => $item) {
										if (!isset($item->Codigo) ){
											setEventMessages('Error en los datos de la factura, no posee codigo de producto CaByS', null, 'errors');
											return -1 ;
										}
										//Crea/Actualiza el producto 
										if ( intval( substr($item->Codigo,0,1)) <= 4 ){
											//Producto
											$Product->type  =  Product::TYPE_PRODUCT;
										}else{
											//Servicio
											$Product->type  =  Product::TYPE_SERVICE;
										}
										$Product->note = $item->Codigo;
										if (is_null($item->CodigoComercial->Codigo)){
											$Product->ref = $item->Codigo;
										}else{
											$Product->ref = $item->CodigoComercial->Tipo.'-'.$item->CodigoComercial->Codigo;
										}
										$Product->description = $item->Detalle;
										$Product->label = $item->Detalle;
										$Product->note_private   = 'Creado apartir de la factura '.$comprobante->clave;
										$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "c_units where code = '".substr($item->UnidadMedida,0,4) ."';";
										$resp = $this->db->query($sql);
										$unidad = $this->db->fetch_object($resp);
										if (is_null($unidad)){
											$sql = "INSERT INTO ".MAIN_DB_PREFIX."c_units 
											( code, scale, label, short_label, unit_type, active) values
											('". substr($item->UnidadMedida,0,4) ."',1,'". $item->UnidadMedida ."','". $item->UnidadMedida ."','qty',1)";
											$resql = $this->db->query($sql);
											if (!$resql) {
												setEventMessages('Error en la creacion del Unidad de medida '. $item->UnidadMedida .'-'.$this->db->lasterror() , null, 'errors');
												return -1 ;
											}else{
												$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "c_units where code = '".substr($item->UnidadMedida,0,4) ."';";
												$resp = $this->db->query($sql);
												$unidad = $this->db->fetch_object($resp);
												$Product->fk_unit  =  $unidad->rowid;
											}
											
										}else{
											$Product->fk_unit  =  $unidad->rowid;
										}
										$Product->finished = 1;
										$sql = "SELECT rowid from ". MAIN_DB_PREFIX . "product where 
										note = '".  $item->Codigo ."' ;";
										$rs = $this->db->query($sql);
										$Productrs = $this->db->fetch_object($rs);
										if (is_null($Productrs)){
											$Product->price_base_type = 'HT';
											$Product->price = $item->PrecioUnitario;
											$Product->price_ttc = $item->PrecioUnitario + ($item->PrecioUnitario * ($item->Impuesto->Tarifa/100));
											$Product->cost_price = $item->PrecioUnitario;
											$Product->default_vat_code = $item->Impuesto->CodigoTarifa;
											$Product->tva_tx = $item->Impuesto->Tarifa;
											$Productid = $Product->create($user,1);
											if ($Productid >0){
												
												if ((strlen($item->Codigo) >= 12 ) && !empty($item->Impuesto->CodigoTarifa) ){
													$sqlinsert = "INSERT INTO ".MAIN_DB_PREFIX.$Product->table_element."_extrafields 
													(fk_object,crlibre_ti,crlibre_c1,crlibre_c2,crlibre_c3,crlibre_c4,crlibre_c5,crlibre_c6,crlibre_c7,crlibre_c8,crlibre_c9) values
													(".$Productid .",'". $item->Impuesto->CodigoTarifa ."','". substr($item->Codigo,0,1)."','".substr($item->Codigo,0,2) ."','".substr($item->Codigo,0,3) ."',
													'".substr($item->Codigo,0,4) ."','".substr($item->Codigo,0,5) ."',
													'".substr($item->Codigo,0,7) ."','".substr($item->Codigo,0,9)."','".substr($item->Codigo,0,11)."','".$item->Codigo."')";
													$resql = $this->db->query($sqlinsert);
													if (!$resql) {
														setEventMessages('Error en la creacion del CaByS '.$this->db->lasterror() , null, 'errors');
														return -1 ;
													}
												}
												$Productrs->rowid = $Productid;
											}else{
												$omitecrearprodserv =true;
												// setEventMessages($comprobante->Clave.' Error en la creacion del producto '.$item->Codigo.' '.$Product->error  , null, 'errors');
												// return -1 ;
											}
										}else{
											$Product->fetch($Productrs->rowid);
										}
										if (!$omitecrearprodserv){
											$Product->add_fournisseur($user,$thirdpartyid, $item->Codigo, $item->Cantidad);
											$Productid = $Product->update($Productrs->rowid ,$user,false,'update');
											if ($Productid >0){
												//setEventMessages('Actualizacion del producto ' , null,'mesgs' );
											}else{
												setEventMessages('Error en la Actualizacion del producto '.$Product->error  , null, 'errors');
												return -1 ;
											}
										}else{
											$fk_product =$Productrs->rowid;
										}
										//Crea linea de detalle de la factura
										$product_desc = $item->Detalle;
										if ($invoice->multicurrency_code == 'CRC'){
											$pu_ht = $item->PrecioUnitario;
										}else{
											$pu_ht = $item->PrecioUnitario * $comprobante->ResumenFactura->CodigoTipoMoneda->TipoCambio;
										}
										$tva_tx = $item->Impuesto->Tarifa;
										$localtax1_tx = 0;
										$localtax2_tx = 0;
										$qty = $item->Cantidad;
										$fk_product =$Productrs->rowid;
										if ( !empty($item->Descuento->MontoDescuento) ) {
											$remise_percent = ($item->Descuento->MontoDescuento/ $item->MontoTotal) * 100;
										}else{
											$remise_percent = 0;
										}
										$date_start = null;
										$date_end = null;
										$ventil ='0';
										$info_bits = '';
										$price_base_type = 'HT';
										$type = $Product->type;
										$rang = $item->NumeroLinea;
										$notrigger =0;
										$array_options = 0;
										$fk_unit = $Product->fk_unit;
										$origin_id =0;
										$pu_ht_devise = 0;
										$ref_supplier = $item->Codigo;
										$special_code = $item->CodigoComercial->Tipo.'-'.$item->CodigoComercial->Codigo;
										$fk_parent_line =0;
										$fk_remise_except =0;

										$result = $invoice->addline($product_desc, $pu_ht, $tva_tx, $localtax1_tx, $localtax2_tx, $qty, $fk_product , $remise_percent, $date_start, $date_end, $ventil, $info_bits, $price_base_type, $type, $rang, $notrigger, $array_options, $fk_unit, $origin_id, $pu_ht_devise, $ref_supplier,$special_code,$fk_parent_line,$fk_remise_except);
										
										if ($result < 0) {
											setEventMessages('Error en la creacion del detalle factura '.$comprobante->Clave.' '.$invoice->error  , null, 'errors');
											return -1 ;
										} else{
											if ( $comprobante->ResumenFactura->TotalIVADevuelto > 0){
												$amount_ht = $comprobante->ResumenFactura->TotalIVADevuelto;
												$desc ='IVA Devuelto';
												$tva_tx = 0; //tipo impuesto es 0% exento
												$discount_type =1;
												$discountid = $thirdpartystatic->set_remise_except($amount_ht, $user, $desc, $tva_tx, $discount_type);
												if ($discountid > 0) {
													$result = $invoice->insert_discount($discountid);
													if ($result < 0) {
														setEventMessages('Error aplicando la devolucion del IVA', $invoice->errors, 'errors');
														return -1 ;
														die ;
													}
												}else{
													setEventMessages('Error en la devolucion del IVA', $thirdpartystatic->errors, 'errors');
													return -1 ;
												}
											}
										}
									}
								}else{
									//setEventMessages('Error en el registro del documento: '.$comprobante->NumeroConsecutivo , null, 'errors');
									//return -1 ;
								}
								
							}
						}
					}
					if ($invoiceid > 0) {
						$attachments = $parameters["attachments"];
						foreach ($attachments as $attachment => $content) {
							$objectref = dol_sanitizeFileName($invoice->ref);
							$objectrefsupplier = dol_sanitizeFileName($invoice->ref_supplier);
							$dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($invoice->id, 2, 0, 0, $invoice, 'invoice_supplier').$objectref;
							$file = $dir."/".$attachment;
							if (!empty($conf->global->SUPPLIER_REF_IN_NAME)) {
								$file = $dir."/".($objectrefsupplier ? "_".$objectrefsupplier : "").$attachment;
							}

							if (!file_exists($dir)) {
								if (dol_mkdir($dir) < 0) {
									setEventMessages('Error en el registro de los documentos, no se pudo agregar el directorio' , null, 'errors');
									return -1 ;
								}
							}
							if (file_exists($dir)) {
                            	$content = mb_convert_encoding($content, 'UTF-8', 'auto');
								$result = file_put_contents($file, $content, FILE_APPEND | LOCK_EX);
								if (!empty($conf->global->MAIN_UMASK)) {
									@chmod($file, octdec($conf->global->MAIN_UMASK));
								}
								if ($result ===false){
									setEventMessages('Error en el registro de los documentos' , null, 'errors');
									return -1 ;
								}
							}
							$destfull =$file;
							$upload_dir = dirname($destfull);
							$destfile = basename($destfull);
							$rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);

							include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
							$ecmfile = new EcmFiles($this->db);
							$result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$file);

							if ($result > 0) {
								$ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
								$ecmfile->fullpath_orig = '';
								$ecmfile->gen_or_uploaded = 'uploaded';
								$ecmfile->description = ''; // indexed content
								$ecmfile->keywords = ''; // keyword content
								$result = $ecmfile->update($user);
								if ($result < 0) {
									setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
									return -1 ;
								}
							} else {
								$ecmfile->entity = $conf->entity;
								$ecmfile->filepath = $rel_dir;
								$ecmfile->filename = $file;
								$ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
								$ecmfile->fullpath_orig = '';
								$ecmfile->gen_or_uploaded = 'uploaded';
								$ecmfile->description = ''; // indexed content
								$ecmfile->keywords = ''; // keyword content
								$ecmfile->src_object_type = $invoice->table_element;	// $this->table_name is 'myobject' or 'mymodule_myobject'.
								$ecmfile->src_object_id   = $invoice->id;

								$result = $ecmfile->create($user);
								if ($result < 0) {
									setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
									return -1 ;
								}else{
									$sql = 'UPDATE '.MAIN_DB_PREFIX.$invoice->table_element." SET last_main_doc = '".$this->db->escape($ecmfile->filepath.'/'.$ecmfile->filename)."'";
									$sql .= ' WHERE rowid = '.$invoice->id;

									$resql = $this->db->query($sql);
									if (!$resql) {
										setEventMessages('Error en la actualizacion de last document', 'warnings');
										dol_print_error($this->db);
										return -1 ;
									} else {
										$invoice->last_main_doc = $ecmfile->filename;
									}
								}
							}
							
						}
					}
				}
			}
		}
		if (!$error) {
			//$this->results = $arrayoftypes;
			return 0; // or return 1 to replace standard code
		} else {
			$this->errors[] = 'Error message';
			return -1;
		}
	}



	/**
	 * Overloading the formatNotificationMessage function : replacing the parent's function with the one below
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
	 */
	public function formatNotificationMessage($parameters, &$object, &$action, $hookmanager)
	{
		global $conf, $user, $langs;

		$error = 0; // Error counter

		/* print_r($parameters); print_r($object); echo "action: " . $action; */
		if (in_array($parameters['currentcontext'], array('invoicecard'))) {	    // do something only for the context 'somecontext1' or 'somecontext2'
			
			if ($action == 'confirm_valid' ){
				// ************
				///////   Asegurar que el notify.class reciba el parametro para multiples archivos a enviar..../
				/////*********** */
				// die;
				dol_syslog(" LOG MOdify files >>> ");

				if ( strlen(trim($object->array_options['options_crlibre_clave']) ) > 0){
					$clave = $object->array_options['options_crlibre_clave'];
					
					$code = $object->ref;
					$pdf_path = DOL_DATA_ROOT .'/'.$object->last_main_doc;
					if ( file_exists($pdf_path) ) {
						$files['file'] = array(
							'0' => DOL_DATA_ROOT.'/facture/'.$code.'/'.$code.'_firmado.xml',
							'1' => DOL_DATA_ROOT.'/facture/'.$code.'/'.$code.'_respuesta.xml',
							'2' => DOL_DATA_ROOT.'/facture/'.$code.'/'.$code.'.pdf',
						);
						$files['mimefile'] = array(
							'0' => 'text/xml',
							'1' => 'text/xml',
							'2' => 'application/pdf'
						);
						$files['filename'] = array(
							'0' => $code.'_firmado.xml',
							'1' => $code.'_respuesta.xml',
							'2' => $code.'.pdf'
						);
						$hookmanager->resArray['files'] =$files;
						return 0;
					}	
				}
			}	
		}

		if (!$error) {
			//$this->results = array('myreturn' => 999);
			//$this->resprints = 'A text to show';
			//return 0; // or return 1 to replace standard code
		} else {
			//$this->errors[] = 'Error message';
			//return -1;
		}
	}

	/**
	 * Execute action
	 *
	 * @param	array	$parameters     Array of parameters
	 * @param   Object	$pdfhandler     PDF builder handler
	 * @param   string	$action         'add', 'update', 'view'
	 * @return  int 		            <0 if KO,
	 *                                  =0 if OK but we want to process standard actions too,
	 *                                  >0 if OK and we want to replace standard actions.
	 */
	public function afterPDFCreation($parameters, &$pdfhandler, &$action)
	{
		global $conf, $user, $langs;
		global $hookmanager;

		$outputlangs = $langs;

		$ret = 0; $deltemp = array();
		dol_syslog(get_class($this).'::executeHooks action='.$action);

		// /* print_r($parameters); print_r($object); echo "action: " . $action; */
		// if (in_array($parameters['currentcontext'], array('invoicecard', 'somecontext2'))) {
		// 	if ($action == 'confirm_valid' ){
		// 		dol_syslog(" RMME afterPDFCreation LOG MOdify files  ");
		// 		$myobject = $parameters["object"];
		// 		// echo '<pre>';
		// 		// var_dump($myobject);
		// 		// echo '</pre>';
		// 		if ( strlen(trim($myobject->array_options['options_crlibre_clave']) ) > 0){
		// 			$text = $langs->trans('ConfirmValidateBill', $myobject->ref);
		// 			if (!empty($conf->notification->enabled)) {
		// 				require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php';
		// 				$notify = new Notify($this->db);
		// 				$text .= '<br>';
		// 				$text .= $notify->confirmMessage('BILL_VALIDATE', $myobject->socid, $myobject);
		// 				$notify->send('BILL_VALIDATE', $myobject );
		// 			}
		// 		}
		// 	}
		// }

		return $ret;
	}


	/**
	 * Execute action
	 *
	 * @param	array	$parameters     Array of parameters
	 * @param   Object	$object		   	Object output on PDF
	 * @param   string	$action     	'add', 'update', 'view'
	 * @return  int 		        	<0 if KO,
	 *                          		=0 if OK but we want to process standard actions too,
	 *  	                            >0 if OK and we want to replace standard actions.
	 */
	public function sendMail($parameters, &$object, &$action)
	{
		global $conf, $user, $langs;
		global $hookmanager;
		
		$outputlangs = $langs;

		$ret = 0; $deltemp = array();
		dol_syslog(get_class($this).'::executeHooks action='.$action);

		return $ret;
	}

	/**
	 * Overloading the afterLogin function : replacing the parent's function with the one below
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
	 */
	public function afterLogin($parameters, &$object, &$action, $hookmanager)
	{
 		global $conf, $user, $langs;
		
 		$error = 0; // Error counter

 		/* print_r($parameters); print_r($object); echo "action: " . $action; */
 		if (in_array($parameters['currentcontext'], array('login'))) {	    // do something only for the context 'somecontext1' or 'somecontext2'
			
 			$_SESSION['dol_tz'] = -6;
 			$_SESSION['dol_tz_string'] ="America/Costa_Rica";
 			$_SESSION['dol_screenheight'] =  1204 ;
 			$_SESSION['dol_screenwidth'] = 768;
// 			$sock = file_get_contents("https://frasedeldia.azurewebsites.net/api/phrase");
// 			if (!$sock) {
// 				echo "$errstr ($errno)<br/>\n"; ##Error si no ha sido posible
// 			} else{
// 				$response = json_decode($sock, true);
// 				$texto_final= '<p><strong>&ldquo;'.$response['phrase'] .'&rdquo;<strong></p><p style="text-align: right;"><em><strong> '. $response['author'].'</strong></em></p>';
// 				dolibarr_set_const($this->db, "MAIN_MOTD", $texto_final, 'chaine', 0, '', $conf->entity);

// 			}

			
 		}

		 if (!$error) {
			//$this->results = $arrayoftypes;
			return 0; // or return 1 to replace standard code
		} else {
			$this->errors[] = 'Error message';
			return -1;
		}
	}


	/**
	 * Overloading the setHtmlTitle function : replacing the parent's function with the one below
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
	 */
	public function setHtmlTitle($parameters, &$object, &$action, $hookmanager)
	{

		$error = 0; // Error counter
		if (!$error) {
			//$this->results = $arrayoftypes;
			return 0; // or return 1 to replace standard code
		} else {
			$this->errors[] = 'Error message';
			return -1;
		}
	}



	/**
	 * Overloading the getLoginPageOptions function : replacing the parent's function with the one below
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
	 */
	public function getLoginPageOptions($parameters, &$object, &$action, $hookmanager)
	{
// 		global $conf, $user, $langs;
		$error = 0; // Error counter
// 		$semana=date("D");

// 		$semanaarray=array("Mon" =>"lunes", "Tue" => "martes", "Wed" => "miércoles", "Thu" => "jueves" , "Fri" => "viernes", "Sat" => "sábado", "Sun" => "domingo");
		
// 		$diadelasemana=$semanaarray[$semana];
// 		$title=urlencode(sprintf('{{Plantilla:Frase-%s}}',$diadelasemana));

// 		$url='http://es.wikiquote.org/w/api.php?action=parse&format=php&text='.$title;
// 		$cadena=fopen($url,"r");
// 		//$cadena= stream_get_contents($cadena, -1);
		
// 		if($cadena){
// 			$array_x =  unserialize( stream_get_contents($cadena, -1) );
			
// 			$texto_html=$array_x["parse"]["text"]["*"];
			
// 			$texto = strip_tags( $texto_html , "<br><small>") ;
// 			require_once DOL_DOCUMENT_ROOT . "/core/lib/admin.lib.php";
// 			dolibarr_set_const($this->db, "MAIN_HOME", '<strong>'.$texto. '</strong>', 'chaine', 0, '', $conf->entity);
		
// 		}
		if (!$error) {
			// $this->results = array('myreturn' => 999);
			// $this->resprints = 'A text to show';
			return 0; // or return 1 to replace standard code
		} else {
			$this->errors[] = 'Ocurrio un error en crfact::formAddObjectLine';
			return -1;
		}
	}
	
	/**
	 * Overloading the formAddObjectLine function : replacing the parent's function with the one below
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
	 */
	public function formAddObjectLine($parameters, &$object, &$action, $hookmanager)
	{
		global $conf, $user, $langs, $extrafields;
		$error = 0; // Error counter
		//print_r($parameters); 
		//echo '<pre>';print_r($object->thirdparty->array_options['options_exo_tipdocto']);echo '</pre>';
		//echo '<pre>';print_r($object);echo '</pre>';
		// echo "action: " . $action; 

		if (in_array($parameters['currentcontext'], array('propalcard','ordercard'))) {		// do something only for the context 'somecontext1' or 'somecontext2'
			if ($object->array_options['options_ind_exonera']) {

				$_POST['options_exo_fechaemision']= date('d-m-Y',intval($object->thirdparty->array_options['options_fechaautexo']));
				$_POST['options_exo_fechaemisionmonth']= date('m',intval($object->thirdparty->array_options['options_fechaautexo']));
				$_POST['options_exo_fechaemisionday']=  date('d',intval($object->thirdparty->array_options['options_fechaautexo']));
				$_POST['options_exo_fechaemisionyear']=   date('Y',intval($object->thirdparty->array_options['options_fechaautexo']));
				$_POST['options_exo_tipdocto']= $object->thirdparty->array_options['options_exo_tipdocto'];
				$_POST['options_exo_numaut']= $object->thirdparty->array_options['options_numautexo'];
				$_POST['options_exo_emisor']= $object->thirdparty->array_options['options_exo_emisor'];
			}
		}

		if (!$error) {
			// $this->results = array('myreturn' => 999);
			// $this->resprints = 'A text to show';
			return 0; // or return 1 to replace standard code
		} else {
			$this->errors[] = 'Ocurrio un error en crfact::formAddObjectLine';
			return -1;
		}
	}


	/**
	 * Overloading the createFrom function : replacing the parent's function with the one below
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
	 */
	public function createFrom($parameters, &$object, &$action, $hookmanager)
	{
		global $conf, $user, $langs, $extrafields;
		$error = 0; // Error counter
		$errmsg = array();
		//print_r($parameters); 
		//echo '<pre>';print_r($object->thirdparty->array_options['options_exo_tipdocto']);echo '</pre>';
		//echo '<pre>';print_r($object);echo '</pre>';
		// echo "action: " . $action; 
		
		if (in_array($parameters['currentcontext'], array('invoicecard'))) {		// do something only for the context 'somecontext1' or 'somecontext2'
			$object->fetch_lines();
			$lines = $object->lines;
			foreach ($lines as $detail => $value){
				$resp = $object->updateline(
					$value->id,
					$value->description,
					$value->subprice,
					$value->qty,
					$value->remise,
					$value->date_start,
					$value->date_end,
					$value->tva_tx,
					$value->flocaltax1_tx,
					$value->flocaltax2_tx,
					'HT',
					$value->finfo_bits,
					$value->fproduct_type,
					$value->fk_parent_line,
					0,
					$value->fk_fournprice,
					$value->pa_ht,
					$value->label,
					$value->special_code,
					$value->array_options,
					$value->situation_percent,
					$value->fk_unit,
					$value->multicurrency_subprice
				);
				if ($resp <= 0 ){
					$error ++;
					$errmsg[] =$object->error;
				}
			}
			
		}

		if (!$error) {
			$this->results = array('myreturn' => 999);
			$this->resprints = 'A text to show';
			return 0; // or return 1 to replace standard code
		} else {
			$this->errors[] = $errmsg;
			return -1;
		}
	}

}

Hry