<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Dian_edx {
	public $param;
	public $pdf;
	private $CI;
	public $_tipoDeComprobanteId;
	public function __construct (){
		$this->param = 'PDB';
		$this->pdf = 'PDF';
		$this->CI = & get_instance();
		$this->session = $this->CI->session;
		$this->CI->load->model('Customer');
		$this->CI->load->model('Sale');
		$this->CI->load->model('Employee');
		$this->_tipoDeComprobanteId = 01; // TEST

		$this->cart = PHPPOSCartSale::get_instance('sale');
	}

	//================================================================================= EDX
		function generate($saved_sale_info) {

				$this->IniciarSesion();

				$_invoice = $this->CI->Sale->get_info($saved_sale_info['sale_id'])->row();
				$cInfo = $this->CI->Customer->get_info($_invoice->customer_id);

				if (!$cInfo->person_id) {
					return false;die();
				}
				$_tienda = $this->CI->Employee->get_logged_in_employee_current_location_id();
			
				$_dCnfg = ($_lIf = get_any_table('dian_cfg','*',['location_id' => $_tienda ]))? $_lIf[0]:false;

				if (!$_dCnfg) {
					return false;die();
				}

				$_tienda = $this->CI->Employee->get_logged_in_employee_current_location_id();
				if (!get_any_table('phppos_locations','*',['location_id'=>$_tienda])) {
					return false;die();
				}

	    		$_join = ['items it', 'si.item_id', 'it.item_id', 'inner'];

				$_items = get_any_table('sales_items si','*',['si.sale_id'=>$saved_sale_info['sale_id']], $_join,[['line','ASC']]);
				
				$_nroDian = ($_nroInvoice = get_any_table('phppos_dian_corr di','*',['prefix'=>$_dCnfg->prefix, $_dCnfg->profile], false,[],1))? $_nroInvoice[0]->dian_id: 0 ;

				$_taxsubtotal =[];
				foreach ($_items as $kk => $val) {
					$_tax_percent = round(($val->tax/$val->subtotal)*100,0);
					if (!isset($_taxsubtotal[$_tax_percent] )) {
						$_taxsubtotal[$_tax_percent] = [];
					}
					$_taxsubtotal[$_tax_percent] += ['TaxableAmount' => round($val->subtotal,2),'TaxAmount' => round($val->tax,2)];
				}

				$_lines = count($_items);
				$_invoiceControl = getInvoiceControl();
				
				$this->_tipoDeComprobanteId = 01; $_prefix = false;
				if ($_invoice->total < 0) {
					$this->_tipoDeComprobanteId = 02;
					$_invoiceControl->Prefix = $_dCnfg->prefix_nc;
					$_prefix = $_invoiceControl->Prefix;
				}

				$_payment_type = explode(':', $_invoice->payment_type);

				if(!($_correl = writeCorr($_invoiceControl->Prefix, $_dCnfg->profile))) {
					die('Dan_edx L-65 Ocurrio un error inesperado ....');
				}


				$dataXmlInvoice =['InvoiceControl' => $_invoiceControl];
				$dataXmlInvoice['InvoiceControl']->schemeID = $_dCnfg->profile;
				$dataXmlInvoice['InvoiceControl']->DianId = $_correl;
				$dataXmlInvoice['InvoiceControl']->ID = $_invoiceControl->Prefix.$dataXmlInvoice['InvoiceControl']->DianId;
				$dataXmlInvoice['InvoiceControl']->LineCountNumeric = $_lines;
				$dataXmlInvoice['InvoiceControl']->InvoicePeriod_StartDate = date('Y-m-d',strtotime($_invoice->sale_time));
				$dataXmlInvoice['InvoiceControl']->InvoicePeriod_EndDate = Sumar_Mes(date('Y-m-d',strtotime($_invoice->sale_time)),$dataXmlInvoice['InvoiceControl']->VigenciaTicket);
				$dataXmlInvoice['InvoiceControl']->PaymentMeansCode = dianPrms()->salePaymentCode[$_payment_type[0]];
				$dataXmlInvoice['InvoiceControl']->LineExtensionAmount = $_invoice->subtotal;
				$dataXmlInvoice['InvoiceControl']->TaxExclusiveAmount = $_invoice->tax;
				$dataXmlInvoice['InvoiceControl']->TaxInclusiveAmount = $_invoice->total;
				$dataXmlInvoice['InvoiceControl']->TaxableAmount = $_invoice->subtotal;
				$dataXmlInvoice['InvoiceControl']->TaxAmount = $_invoice->tax;
				$dataXmlInvoice['InvoiceControl']->TaxSubtotal = $_taxsubtotal;
				$dataXmlInvoice['InvoiceControl']->Total = $_invoice->total;
				$dataXmlInvoice['InvoiceControl']->lines = $_items;
				$dataXmlInvoice['InvoiceControl']->employeeFullName = $this->CI->Employee->get_logged_in_employee_info()->full_name;
				$dataXmlInvoice['InvoiceControl']->tipoComprobanteId = $this->_tipoDeComprobanteId;
				
				$dataXmlInvoice['Supplier'] = getSupplierParty($_prefix);
				$dataXmlInvoice['Customer'] = getCustomerParty($cInfo);

				$_prm = (object) [
				//'nit'=>$cInfo->account_number, 
				'nit' => $dataXmlInvoice['Supplier']->PartyLegalEntityNIT,
				'puntoDeVentaId' => $_dCnfg->pto_venta,
				'tipoDeComprobanteId' => $this->_tipoDeComprobanteId,
				'formatoId' => $_dCnfg->formato_id,
				'SesionId' => $this->session->userdata('ws_sesionid'),
				'FechaVencimiento' =>  $this->session->userdata('ws_fechavencimiento'),
				];

				$_xml = $this->CI->load->view("edx_elements/xml_invoice",$dataXmlInvoice,true);

				/*$_prm->XML ='<?xml version="1.0" encoding="utf-8"?>'. str_replace(['<','>'], ['&lt;','&gt;'], $_xml);*/
				$_prm->XML = str_replace(['<','>'], ['&lt;','&gt;'], $_xml);

				//log_message('error', 'Sales CTRLR L1956  XXXX'.$_prm->XML.'XXXX');
				$doc = new DOMDocument();
				libxml_use_internal_errors(true);
				$doc->loadHTML(callWS('AutorizarComprobantesAsincronico', $_prm));
				libxml_clear_errors();
				$xml = $doc->saveXML($doc->documentElement);
				$xml = simplexml_load_string($xml);

				$_xml = $xml->body->envelope->body->autorizarcomprobantesasincronicoresponse->autorizarcomprobantesasincronicoresult;
				$_xml = simplexml_load_string($_xml);

				writeDianId($dataXmlInvoice['InvoiceControl']->DianId, $saved_sale_info['location_id'], $saved_sale_info['sale_id'], $_xml->Transaccion->ID);
			
				$_trans = (array)$_xml->Transaccion->ID;

				if(getPrintInvoice()){
					if ($this->salidaTransaccion($_trans[0], $dataXmlInvoice['Supplier']->PartyLegalEntityNIT)) {
						$this->DescargarPdf ($_invoice->customer_id,$_xml->Transaccion->ID);			
					}else{
						print_r('ocurrio un error salidaTransaccion Nr '.$_trans[0].' L106');
					}
				}

		}

		function DescargarPdf ($_customer_id,$_transaccionId) {
			if (!fEnRango($this->session->userdata('ws_fechavencimiento'))) {
				$doc = new DOMDocument();
				libxml_use_internal_errors(true);
				$doc->loadHTML(callWS('IniciarSesion', getComfiarUser()));
				libxml_clear_errors();
				$xml = $doc->saveXML($doc->documentElement);
				$xml = simplexml_load_string($xml);

				$_resp = [];
				if(@$xml->body->envelope->body->iniciarsesionresponse->iniciarsesionresult->sesionid){
					$this->session->set_userdata("ws_sesionid", (string)$xml->body->envelope->body->iniciarsesionresponse->iniciarsesionresult->sesionid);
					$this->session->set_userdata("ws_fechavencimiento", (string)$xml->body->envelope->body->iniciarsesionresponse->iniciarsesionresult->fechavencimiento);
				}else{
					$error = true;
					$_error[] =  (string)$xml->body->envelope->body->fault->faultstring;
				}
			}
			
			if (@$error) {
				foreach ($_error as $val) {
					$this->_reload(array('error' => $val));
				}
				$error = false;
				return;
			}

			$_tienda = $this->CI->Employee->get_logged_in_employee_current_location_id();
			$_dInfo = ($_dIf = get_any_table('dianid di','*',['location_id' => $_tienda, 'di.tran_id' => $_transaccionId]))? $_dIf[0]:false;
			$_dCnfg = ($_lIf = get_any_table('dian_cfg','*',['location_id' => $_dInfo->location_id ]))? $_lIf[0]:false;

			if ($_dInfo) {
				$_prm = (object) [
				'transaccionId' => $_transaccionId,
				'cuitId' => $_dCnfg->cia_nit, 
				'puntoDeVentaId' => $_dCnfg->pto_venta,
				'tipoComprobanteId' => $this->_tipoDeComprobanteId, 
				'numeroComprobante' => $_dInfo->dian_id,
				'SesionId' => $this->session->userdata('ws_sesionid'),
				'FechaVencimiento' =>  $this->session->userdata('ws_fechavencimiento')
				];

				$doc = new DOMDocument();
				libxml_use_internal_errors(true);
				$doc->loadHTML(callWS('DescargarPdf', $_prm));
				libxml_clear_errors();
				$xml = $doc->saveXML($doc->documentElement);
				$xml = simplexml_load_string($xml);

				if ($_pdfInvoice = @$xml->body->envelope->body->descargarpdfresponse->descargarpdfresult) {
					
					$pdf_decoded = base64_decode ($_pdfInvoice);
					//Write data back to pdf file
					/*$pdf = fopen ('test.pdf','w');
					fwrite ($pdf,$pdf_decoded);
					//close output file
					fclose ($pdf);*/
					header('Content-Type: application/pdf');
					echo $pdf_decoded;

				}else{
					print_r('Sales CTRLR L201 DescargarPdf: '.((string) $xml));
					log_message('error','Sales CTRLR L175 DescargarPdf: '.((string) $xml));	
				}
				
			}else{
				$error = true;
			}

			return;
		}


		function ultimoComprobante(){
			$error = false; $_error = [];
			
			if (!fEnRango($this->session->userdata('ws_fechavencimiento'))) {
				$doc = new DOMDocument();
				libxml_use_internal_errors(true);
				$doc->loadHTML(callWS('IniciarSesion', getComfiarUser()));
				libxml_clear_errors();
				$xml = $doc->saveXML($doc->documentElement);
				$xml = simplexml_load_string($xml);

				$_resp = [];
				if(@$xml->body->envelope->body->iniciarsesionresponse->iniciarsesionresult->sesionid){
					$this->session->set_userdata("ws_sesionid", (string)$xml->body->envelope->body->iniciarsesionresponse->iniciarsesionresult->sesionid);
					$this->session->set_userdata("ws_fechavencimiento", (string)$xml->body->envelope->body->iniciarsesionresponse->iniciarsesionresult->fechavencimiento);
				}else{
					$error = true;
					$_error[] =  (string)$xml->body->envelope->body->fault->faultstring;
				}
			}
			
			if ($error) {
				foreach ($_error as $val) {
					$this->_reload(array('error' => $val));
				}
				$error = false;
				return;
			}


			$_prm = (object) [
			'cuitId' => $this->config->item('tax_id'), 
			'puntoDeVentaId' => '10000',
			'tipoComprobanteId' => $this->_tipoDeComprobanteId, 
			'SesionId' => $this->session->userdata('ws_sesionid'),
			'FechaVencimiento' =>  $this->session->userdata('ws_fechavencimiento')
			];

			$doc = new DOMDocument();
			libxml_use_internal_errors(true);
			$doc->loadHTML(callWS('UltimoNumeroComprobante', $_prm));
			libxml_clear_errors();
			$xml = $doc->saveXML($doc->documentElement);
			$xml = simplexml_load_string($xml);
			$_n = $xml->body->envelope->body->ultimonumerocomprobanteresponse->ultimonumerocomprobanteresult;
			$_nro = ($_n > 0)? $_n:0; 
			return $_nro;

		}

		function echoUltimoComprobante(){
			
			echo ($this->ultimoComprobante());echo('<hr>');
			echo $this->session->userdata('ws_sesionid');echo('<hr>');
			echo $this->session->userdata('ws_fechavencimiento');echo('<hr>');
		}

		function salidaTransaccion($transaccionId, $cia_nit){

			$this->IniciarSesion();

			$_prm = (object) [
			'cuitId' => $cia_nit, 
			'transaccionId' => $transaccionId,
			'SesionId' => $this->session->userdata('ws_sesionid'),
			'FechaVencimiento' =>  $this->session->userdata('ws_fechavencimiento')
			];

			$doc = new DOMDocument();
			libxml_use_internal_errors(true);
			$_i = 1;
			while (@$_xml->Transaccion->Estado!='Transacción Exitosa') {
				$doc->loadHTML(callWS('SalidaTransaccion', $_prm));
				$xml = $doc->saveXML($doc->documentElement);
				$xml = simplexml_load_string($xml);
				$_xml = simplexml_load_string($xml->body->envelope->body->salidatransaccionresponse->salidatransaccionresult);
				if (isset($_xml->Error)) {
					log_message('error','salidaTransaccion L289: '. json_encode($_xml->Error));
					print_r($_xml->Error);die('Dian_edx L290');
					return false;
					break;	
				}

				if (@$_xml->Transaccion->Estado == 'Transacción Exitosa') {
					break;
				}

				sleep(10);
				if ($_i > 4) {
					break;
				}$_i++;
			}
			return (@$_xml->Transaccion->Estado=='Transacción Exitosa');

		}

		function IniciarSesion(){
			$error = false; $_error = [];
			$ws_fechavencimiento = $this->session->userdata('ws_fechavencimiento')? False:$this->session->userdata('ws_fechavencimiento');

			if (!fEnRango($ws_fechavencimiento)) {
				$doc = new DOMDocument();
				libxml_use_internal_errors(true);
				$_gComfiar = getComfiarUser();
				if (!$_gComfiar) {
					$error = true;
					$_error[] = ' No está definida una RESOLCIóN para esta tienda';
				}
				if (!$error) {
					$doc->loadHTML(callWS('IniciarSesion', $_gComfiar));
					libxml_clear_errors();
					$xml = $doc->saveXML($doc->documentElement);
					$xml = simplexml_load_string($xml);
					$_resp = [];
					if(@$xml->body->envelope->body->iniciarsesionresponse->iniciarsesionresult->sesionid){
						$this->session->set_userdata("ws_sesionid", (string)$xml->body->envelope->body->iniciarsesionresponse->iniciarsesionresult->sesionid);
						$this->session->set_userdata("ws_fechavencimiento", (string)$xml->body->envelope->body->iniciarsesionresponse->iniciarsesionresult->fechavencimiento);
					log_message('error','Sales CTRLR L1830 ws_sesionid: '. $this->session->userdata('ws_sesionid'));
					log_message('error','Sales CTRLR L1831 ws_fechavencimiento: '. $this->session->userdata('ws_fechavencimiento'));

					}else{
						$error = true;
						$_error[] =  (string)$xml->body->envelope->body->fault->faultstring;
					}
				}
			}

			
			if ($error) {
				$error = false;
				return $_error;
			}

			return true;
		}
	//================================================================================= EDX
}
?>