<?php  
if (!defined('_PS_VERSION_')) {
    exit();
}

include_once(dirname( __FILE__ )  . '/../../classes/ChilexpressOficialOrderMeta.php');
include_once(dirname( __FILE__ )  . '/../../classes/PDFLabel.php');
include_once(dirname( __FILE__ )  . '/../../chilexpress_oficial_api.php');

class ChilexpressOrderController extends AdminController
{
	public function __construct()
	{ 
		$this->bootstrap = true;
        $this->table = 'chilexpressorder';
        $this->className = 'ChilexpressOrder';

        $this->carriers_serviceTypeCode = array(
            'CHILEXPRESS_OFCL_DHSP'  => 2,
            'CHILEXPRESS_OFCL_DHS'   => 3,
            'CHILEXPRESS_OFCL_DHSS'  => 4,
            'CHILEXPRESS_OFCL_3DH'   => 5,
            'CHILEXPRESS_OFCL_MDAP'  => 8,
			'CHILEXPRESS_OFCL_EDS'   => 11,
			'CHILEXPRESS_OFCL_BIG1'  => 41,
            'CHILEXPRESS_OFCL_BIG2'  => 42,
			'CHILEXPRESS_OFCL_BSC3' => 53,
            'CHILEXPRESS_OFCL_BSC4' => 54,
            'CHILEXPRESS_OFCL_BSC5' => 55,
            'CHILEXPRESS_OFCL_EX12' => 56,

        );

        $this->api = new Chilexpress_Oficial_API();

        parent::__construct();
	}

	public function postProcess()
    {
        parent::postProcess();
    }

 	public function initContent(){ // NOSONAR

 		$orders = array();
 		$action = ' ';
		$order_type = 4; // PDF by default

 		if ( isset($_GET["order_id"]) ) {
 			array_push($orders, $_GET["order_id"]);
 		}

 		if ( isset($_GET["action"]) ) {
 			$action = $_GET["action"];
			if (!$action) {
				$action = "generar_ot";
			}
 		}
		if ( isset($_GET["order_type"]) ) {
 			$order_type = intval($_GET["order_type"]);
			if ($order_type < 1 || $order_type > 4) {
				$order_type = 4;
			}
 		}

 		if ( isset($_GET["group_action"]) ) {
			$action = 'generar_multiples_ot';
 		}

 		if ( $action == 'generar_multiples_ot' ){
 			
 			$orders = explode(",", $_GET['pedidos']);
 			$sql = new DbQuery();

 			foreach ($orders as $key => $order_id) 
 			{
 				$order_carrier = new OrderCarrier((int) $order_id);
                $transportOrderNumber = ( isset($order_carrier->tracking_number) ) ? $order_carrier->tracking_number : '';

                if( $transportOrderNumber != '' ){
                	unset( $orders[$key] );
                }
 			}
 			
 		}

 		if( count($orders) == 0 )
 		{
 			return 'Orden no encontrada';
 		}

 		$payload_header = array(
			"certificateNumber" => 0, //Número de certificado, si no se ingresa se creará uno nuevo
			"customerCardNumber"=> Configuration::get('numero_tcc_origen'), // Número de Tarjeta Cliente Chilexpress (TCC)
			"countyOfOriginCoverageCode"=> Configuration::get('comuna_origen'), // Comuna de origen
			"labelType"=> 2, // Imagen
			"marketplaceRut"=> intval(Configuration::get('numero_tcc_origen')), // Rut asociado al Marketplace
			"sellerRut"=> "DEFAULT", // Rut asociado al Vendedor
			"sourceChannel" => 6 // prestashop se identifica en el sistema como 6
		);


		if (isset($_POST['submitchilexpress_oficial']) && $_POST['submitchilexpress_oficial'] == 1 || $action == 'generar_multiples_ot')
	 	{
	 		foreach ($orders as $key => $order) 
	 		{
	 			$order_id = intval($order);
				$order = new Order($order_id);

		        if (!Validate::isLoadedObject($order)) {
		            return 'Orden no encontrada';
		        }

		        $address_obj = new Address($order->id_address_delivery);

		        if(!$address_obj->phone){
		        	die('El teléfono del destino es requerido ó tiene un formato incorrecto | Pedido: '.$order_id);
		        }

		        $customer = new Customer($address_obj->id_customer);

		        $address = array(
		        	"city" => $address_obj->city,
		        	"address1" => $address_obj->address1,
		        	"other" => $address_obj->other,
		        );
		        $devolucion = array(
		        	"city" => Configuration::get('comuna_devolucion'),
		        	"address1" => Configuration::get('calle_devolucion'),
		        	"address2" => Configuration::get('numero_calle_devolucion'),
		        	"other" => Configuration::get('complemento_devolucion')
		        );
		        $remitente = array(
		        	"nombre" => Configuration::get('nombre_remitente'),
		        	"telefono" => Configuration::get('telefono_remitente'),
		        	"email" => Configuration::get('email_remitente')
		        );
		        $destinatario = array(
		        	"nombre" => $customer->firstname.' '.$customer->lastname,
		        	"telefono" => $address_obj->phone,
		        	"email" => $customer->email
		        );


		        $cart = new Cart($order->id_cart);
		        $products = $cart->getProducts(true);

			    $products_array = array();
			    
			    foreach($products as $product) {
			        $products_array[] = array(
			            "id" => $product["id_product"],
			            "cart_quantity" => $product["cart_quantity"],
			            "name" => isset($product["name"]) ? $product["name"] : 'Sin Nombre',
			            "width" => ( floatval($product['width']) ) ? $product['width'] : Configuration::get(CXP_PRODUCT_DEFAULT_WIDTH),
			            "height" => ( floatval($product['height']) ) ? $product['height'] : Configuration::get(CXP_PRODUCT_DEFAULT_HEIGHT),
			            "depth" => ( floatval($product['depth']) ) ? $product['depth'] : Configuration::get(CXP_PRODUCT_DEFAULT_DEPTH),
			            "weight" => ( floatval($product['weight']) ) ? $product['weight'] : Configuration::get(CXP_PRODUCT_DEFAULT_WEIGHT),
			            "total" => $product["total"],
			        );
			    }
   
				$serviceTypeId  = 0;
		 		foreach ($this->carriers_serviceTypeCode as $carrier_key => $stypeid)
		 		{
					if (Configuration::get($carrier_key) == $order->id_carrier)
					{
						$serviceTypeId = $stypeid;
					}
				}

				$payload_address_destino = array(
				  	"addressId" => 0, // Id de la dirección obtenida de la API Validar dirección
					"countyCoverageCode"=>  $address["city"], // Cobertura de destino obtenido por la API Consultar Coberturas
					"streetName"=> $address["address1"], // Nombre de la calle
					//"streetNumber"=> $address["other"], // Numeraci'on de la calle
					"supplement"=> $address["other"], // Información complementaria de la dirección
					"addressType"=> "DEST", // Tipo de dirección; DEST = Entrega, DEV = Devolución.
					"deliveryOnCommercialOffice"=> false, // Indicador si es una entrega en oficina comercial (true) o entrega en domicilio (false)
					"commercialOfficeId"=> "",
					"observation"=> "DEFAULT" // Observaciones adicionales
			  	);

				$payload_address_devolucion = array(
					"addressId"=> 0,
					"countyCoverageCode"=> $devolucion['city'],
					"streetName"=> $devolucion['address1'],
					"streetNumber"=> isset($devolucion['address2']) ? $devolucion['address2'] : '',
					"supplement"=> $devolucion['other'],
					"addressType"=> "DEV",
					"deliveryOnCommercialOffice"=> false,
					"observation"=> "DEFAULT"
			  	);

				$payload_contact_devolucion = array(
					"name"=> $remitente['nombre'],
					"phoneNumber"=> $remitente['telefono'],
					"mail"=> $remitente['email'],
					"contactType"=> "R" // Tipo de contacto; Destinatario (D), Remitente (R)
			  	);

				$payload_contact_destino = array(
					"name"=> $destinatario["nombre"],
					"phoneNumber"=> $destinatario["telefono"],
					"mail"=> $destinatario["email"],
					"contactType"=> "D" // Tipo de contacto; Destinatario (D), Remitente (R)
			  	);

				$pre_paquetes = array();
				$paquetes = array();

				if($_POST['submitchilexpress_oficial'] == 1){
					$opcion_paquetes = array( $_POST["paquetes"] );
				}
				else if($action == 'generar_multiples_ot'){
						
					foreach($products as $product) {
						$_POST["paquetes"][$key][ $product["id_product"] ] = "1";
					}

					$opcion_paquetes = $_POST["paquetes"];	
				}
				else{
					$opcion_paquetes = [];	
				}
					
				//$opcion_paquetes = $_POST["paquetes"];

				foreach($opcion_paquetes[$key] as $prodid => $numero_paquete ):
					foreach ($products_array as $product ):
						//echo $product["id"].' - '.$prodid;
						if ($product["id"] == "$prodid") {
							if (isset($pre_paquetes[$numero_paquete])) {
								$nombre = 'Sin Nombre';
								if (isset($product["name"])) {
									$nombre = $product["name"]; 
								}
								$pre_paquetes[$numero_paquete]["names"][] = $nombre." x ".$product["cart_quantity"];
								$pre_paquetes[$numero_paquete]["weight"] += $product["weight"]*$product["cart_quantity"];
								$pre_paquetes[$numero_paquete]["total"] += $product["total"]*$product["cart_quantity"];
								$pre_paquetes[$numero_paquete]["volumes"]["$item_id"] = $product['height']*$product["cart_quantity"]*$product['width']*$product['depth'];
							} else {
								$names = array( (isset($product["name"]) ? $product["name"] : '')." x ".$product["cart_quantity"]);
								$pre_paquetes[$numero_paquete] = array(
									"names" => $names,
									"weight"=> $product["weight"]*$product["cart_quantity"],
									"total"=> $product["total"]*$product["cart_quantity"],
									"volumes" => array(
										"$prodid" => $product['height']*$product["cart_quantity"]*$product['width']*$product['depth']
									)
								);
							}
						}
					endforeach;
				endforeach;

				foreach($pre_paquetes as $numero_paquete => $base_paquete ):
					// ordenamos los volumenes en volumen de mayor a menor
					arsort($base_paquete["volumes"]);
					// obtenemos el id del producto 
					$biggest_product_id = $this->array_key_first($base_paquete["volumes"]);
					foreach ($products_array as $product ):
						$item_id = $product["id"];

						if ($item_id == $biggest_product_id) {

							if($base_paquete["weight"] == 0) {
								$base_paquete["weight"] += 1;
							}

							if($product['height'] == 0) {
								$product['height'] += 1;
							}

							if($product['width'] == 0) {
								$product['width'] += 1;
							}

							if($product['depth'] == 0) {
								$product['depth'] += 1;
							}
								
							$articulos_tienda = Configuration::get('articulos_tienda');
							if (!$articulos_tienda) {
								$articulos_tienda = 5;
							}

						    $paquetes[] =  array(
								"weight"=> $base_paquete["weight"], // Peso en kilogramos
								"height"=> $product['height'], // Altura en centímetros
								"width"=> $product['width'], // Ancho en centímetros
								"length"=> $product['depth'],  // Largo en centímetros
								"serviceDeliveryCode"=> $serviceTypeId, // Código del servicio de entrega, obtenido de la API Cotización
								"productCode"=> "3", // Código del tipo de roducto a enviar; 1 = Documento, 3 = Encomienda
								"deliveryReference"=> "ORDEN-".$order_id, // Referencia que permite identificar el envío por parte del cliente.
								"groupReference"=> "ORDEN-".$order_id."-GRUPO-1", // Referencia que permite identificar un grupo de bultos que va por parte del cliente.
								"declaredValue"=> round($base_paquete["total"]), // Valor declarado del producto
								"declaredContent"=> $articulos_tienda, // Tipo de producto enviado; 1 = Moda, 2 = Tecnologia, 3 = Repuestos, 4 = Productos medicos, 5 = Otros
								"descriptionContent" => implode(";",$base_paquete["names"]),
								"extendedCoverageAreaIndicator"=> false, // Indicador de contratación de cobertura extendida 0 = No, 1 = Si
								"receivableAmountInDelivery"=> 0 // Monto a cobrar, en caso que el cliente tenga habilitada esta opción. Se deja en 0 a solicitud de RCEA
			  				);
						}
					endforeach;
				endforeach;

				$details[] = array(
					"addresses" => array(
						$payload_address_destino,
						$payload_address_devolucion
					),
					"contacts" => array( // Se debe entregar un detalle para los datos de contacto del destinatario (D) y otro para los del remitente (R)
						$payload_contact_devolucion,
						$payload_contact_destino
					),
					"packages" => $paquetes
				);   

	 		} // end foreach orders

	 		$payload = array(
				"header"  => $payload_header,
				"details" => $details
			);

	 		$jresult = $this->api->generar_ot( json_encode($payload) );
			$serviceValue = false;
			
			$shipping_numbers = array();
			if (!$jresult)
			{
			    return 'Error tratando de crear Orden de Transporte';
			} 
			else {
				
				$certificateNumber = strval( $jresult["data"]["header"]["certificateNumber"] );
				$countOfGeneratedOrders = intval( $jresult["data"]["header"]["countOfGeneratedOrders"] );

			    for($i = 0; $i < $countOfGeneratedOrders; $i++ ) {

			        $OrderMeta = new ChilexpressOficialOrderMeta();
			        
			        $porciones = explode("-", $jresult['data']['detail'][$i]['reference']);
					$orderId = $porciones[1];

					$OrderMeta->id_order = (int)$orderId;
					$shipping_numbers[$orderId][] = $jresult['data']['detail'][$i]['transportOrderNumber'];

					$OrderMeta->transportOrderNumber = $jresult['data']['detail'][$i]['transportOrderNumber'];
					$OrderMeta->certificateNumber = $certificateNumber;
					$OrderMeta->reference = $jresult['data']['detail'][$i]['reference'];
					$OrderMeta->productDescription = $jresult['data']['detail'][$i]['productDescription'];
					$OrderMeta->serviceDescription = $jresult['data']['detail'][$i]['serviceDescription'];
					$OrderMeta->genericString1 = $jresult['data']['detail'][$i]['genericString1'];
					$OrderMeta->genericString2 = $jresult['data']['detail'][$i]['genericString2'];
					$OrderMeta->deliveryTypeCode = $jresult['data']['detail'][$i]['deliveryTypeCode'];
					$OrderMeta->destinationCoverageAreaName = $jresult['data']['detail'][$i]['destinationCoverageAreaName'];
					$OrderMeta->additionalProductDescription = $jresult['data']['detail'][$i]['additionalProductDescription'];
					$OrderMeta->barcode = $jresult['data']['detail'][$i]['barcode'];
					$OrderMeta->classificationData = $jresult['data']['detail'][$i]['classificationData'];
					$OrderMeta->printedDate = $jresult['data']['detail'][$i]['printedDate'];
					$OrderMeta->labelVersion = $jresult['data']['detail'][$i]['labelVersion'];
					$OrderMeta->distributionDescription = $jresult['data']['detail'][$i]['distributionDescription'];
					$OrderMeta->companyName = $jresult['data']['detail'][$i]['companyName'];
					$OrderMeta->recipient = $jresult['data']['detail'][$i]['recipient'];
					$OrderMeta->address = $jresult['data']['detail'][$i]['address'];
					$OrderMeta->groupReference = $jresult['data']['detail'][$i]['groupReference'];
					$OrderMeta->createdDate = $jresult['data']['detail'][$i]['createdDate'];
					$OrderMeta->labelData = $jresult['data']['detail'][$i]['label']['labelData'];

				    $OrderMeta->add();
			    }

			    foreach ($shipping_numbers as $id_order => $value) 
			    {
			    	$order = new Order( $id_order );
			    	$order_carrier = new OrderCarrier( (int) $order->getIdOrderCarrier() );
			    	$order_carrier->tracking_number = implode(',', $value);
			    	$order_carrier->save();

			    	$order->shipping_number = implode(',', $value);
			    	$order->save();

			    	$resultado = $this->sendOrderConfirmationEmail($id_order);
			    }


			    if( $_POST['submitchilexpress_oficial'] == 1 )
			    {
			    	$version_parts = explode('.', _PS_VERSION_);
					if (count($version_parts) >= 3 && $version_parts[0] >= 1 && $version_parts[1] >= 7 && $version_parts[2] >= 7) {
						// newer than 1.7.7
						$link = new Link();
						$url = ($link->getAdminLink('AdminOrders', true, [], ['id_order' => $order_id, 'vieworder' => 1]));
						header("Location: $url");
						die();
					} else {
						// older than 1.7.7
						$url = ($this->context->link->getAdminLink('AdminOrders', true, [], ['id_order' => $order_id, 'vieworder' => 1]) . '&amp;id_order='.$order_id.'&amp;vieworder');
						header("Location: $url");
						die();
					}
					
					Tools::redirect($url);
			    }

			    if( $action == 'generar_multiples_ot' )
			    {
			    	$link = new Link();
					$url = _PS_BASE_URL_.$link->getAdminLink('AdminOrders', true, [], []);
					Tools::redirect($url);
			    }

		    }

 		}

 		
 		$order_id = $orders[0];
 		$order = new Order($order_id);

		if (!Validate::isLoadedObject($order)) {
		    return 'Orden no encontrada';
		}
		$address_obj = new Address($order->id_address_delivery);

		# Variable ocupada para mostrar cosas al usuario cuando hay error
		$errorData = array("visible_error" => "none", "visible_got" => "true", "msg" => "Error no detectado");

		/*if (!$address_obj->phone) {
			$errorData['visible_error'] = "true";
			$errorData['visible_got'] = "none";
			$errorData['msg'] = "El Teléfono del cliente es obligatorio para generar OT";
		}*/

		// Formato de tel'efono 
		$phone_destination = $address_obj->phone;
		if( strlen($phone_destination) === 8 ){
			$phone_destination = "569".$phone_destination;
		}
		else if( strlen($phone_destination) === 9 ){
			$phone_destination = "56".$phone_destination;
		}
		else{
			$errorData['visible_error'] = "true";
			$errorData['visible_got'] = "none";
			$errorData['msg'] = "El teléfono del destino es requerido ó tiene un formato incorrecto";
		}

		$customer = new Customer($address_obj->id_customer);

		$address = array(
		    "city" => $address_obj->city,
		    "address1" => $address_obj->address1,
		    "other" => $address_obj->other,
		);
		$devolucion = array(
		    "city" => Configuration::get('comuna_devolucion'),
		    "address1" => Configuration::get('calle_devolucion'),
		    "address2" => Configuration::get('numero_calle_devolucion'),
		    "other" => Configuration::get('complemento_devolucion')
		);
		$remitente = array(
		    "nombre" => Configuration::get('nombre_remitente'),
		    "telefono" => Configuration::get('telefono_remitente'),
		    "email" => Configuration::get('email_remitente')
		);
		$destinatario = array(
		    "nombre" => $customer->firstname.' '.$customer->lastname,
		    "telefono" => $phone_destination,
		    "email" => $customer->email
		);

		$cart = new Cart($order->id_cart);
		$products = $cart->getProducts(true);

		$products_array = array();

		foreach($products as $product) {
			$products_array[] = array(
			    "id" => $product["id_product"],
			    "cart_quantity" => $product["cart_quantity"],
			    "name"   => isset($product["name"]) ? $product["name"] : 'Sin nombre',
			    "width"  => ( floatval($product['width']) ) ? $product['width'] : Configuration::get(CXP_PRODUCT_DEFAULT_WIDTH),
			    "height" => ( floatval($product['height']) ) ? $product['height'] : Configuration::get(CXP_PRODUCT_DEFAULT_HEIGHT),
			    "depth"  => ( floatval($product['depth']) ) ? $product['depth'] : Configuration::get(CXP_PRODUCT_DEFAULT_DEPTH),
			    "weight" => ( floatval($product['weight']) ) ? $product['weight'] : Configuration::get(CXP_PRODUCT_DEFAULT_WEIGHT),
			    "total"  => $product["total"],
			);
		}

 		if ($action == 'generar_ot') {
 			$tpl = $this->context->smarty->createTemplate(_PS_MODULE_DIR_ . 'chilexpress_oficial/views/templates/admin/chilexpress_oficial.tpl', $this->context->smarty);

	        $tpl->assign(array(
	        	'order' => $order,
	        	'destino' => $address,
	        	'devolucion' => $devolucion,
	        	'remitente' => $remitente,
	        	'destinatario' => $destinatario,
	        	'productos' => $products_array,
	        	'cantidad' => count($products_array),
				'error_data'  => $errorData,
	        	"url" => $this->context->link->getAdminLink('ChilexpressOrder').'&order_id='.$order_id.'&action=generar_ot'
	        ));
	        $this->content .= $tpl->fetch();
	        parent::initContent();
 		} else if ($action == 'ver_ot') {
 			$tpl = $this->context->smarty->createTemplate(_PS_MODULE_DIR_ . 'chilexpress_oficial/views/templates/admin/chilexpress_oficial_ver_ot.tpl', $this->context->smarty);

 			$query = new DbQuery();
            $query->from('chilexpress_oficial_ordermeta', 'com');
            $query->where('com.id_order = "'.$order_id.'"');
            $metasArray = Db::getInstance()->executeS($query);
			

	        $tpl->assign(array(
	        	'ots' => $metasArray,
	        	'pdfurl' => $this->context->link->getAdminLink('ChilexpressOrder').'&order_id='.$order_id.'&action=print_ot',
				'zplurl' => $this->context->link->getAdminLink('ChilexpressOrder').'&order_id='.$order_id.'&action=print_ot&order_type=3',
				'pngurl' => $this->context->link->getAdminLink('ChilexpressOrder').'&order_id='.$order_id.'&action=print_ot&order_type=2',
	        ));
	        $this->content .= $tpl->fetch();
	        parent::initContent();
 		} else if ($action == 'print_ot') {
 			$query = new DbQuery();
            $query->from('chilexpress_oficial_ordermeta', 'com');
            $query->where('com.id_order = "'.$order_id.'"');
            $metasArray = Db::getInstance()->executeS($query);

            $otrackings = array();
            foreach ($metasArray as $ot) {	
				$etiqueta = $this->api->obtener_etiqueta( $ot['transportOrderNumber'],  $order_type);
				$type = 'PDF';
				//TODO:safe
				if (isset($etiqueta['data']) && isset($etiqueta['data']['label']) && isset($etiqueta['data']['label']['labelType'])) {
					$type = $etiqueta['data']['label']['labelType'];
				}
				if (!isset($etiqueta['data']['label']['labelData'])) {
					echo "Hubieron problemas al obtener la etiqueta, por favor reintente mas tarde";
					exit();
				}
				$fileExtension = '';
				$contentType = '';
				$decodeData = true;
				switch ($type) {
					case 'PDF':
						$fileExtension = '.pdf';
						$contentType = 'application/pdf';
						break;
					case 'ZPL':
						$fileExtension = '.zpl';
						$contentType = 'application/zpl';
						$decodeData = false;
						break;
					case 'Binary':
						$fileExtension = '.png';
						$contentType = 'image/png';
						break;
					default:
						echo "Unknown label type";
						die(0);
				}

				header('Content-Type: ' . $contentType);
				$fileName = 'Orden_de_transporte_' . $ot['transportOrderNumber'];
				header('Content-Disposition: attachment; filename="'.$fileName.$fileExtension.'"');
				if ($decodeData) {
					echo base64_decode($etiqueta['data']['label']['labelData']);
				} else {
					echo $etiqueta['data']['label']['labelData'];
				}
				exit();
            }
 		}
    }


    public function viewAccess($disable = false)
    {
        if (version_compare(_PS_VERSION_, '1.5.1.0', '<=')) { // NOSONAR
            return true;
		}
        return true;
    }


    function array_key_first(array $arr) {
        foreach($arr as $key => $unused) {
            return $key;
        }
        return NULL;
    }




	private static function sendOrderConfirmationEmail($id_order)
  	{
		function formatPrice($price, $currency_code) {
			// Tools::displayPrice is deprecated in 1.7.6 and removed in 9.0.0
			$context = Context::getContext();
			return $context->currentLocale->formatPrice($price, $currency_code ?? 'CLP', false);
		}

	    $order = new Order($id_order);
	    $context = Context::getContext();
	    $invoice = new Address($order->id_address_invoice);
	    $delivery = new Address($order->id_address_delivery);
	    $delivery_state = $delivery->id_state ? new State((int) $delivery->id_state) : false;
	    $invoice_state = $invoice->id_state ? new State((int) $invoice->id_state) : false;
	    $carrier = $order->id_carrier ? new Carrier($order->id_carrier) : false;
	    $customer = $order->getCustomer();
	    $orderLanguage = new Language((int) $order->id_lang);
	    $currency = new Currency($order->id_currency);
    
	    $product_var_tpl_list = array();
	    
	    foreach ($order->getProducts() as $product) {

	    	$vars = array();
	      	$vars['unit_price'] = formatPrice($product['unit_price_tax_excl'], $currency->iso_code ?? 'CLP');
	      	$vars['price'] = formatPrice($product['total_price_tax_incl'], $currency->iso_code ?? 'CLP');
	      	$vars['reference'] = $product['reference'];
	      	$vars['name'] = $product['product_name'];
	      	$vars['quantity'] = $product['product_quantity'];
	      	$vars['customization'] = array();

	      	array_push($product_var_tpl_list, $vars);
	    }

	    $cart = Cart::getCartByOrderId($order->id);

	    $cart_rules = $cart->getCartRules();
	    $cart_rules_var_tpl_list = array();

    	foreach($cart_rules as $rule){
      		$vars = array();

      		if($order->id_currency != $rule['reduction_currency']){
        		$conversion_rate = floatval(Db::getInstance()->getRow("SELECT conversion_rate FROM ps_currency WHERE id_currency = {$order->id_currency}")['conversion_rate']);
        		$vars['voucher_reduction'] = $rule['reduction_amount'] * $conversion_rate;
      		}
      		else{
        		$vars['voucher_reduction'] = $rule['reduction_amount'];
      		}

      		$vars['voucher_reduction'] = Tools::displayPrice($vars['voucher_reduction'], $currency, false);
      		$vars['voucher_name'] = $rule['description'];

      		array_push($cart_rules_var_tpl_list, $vars);
    	}

    	$product_list_html = self::getEmailTemplateContent('order_conf_product_list.tpl', Mail::TYPE_HTML, $product_var_tpl_list);
    	$cart_rules_list_html = self::getEmailTemplateContent('order_conf_cart_rules.tpl', Mail::TYPE_HTML, $cart_rules_var_tpl_list);  

    	$data = array(
      		'{products}' => $product_list_html,
      		'{discounts}' => $cart_rules_list_html,
      		'{firstname}' => $customer->firstname,
      		'{lastname}' => $customer->lastname,
      		'{email}' => $customer->email,
      		'{delivery_block_txt}' => self::getFormatedAddress($delivery, "\n"),
      		'{invoice_block_txt}' => self::getFormatedAddress($invoice, "\n"),
      		'{delivery_block_html}' => self::getFormatedAddress($delivery, '<br />', array(
          		'firstname' => '<span style="font-weight:bold;">%s</span>',
          		'lastname' => '<span style="font-weight:bold;">%s</span>',
      		)),
      		'{invoice_block_html}' => self::getFormatedAddress($invoice, '<br />', array(
          		'firstname' => '<span style="font-weight:bold;">%s</span>',
          		'lastname' => '<span style="font-weight:bold;">%s</span>',
      		)),
      		'{delivery_company}' => $delivery->company,
      		'{delivery_firstname}' => $delivery->firstname,
      		'{delivery_lastname}' => $delivery->lastname,
      		'{delivery_address1}' => $delivery->address1,
      		'{delivery_address2}' => isset($delivery->address2) ? $delivery->address2 : '',
      		'{delivery_city}' => $delivery->city,
      		'{delivery_postal_code}' => $delivery->postcode,
      		'{delivery_country}' => $delivery->country,
      		'{delivery_state}' => $delivery->id_state ? $delivery_state->name : '',
      		'{delivery_phone}' => ($delivery->phone) ? $delivery->phone : $delivery->phone_mobile,
      		'{delivery_other}' => $delivery->other,
      		'{invoice_company}' => $invoice->company,
      		'{invoice_vat_number}' => $invoice->vat_number,
      		'{invoice_firstname}' => $invoice->firstname,
      		'{invoice_lastname}' => $invoice->lastname,
      		'{invoice_address2}' => isset($invoice->address2) ? $invoice->address2 : '',
      		'{invoice_address1}' => $invoice->address1,
      		'{invoice_city}' => $invoice->city,
      		'{invoice_postal_code}' => $invoice->postcode,
      		'{invoice_country}' => $invoice->country,
      		'{invoice_state}' => $invoice->id_state ? $invoice_state->name : '',
      		'{invoice_phone}' => ($invoice->phone) ? $invoice->phone : $invoice->phone_mobile,
      		'{invoice_other}' => $invoice->other,
      		'{order_name}' => $order->getUniqReference().'</br><b>N° Tracking:</b> '.$order->getWsShippingNumber().'</br>',
      		'{date}' => Tools::displayDate(date('Y-m-d H:i:s'), false),//Tools::displayDate(date('Y-m-d H:i:s'), null, 1),
      		'{carrier}' => ($order->isVirtual() || !isset($carrier->name)) ? 'Sin transportista' : $carrier->name,
      		'{payment}' => Tools::substr($order->payment, 0, 255),
      		'{total_paid}' => formatPrice($order->total_paid, $currency->iso_code ?? 'CLP'),
      		'{total_products}' => formatPrice(
          		Product::getTaxCalculationMethod() == PS_TAX_EXC ? $order->total_products :
              	$order->total_products_wt, $currency->iso_code ?? 'CLP'),
      		'{total_discounts}' =>  formatPrice($order->total_discounts, $currency->iso_code ?? 'CLP'),
      		'{total_shipping}' => formatPrice($order->total_shipping, $currency->iso_code ?? 'CLP'),
      		'{total_shipping_tax_excl}' => formatPrice($order->total_shipping_tax_excl, $currency->iso_code ?? 'CLP'),
      		'{total_shipping_tax_incl}' => formatPrice($order->total_shipping_tax_incl, $currency->iso_code ?? 'CLP'),
      		'{total_wrapping}' => formatPrice($order->total_wrapping, $currency->iso_code ?? 'CLP'),
			'{total_tax_paid}' => formatPrice(($order->total_products_wt - $order->total_products) +
          		($order->total_shipping_tax_incl - $order->total_shipping_tax_excl), $currency->iso_code ?? 'CLP'),
    	);

    	$res = Mail::Send(
      		(int)$order->id_lang,
      		'order_conf',
      		$context->getTranslator()->trans(
          		'Pedido Confirmado',
          		array(),
          		'Emails.Subject',
          		$orderLanguage->locale
      		),
      		$data,
      		$customer->email,
      		$customer->firstname.' '.$customer->lastname,
      		null,
      		null,
      		false,
      		null, _PS_MAIL_DIR_, false, (int)$order->id_shop
    	);

    	return json_encode(array("success" => ($res ? true : false), "result" => $res));
  	}

  	private static function getEmailTemplateContent($template_name, $mail_type, $var)
  	{
    	$email_configuration = Configuration::get('PS_MAIL_TYPE');
    	if ($email_configuration != $mail_type && $email_configuration != Mail::TYPE_BOTH) {
        	return '';
    	}
    
    	$pathToFindEmail = array(
        	_PS_THEME_DIR_.'mails'.DIRECTORY_SEPARATOR.Context::getContext()->language->iso_code.DIRECTORY_SEPARATOR.$template_name,
        	_PS_THEME_DIR_.'mails'.DIRECTORY_SEPARATOR.'en'.DIRECTORY_SEPARATOR.$template_name,
        	_PS_MAIL_DIR_.Context::getContext()->language->iso_code.DIRECTORY_SEPARATOR.$template_name,
        	_PS_MAIL_DIR_.'en'.DIRECTORY_SEPARATOR.$template_name,
    	);

    	foreach ($pathToFindEmail as $path) {
        	if (Tools::file_exists_cache($path)) {
          		Context::getContext()->smarty->assign('list', $var);
            	return Context::getContext()->smarty->fetch($path);
        	}
    	}

    	return '';
  	}

  	private static function getFormatedAddress(Address $the_address, $line_sep, $fields_style = array())
  	{
    	return AddressFormat::generateAddress($the_address, array('avoid' => array()), $line_sep, ' ', $fields_style);
  	}

}