<?php
	//Esta a funcionar
	$path = dirname(__FILE__) . '/../../../core/';
	include $path . 'core_files.php';
	error_reporting(E_ALL);
	ini_set('display_errors', 0);



	$rs_metodo = new DataObj;
	$db_link = db_opendb_conection($GLOBALS['DB_host'], $GLOBALS['DB_user'], $GLOBALS['DB_pass']);

	$sql = "SELECT * FROM metodos_pagamento WHERE Tipo=".MP_TP_MB_HIPAY;
	$rs_metodo->db_open($db_link, $GLOBALS['DB_name'], $sql);
	$sandbox = 0;
	$conta_ifthen = '';
	if (!$rs_metodo->EOF())
	{
		$username = $rs_metodo->db_data["Username"];
		$password = $rs_metodo->db_data["Password"];
		$sandbox = $rs_metodo->db_data['sandox'];
	}
	$rs_metodo->db_close();

	if ($username && $password && $_GET['id_enc'] > 0)
	{
		$id_enc = $_GET['id_enc'];
		$rs = new DataObj;
		$sql_all = "SELECT TotalDocComIva FROM encomendas WHERE encomendas.ID='" . $id_enc . "'";
		$rs->db_open($db_link, $GLOBALS['DB_name'], $sql_all);
		if (!$rs->EOF())
		{
			$valor = $rs->db_data['TotalDocComIva'];
		}
		$rs->db_close();

		if(GenerateRef($username,$password,$id_enc,$valor,$sandbox))
		{
			echo getRef($id_enc);
		}
		else
		{
			$msg_tmp.='Não foi possivel gerar referência.';
		}
		echo $msg_tmp;
	}




	function GenerateRef($username,$password,$order_id,$order_value,$sanbox = 0)
	{
		$order_value =  numberformat( $order_value,4 );
		$order_value = str_replace(',','.',$order_value);
		$order_value= sprintf("%01.2f", $order_value);

		if ($order_value < 2)
		{
			echo "Lamentamos mas é impossível gerar uma referência MB para valores inferiores a 2 Euro";
			return;
		}


		$res=array();

		global $DB_host,$DB_user,$DB_pass,$DB_name,$admin_lang;
		$db_link=db_opendb_conection($DB_host,$DB_user,$DB_pass);
		$rs = new DataObj;
		$rs->db_open($db_link, $DB_name, 'SELECT * from encomendas WHERE ID = '.$order_id);
		if(!$rs->EOF())
		{
			$enc_Nome=$rs->db_data['enc_Nome'];
			$enc_Apelido=$rs->db_data['enc_Apelido'];
			$enc_Email=$rs->db_data['enc_Email'];
			$enc_Telefone=$rs->db_data['enc_Telefone'];
			$enc_Nif=$rs->db_data['enc_Nif'];
			$enc_Pais=$rs->db_data['enc_Pais'];
			$enc_Morada=$rs->db_data['enc_Morada'];
			$enc_Cidade=$rs->db_data['enc_Cidade'];
			$enc_DataNascimento=$rs->db_data['enc_DataNascimento'];
			$enc_Sexo=$rs->db_data['enc_Sexo'];
			$enc_Codigo_Postal=$rs->db_data['enc_Codigo_Postal'];
			$enc_Nome_ent=$rs->db_data['enc_Nome_ent'];
			$enc_Apelido_ent=$rs->db_data['enc_Apelido_ent'];
			$enc_Morada_ent=$rs->db_data['enc_Morada_ent'];
			$enc_Pais_ent=$rs->db_data['enc_Pais_ent'];
			$enc_Cidade_ent=$rs->db_data['enc_Cidade_ent'];
			$enc_Codigo_Postal_ent=$rs->db_data['enc_Codigo_Postal_ent'];
			$enc_Telefone_ent=$rs->db_data['enc_Telefone_ent'];

			
			$order = array(
					'id' => $order_id,
					'billing_name' => $enc_Nome,
					'billing_street' => $enc_Morada,
					'billing_postcode' => $enc_Codigo_Postal,
					'billing_town' => $enc_Cidade,
					'email' => $enc_Email,
					'total' => $order_value
			);
			$res = createMbReference($order,$username,$password);
		}
		$rs->db_close();

		if($res['entity'])
		{

			$refs[1] = $res['entity'];
			$refs[2] = $res['reference'];

			global $DB_host,$DB_user,$DB_pass,$DB_name,$admin_lang;
			$db_link=db_opendb_conection($DB_host,$DB_user,$DB_pass);
			$rs = new DataObj;
			$rs->db_open($db_link, $DB_name, 'SELECT id_order FROM hipayreferences WHERE id_order = '.$order_id);
			if(!$rs->EOF())
			{
				$sql='UPDATE hipayreferences SET refMB = "'.$refs[2].'", refPS = "'.$refs[1].'", value = "'.$order_value.'" WHERE id_order = "'.$order_id.'"';
			}
			else $sql='INSERT INTO hipayreferences (id_order, refMB, refPS, value) values ('.$order_id.', "'.$refs[2].'", "'.$refs[1].'", "'.$order_value.'")';
			$rs->db_close();

			$res = Runquery($db_link,$DB_name,$sql);

			$sql = "UPDATE encomendas SET Ent_atm='".$refs[1]."',Ref_atm='".str_replace(' ', '', $refs[2])."' WHERE ID='" . $order_id . "'";
			$res = Runquery($db_link, $GLOBALS['DB_name'], $sql);
		}
		else
		{
			$message = "/<a:message>(.*?)<\/a:message>/s";
			if(preg_match($message,$response,$message_value)){echo $message_value[1];}
		}
		return true;
	}


	function getRef($order_id)
	{
		global $DB_host,$DB_user,$DB_pass,$DB_name;
		$db_link=db_opendb_conection($DB_host,$DB_user,$DB_pass);
		$rs = new DataObj;

		$table_name = "hipayreferences";
		$rs->db_open($db_link,$DB_name, 'SELECT refMB, refPS, value FROM '.$table_name.' WHERE id_order = '.$order_id);
		while(!$rs->EOF())
		{
			$refs[2] = $rs->db_data["refMB"];
			$order_value = $rs->db_data["value"];

			if($refs[2] != -1)
			{
				$refs[2] = substr($refs[2],0,3).' '.substr($refs[2],3,3).' '.substr($refs[2],6,3);
				$tabelaMulti = '<table cellpadding="3" width="400px" cellspacing="0" style="margin-top: 10px;border: 1px solid #dcdcdc;margin:0 auto" align="center">';
				$tabelaMulti .= "<tr>";
				$tabelaMulti .=	'<td style="font-size: x-small; border-top: 0px; border-left: 0px; border-right: 0px; border-bottom: 1px solid #dcdcdc; background-color: #dcdcdc; color: black" colspan="3"><center>Pagamento por Multibanco (by HIPAY)</center></td>';
				$tabelaMulti .= "</tr>";
				$tabelaMulti .= "<tr>";
				$tabelaMulti .=	'<td rowspan="4"><div align="center"><img src="https://colegios.trotinete.pt/external_api/pagamentos/pgm_hipay/MB125x80px.png" alt=""/></div></td>';
				$tabelaMulti .=	'<td style="font-size: x-small; font-weight:bold; text-align:left">Entidade:</td>';
				$tabelaMulti .=	'<td style="font-size: x-small; text-align:left">11024</td>';
				$tabelaMulti .= "</tr>";
				$tabelaMulti .= "<tr>";
				$tabelaMulti .= '<td style="font-size: x-small; font-weight:bold; text-align:left">Refer&ecirc;ncia:</td>';
				$tabelaMulti .=	'<td style="font-size: x-small; text-align:left">'. $refs[2].'</td>';
				$tabelaMulti .= "</tr>";
				$tabelaMulti .= "<tr>";
				$tabelaMulti .=	'<td style="font-size: x-small; font-weight:bold; text-align:left">Valor:</td>';
				$tabelaMulti .=	'<td style="font-size: x-small; text-align:left">'.numberformat($order_value).'</td>';
				$tabelaMulti .= "</tr>";
				$tabelaMulti .= "<tr>";
				$tabelaMulti .= '<td style="font-size: x-small; font-weight:bold; text-align:left">&nbsp;</td>';
				$tabelaMulti .= '<td style="font-size: x-small; text-align:left">&nbsp;</td>';
				$tabelaMulti .= "</tr>";
				$tabelaMulti .= "<tr>";
				$tabelaMulti .=	'<td style="font-size: xx-small;border-top: 1px solid #dcdcdc; border-left: 0px; border-right: 0px; border-bottom: 0px; background-color: #dcdcdc; color: black" colspan="3"><center>O tal&atilde;o emitido pela caixa autom&aacute;tica faz prova de pagamento. Conserve-o.</center></td>';
				$tabelaMulti .= "</tr>";
				$tabelaMulti .= "</table>";
			}
			$rs->db_next();
		}
		$rs->db_close();


		if($order_id > 0 )
		{
			$sql = 'UPDATE encomendas SET enc_pagamento_dados="'.addslashes($tabelaMulti).'" WHERE ID = '.$order_id;
			Runquery($db_link, $GLOBALS['DB_name'], $sql);
		}
		return $tabelaMulti;
	}


  function createMbReference($order,$username = "hp3447357",$password = "trotinete16",$origin = false)
  {
    // variables to pass to webservice
    if(!$origin)
    {
      $origin = "http://www.trotinete.pt/hipay?id=".$order->id;      
    }
    // $username = "hp3447357";
    // $password = "trotinete16";
    $amount = $order['total'];
    $additionalInfo = "";
    $name = $order['billing_name'];
    $address = $order['billing_street'];
    $postCode = $order['billing_postcode'];
    $city = $order['billing_town'];
    $NIC = "";
    $externalReference = "54684631687";
    $contactPhone = "" ;
    $email = $order['email'];
    $IDUserBackoffice = -1; //-1 in most cases
    $timeLimitDays = 3; //3, 30 or 90 days; only used for entity 11249 and ignored for entity 10241 (must be 0)
    $sendEmailBuyer = false;


    //variables do store the results to show to the user
    $reference="";
    $entity="";
    $value="";
    $error="";


    // call webservice
    try
		{

			// URL from where the webservice is located. This example uses a test webservice; when using in a real environment,
			// you must replace this URL for the real CompraFacil webservice URL
			//$wsURL = "https://hm.comprafacil.pt/SIBSClick2Teste/webservice/CompraFacilWS.asmx?WSDL";
      $wsURL = "https://hm.comprafacil.pt/SIBSClick2/webservice/ComprafacilWS.asmx?WSDL";

			$parameters = array(
				"origin" => $origin,
				"username" => $username,
				"password" => $password,
				"amount" => $amount,
				"additionalInfo" => $additionalInfo,
				"name" => $name,
				"address" => $address,
				"postCode" => $postCode,
				"city" => $city,
				"NIC" => $NIC,
				"externalReference" => $externalReference,
				"contactPhone" => $contactPhone,
				"email" => $email,
				"IDUserBackoffice" => $IDUserBackoffice,
				"timeLimitDays" => $timeLimitDays,
				"sendEmailBuyer" => $sendEmailBuyer
				);
			
			$client = new SoapClient($wsURL);
			$res = $client->getReferenceMB($parameters);

			if ($res->getReferenceMBResult)
			{
				$entity = $res->entity;
				$value = number_format($res->amountOut, 2);
				$reference = $res->reference;
				$error = "";
				return [ 'entity'=>$entity,'value'=>$value,'reference'=>$reference,'error'=>$error];
			}
			else
			{
				return $res->error;
			}

		}
		catch (Exception $e){
			$error = $e->getMessage();
			return 'Erro ao invocar webservice.';
		}



  }
?>