<?php

/*------------------------------------------------------------------------
# com_invoices - Invoice Manager for Joomla
# ------------------------------------------------------------------------
# author				Germinal Camps
# copyright 			Copyright (C) 2012 - 2016 JoomlaThat.com. All Rights Reserved.
# @license				http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
# Websites: 			http://www.joomlathat.com
# Technical Support:	Forum - http://www.joomlathat.com/support
-------------------------------------------------------------------------*/

//no direct access
defined('_JEXEC') or die('Restricted access.');

class InvoicesHelper{

	static function showInvoicesFooter(){
		require_once(JPATH_SITE.DS.'components'.DS.'com_invoices'.DS.'helpers'.DS.'version.php');
		return InvoicesVersion::show_footer();
	}

	static function format($number, $currency = false){

		$params = JComponentHelper::getParams( 'com_invoices' );
		$db = JFactory::getDBO();

		if(is_int($currency)){
			$query = "SELECT * FROM #__invoices_currencies WHERE id = ".(int)$currency;
			$db->setQuery($query);
			$currency = $db->loadObject();
		}

		if(!$currency){
			$query = "SELECT * FROM #__invoices_currencies WHERE id = ".(int)$params->get('currency_id', 1);
			$db->setQuery($query);
			$currency = $db->loadObject();
		}
		if($currency == 'percent'){
			$currency = new stdClass();
			$currency->decpoint = ".";
			$currency->thousands = ",";
			$currency->decimals = 0;
			$currency->symbol_before = "";
			$currency->symbol_after = "%";

		}

		$decpoint = $currency->decpoint;
		$thousands = $currency->thousands;
		$decimals = $currency->decimals;
		$before = $currency->symbol_before;
		$after = $currency->symbol_after;

		return $before  . number_format($number, $decimals, $decpoint, $thousands)  . $after ;
	}

	static function format_editing($number){

		$params = JComponentHelper::getParams( 'com_invoices' );

		$decimals = $params->get('decimals_editing', 2);

		return number_format($number, $decimals, '.', '') ;
	}

	static function format_simple($number){

		return str_replace(".", ",", $number) ;
	}

	static function get_subtotal($invoice_id){

		$db = JFactory::getDBO();

		$query = ' SELECT SUM((it.value * it.amount - it.discount)*(1+it.tax/100)) FROM #__invoices_items AS it WHERE it.invoice_id = '.$invoice_id ;
		$db->setQuery($query);
		$subtotal = $db->loadResult();

		$query = ' SELECT discount FROM #__invoices_invoices AS i WHERE i.id = '.$invoice_id ;
		$db->setQuery($query);
		$discount = $db->loadResult();

		return $subtotal - $discount;

	}

	static function get_subtotal_items($invoice_id){

		$db = JFactory::getDBO();

		$query = ' SELECT SUM(it.value * it.amount - it.discount) FROM #__invoices_items AS it WHERE it.invoice_id = '.$invoice_id ;
		$db->setQuery($query);
		$subtotal = $db->loadResult();

		$query = ' SELECT discount FROM #__invoices_invoices AS i WHERE i.id = '.$invoice_id ;
		$db->setQuery($query);
		$discount = $db->loadResult();

		return $subtotal - $discount;

	}

	static function get_total($invoice, $update_taxes = false){

		$db = JFactory::getDBO();

		$taxes_value = 0;
		$thetaxvalue = 0 ;

		if(!isset($invoice->subtotal_items)) $invoice->subtotal_items = InvoicesHelper::get_subtotal_items($invoice->id);

		$subtotal1 = $invoice->subtotal ;
		$subtotal1_items = $invoice->subtotal_items ;

		//if($invoice->taxes){
		$query = ' SELECT tax.*, tai.value AS value, tai.id AS tai_id FROM #__invoices_taxes AS tax '
		.' LEFT JOIN #__invoices_tax_invoice AS tai ON (tai.tax_id = tax.id AND tai.reference_id = ' . $invoice->id . ' AND tai.type = 1) '
		.' WHERE tai.active = 1 '
		.' ORDER BY ordering, name ' ;
		$db->setQuery($query);
		$taxes = $db->loadObjectList();

		foreach($taxes as $tax){
			switch($tax->type){
				case "percent":

				if($tax->ordering == 1){ //first group of taxes
					if($tax->calculate_on == 1){
						$thetaxvalue = ( $tax->value / 100 ) * $invoice->subtotal_items ;
						$taxes_value += ( $tax->value / 100 ) * $invoice->subtotal_items ;
					}
					else{
						$thetaxvalue = ( $tax->value / 100 ) * $invoice->subtotal ;
						$taxes_value += ( $tax->value / 100 ) * $invoice->subtotal ;
					}
				}
				else if($tax->ordering == 2){ //second group of taxes
					if($tax->calculate_on == 1){
						$thetaxvalue = ( $tax->value / 100 ) * $subtotal1_items ;
						$taxes_value += ( $tax->value / 100 ) * $subtotal1_items ;
					}
					else{
						$thetaxvalue = ( $tax->value / 100 ) * $subtotal1 ;
						$taxes_value += ( $tax->value / 100 ) * $subtotal1 ;
					}
				}

				break;
				case "static":
				$thetaxvalue = $tax->value ;
				$taxes_value += $tax->value ;
				break;
			}

			if($tax->ordering == 1){
				$subtotal1 += $thetaxvalue ;
				$subtotal1_items += $thetaxvalue ;
			}

			if($update_taxes){
				$query = "UPDATE #__invoices_tax_invoice SET computed_value = '$thetaxvalue' WHERE id = " . $tax->tai_id ;
				$db->setQuery($query);
				$db->query();
			}
		}

		//}

		$total = $invoice->subtotal + $taxes_value ;

		return $total;

	}

	static function get_display_taxes($row){

		$db = JFactory::getDBO();

		$subtotal = $row->subtotal;
		$subtotal_items = $row->subtotal_items;

		$subtotal1 = $row->subtotal ;
		$subtotal1_items = $row->subtotal_items ;

		$display_taxes = array();

		//taxes in 2.1

		//individual item taxes
		$query = ' SELECT SUM((it.value * it.amount - it.discount)*(it.tax/100)) AS tax_value, it.tax_id '
		.' FROM #__invoices_items AS it '
		.' WHERE it.invoice_id = '.$row->id
		.' GROUP BY it.tax_id' ;
		$db->setQuery($query);
		$items_taxes = $db->loadObjectList('tax_id');

		//invoice-global taxes
		$query = ' SELECT tax.*, tai.value AS value, tai.active FROM #__invoices_taxes AS tax '
		.' LEFT JOIN #__invoices_tax_invoice AS tai ON (tai.tax_id = tax.id AND tai.reference_id = ' . $row->id . ' AND tai.type = 1 AND tai.active = 1) '
		.' ORDER BY ordering, name ' ;
		$db->setQuery($query);
		$taxes = $db->loadObjectList('id');

		foreach($taxes as $tax){

			$taxes_value = 0 ;

			//invoice-global taxes
			if($tax->active){

				switch($tax->type){
					case "percent":

					if($tax->ordering == 1){ //first group of taxes
						if($tax->calculate_on == 1) $taxes_value = ( $tax->value / 100 ) * $subtotal_items ;
						else $taxes_value = ( $tax->value / 100 ) * $subtotal ;

					}
					else if($tax->ordering == 2){ //second group of taxes
						if($tax->calculate_on == 1) $taxes_value = ( $tax->value / 100 ) * $subtotal1_items ;
						else $taxes_value = ( $tax->value / 100 ) * $subtotal1 ;

					}

					break;
					case "static":
					$taxes_value = $tax->value ;
					break;
				}

				if($tax->ordering == 1){
					$subtotal1 += $taxes_value ;
					$subtotal1_items += $taxes_value ;
				}

			}

			$taxobject = new stdClass();

			$taxobject->tax_id = $tax->id;

			//individual item taxes
			if(isset($items_taxes[$tax->id])) $taxobject->items_tax = $items_taxes[$tax->id] ;
			else {
				$taxobject->items_tax = new stdClass();
				$taxobject->items_tax->tax_value = 0 ;
				//if only global tax, we can show the percentage
				if($tax->active && $tax->type == "percent") $taxobject->tax_percentage = InvoicesHelper::format($tax->value, 'percent');
			}

			$taxobject->global_tax = $taxes_value;

			$taxobject->tax = $taxobject->items_tax->tax_value + $taxobject->global_tax;
			$taxobject->formatted_tax = InvoicesHelper::format($taxobject->tax, $row->currency_id);

			$display_taxes[$tax->id] = $taxobject ;
		}

		return $display_taxes;
	}

	static function get_total_from_id($invoice_id , $update_taxes = false){

		$total = 0;

		if($invoice_id){
			$db = JFactory::getDBO();
			$query = ' SELECT * FROM #__invoices_invoices WHERE id = ' . $invoice_id ;
			$db->setQuery($query);
			$invoice = $db->loadObject();

			if($invoice->id){
				$invoice->subtotal = InvoicesHelper::get_subtotal($invoice_id);

				$total = InvoicesHelper::get_total($invoice, $update_taxes);
			}

		}
		return $total;
	}

	static function download_pdf_button($id){

		$version = PHP_VERSION >= 5.0 ? true : false ;
		$quotes = get_magic_quotes_gpc();

		if(file_exists(JPATH_SITE.DS.'components'.DS.'com_invoices'.DS.'helpers'.DS.'dompdf'.DS.'autoload.inc.php') && $version && !$quotes){

			$mainframe = JFactory::getApplication();
			$uri = JFactory::getURI();

			if(!$mainframe->isSite()){
				$url = JRoute::_('index.php?option=com_invoices&view=invoice&format=dompdf&cid[]='.$id);
			}
			else $url = JRoute::_('index.php?option=com_invoices&view=invoice&format=dompdf&id='.$id);


			$return = "<a href='".$url."' title=\"".JText::_('DOWNLOAD_INVOICE_PDF')."\">".JHTML::image('components/com_invoices/assets/images/page_white_acrobat.png', JText::_('DOWNLOAD_INVOICE_PDF'))."</a>" ;
		}
		else $return = "";
		return $return ;

	}

	static function download_pdf_link($id){

		$version = PHP_VERSION >= 5.0 ? true : false ;
		$quotes = get_magic_quotes_gpc();

		if(file_exists(JPATH_SITE.DS.'components'.DS.'com_invoices'.DS.'helpers'.DS.'dompdf'.DS.'autoload.inc.php') && $version && !$quotes){

			$mainframe = JFactory::getApplication();
			$uri = JFactory::getURI();


			if(!$mainframe->isSite()){
				$url = JRoute::_('index.php?option=com_invoices&view=invoice&format=dompdf&cid[]='.$id, false);
			}
			else $url = JRoute::_('index.php?option=com_invoices&view=invoice&format=dompdf&id='.$id);


			$return = $url;
		}
		else $return = "";
		return $return ;

	}

	static function pdf_enabled(){

		$version = PHP_VERSION >= 5.0 ? true : false ;
		$quotes = get_magic_quotes_gpc();

		if(file_exists(JPATH_SITE.DS.'components'.DS.'com_invoices'.DS.'helpers'.DS.'dompdf'.DS.'autoload.inc.php') && $version && !$quotes){

			return true;
		}
		else return false;

	}

	static function view_modal_button($id){

		$modal = true ;

		if($modal){
			$link = "&tmpl=component" ;
			$rel = 'rel="{ size: {x: 800, y: 500}, handler: \'iframe\'}"';
		}

		$mainframe = JFactory::getApplication();
		$uri = JFactory::getURI();

		$url = JRoute::_('index.php?option=com_invoices&view=invoice&id='.$id.$link);

		if(!$mainframe->isSite()){
			//$url = $uri->root().'index.php?option=com_invoices&view=invoice&id='.$id.$link;
			$url = JRoute::_('index.php?option=com_invoices&view=invoice&cid[]='.$id.$link);
		}

		$return = "<a class='modal' ".$rel." href='".$url."' title=\"".JText::_('VIEW_INVOICE_DETAILS')."\">".JHTML::image('components/com_invoices/assets/images/magnifier.png', JText::_('VIEW_INVOICE_DETAILS'))."</a>" ;
		return $return ;

	}

	static function view_online_button($id){

		$mainframe = JFactory::getApplication();
		$uri = JFactory::getURI();

		$url = JRoute::_('index.php?option=com_invoices&view=invoice&id='.$id );

		if(!$mainframe->isSite()){
			//$url = $uri->root().'index.php?option=com_invoices&view=invoice&id='.$id.'&tmpl=component';
			$url = JRoute::_('index.php?option=com_invoices&view=invoice&cid[]='.$id.'&tmpl=component');
		}

		$return = "<a target='_blank' href='".$url."' title=\"".JText::_('VIEW_INVOICE_ONLINE')."\">".JHTML::image('components/com_invoices/assets/images/invoice.png', JText::_('VIEW_INVOICE_ONLINE'))."</a>" ;
		return $return ;

	}


	static function send_email_button($id, $type = "invoice"){

		$mainframe = JFactory::getApplication();

		if(!$mainframe->isSite()){
			$url = JRoute::_('index.php?option=com_invoices&controller='.$type.'&task=send_email&cid[]='.$id);
		}
		else{
			$url = JRoute::_('index.php?option=com_invoices&task=send&id='.$id);
		}

		$return = "<a href='".$url."' title=\"".JText::_('SEND_EMAIL')."\">".JHTML::image('components/com_invoices/assets/images/email.png', JText::_('SEND_EMAIL'))."</a>" ;
		return $return ;

	}

	static function send_email_link($id, $type = "invoice"){

		$mainframe = JFactory::getApplication();

		if(!$mainframe->isSite()){
			$url = JRoute::_('index.php?option=com_invoices&controller='.$type.'&task=send_email&cid[]='.$id, false);
		}
		else{
			$url = JRoute::_('index.php?option=com_invoices&task=send&id='.$id);
		}

		return $url ;

	}


	static function create_invoice($data, $items, $payments){
		$mainframe = JFactory::getApplication();
		$model = InvoicesHelper::getInvoiceAdminModel();
		require_once( JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_invoices'.DS.'tables'.DS.'invoice.php' );
		require_once( JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_invoices'.DS.'tables'.DS.'contact.php' );
		require_once( JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_invoices'.DS.'tables'.DS.'item.php' );
		require_once( JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_invoices'.DS.'tables'.DS.'payment.php' );
		require_once( JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_invoices'.DS.'tables'.DS.'taxinvoice.php' );
		if ($invoice_id = $model->store($data, $items, $payments)) {
			$msg = JText::_( 'INVOICE_SAVED' );
			$type = "message" ;
		} else {
			$msg = JText::_( 'ERROR_SAVING_INVOICE' );
			$type = "error" ;
		}

		return $invoice_id;
	}

	static function getInvoiceAdminModel()
	{
		if (!class_exists( 'InvoicesModelInvoice' ))
		{
			// Build the path to the model based upon a supplied base path
			$path = JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_invoices'.DS.'models'.DS.'invoice.php';
			$false = false;

			// If the model file exists include it and try to instantiate the object
			if (file_exists( $path )) {
				require_once( $path );
				if (!class_exists( 'InvoicesModelInvoice' )) {
					JError::raiseWarning( 0, 'View class InvoicesModelInvoice not found in file.' );
					return $false;
				}
			} else {
				JError::raiseWarning( 0, 'View InvoicesModelInvoice not supported. File not found.' );
				return $false;
			}
		}

		$model = new InvoicesModelInvoice();
		return $model;
	}

	static function getStatus(){
		$status = array();

		$status[] = "paid";
		$status[] = "pending";
		$status[] = "partial_paid";
		$status[] = "pastdue";
		$status[] = "refunded";
		$status[] = "partial_refunded";
		$status[] = "corrected";

		return $status;
	}

	static function getQuoteStatus(){
		$status = array();

		$status[] = "pending";
		$status[] = "accepted";
		$status[] = "accepted_client";
		$status[] = "cancelled";
		$status[] = "rejected";
		$status[] = "rejected_client";
		$status[] = "expired";

		return $status;
	}

	static function getStatusPaymentFilters(){
		$status = array();

		$status[] = (object)array("id" => "unpaid", "name" => 'UNPAID_SIMPLE');
		$status[] = (object)array("id" => "paid", "name" => 'PAID');
		$status[] = (object)array("id" => "pending", "name" => 'PENDING_VALIDATION');

		return $status;
	}

	static function getPaymentStatus(){
		$status = array();

		$status[0] = JText::_('UNPAID');
		$status[1] = JText::_('PAID');
		$status[2] = JText::_('UNPAID_ONTIME');
		$status[3] = JText::_('PENDING_VALIDATION');

		return $status;
	}

	static function getPaymentData($payment_id){

		$db = JFactory::getDBO();

		$query = ' SELECT pa.* FROM #__invoices_payments AS pa WHERE pa.id = '.$payment_id;
		$db->setQuery($query);
		$payment = $db->loadObject();

		return $payment;

	}

	static function getNextRecurrencyDate($invoice){

		if($invoice["rec_year"]) $months = $invoice["rec_year"] * 12 + $invoice["rec_month"] ;
		else $months = $invoice["rec_month"] ;

		$thetime = $invoice["rec_nextdate"] . " + ".$months." months + ".$invoice["rec_day"]." days" ;
		//echo $thetime;die;

		$nextdate = strtotime($thetime) ;
		$nextdate = date("Y-m-d", $nextdate) ;

		return $nextdate ;

	}

	static function getPaymentLink($payment_id){
		$uri = JFactory::getURI();

		$link = $uri->base() . 'index.php?option=com_invoices&view=payment&id='.$payment_id ;
		$link = str_replace("administrator/","",$link) ;
		return $link;
	}

	static function getInvoiceLink($invoice_id){
		$uri = JFactory::getURI();

		$link = $uri->base() . 'index.php?option=com_invoices&view=invoice&id='.$invoice_id ;
		$link = str_replace("administrator/","",$link) ;
		return $link;
	}

	static function getInvoicePublicLink($invoice_id){
		$uri = JFactory::getURI();
		$db = JFactory::getDBO();

		$query = " SELECT auth_code FROM #__invoices_invoices WHERE id = ".$invoice_id ;
		$db->setQuery($query);
		$auth_code = $db->loadResult();

		$link = $uri->base() . 'index.php?option=com_invoices&view=invoice&id='.$invoice_id .'&auth_code='.$auth_code;
		$link = str_replace("administrator/","",$link) ;
		return $link;
	}

	static function getQuoteAcceptLink($quote_id){
		$uri = JFactory::getURI();
		$db = JFactory::getDBO();

		$query = " SELECT auth_code FROM #__invoices_invoices WHERE id = ".$quote_id ;
		$db->setQuery($query);
		$auth_code = $db->loadResult();

		$link = $uri->base() . 'index.php?option=com_invoices&task=accept_quote&id='.$quote_id .'&auth_code='.$auth_code;
		$link = str_replace("administrator/","",$link) ;
		return $link;
	}

	static function getQuoteRejectLink($quote_id){
		$uri = JFactory::getURI();
		$db = JFactory::getDBO();

		$query = " SELECT auth_code FROM #__invoices_invoices WHERE id = ".$quote_id ;
		$db->setQuery($query);
		$auth_code = $db->loadResult();

		$link = $uri->base() . 'index.php?option=com_invoices&task=reject_quote&id='.$quote_id .'&auth_code='.$auth_code;
		$link = str_replace("administrator/","",$link) ;
		return $link;
	}

	static function getInvoiceNum($real_invoice_num, $type = 1){
		$params = JComponentHelper::getParams( 'com_invoices' );
		if($type == 1) $format = $params->get('invoice_num_format') ;
		elseif($type == 2) $format = $params->get('quote_num_format') ;

		$real_invoice_num = str_pad($real_invoice_num, $params->get('invoice_number_digits', 0), '0', STR_PAD_LEFT);

		$string = str_replace("[num]", $real_invoice_num, $format) ;
		$string = str_replace("[yyyy]", date("Y"), $string) ;
		$string = str_replace("[mm]", date("m"), $string) ;
		$string = str_replace("[dd]", date("d"), $string) ;

		return $string ;

	}

	static function getInvoiceStatus($invoice, $total, $total_payments, $amount_outstanding){

		$params = JComponentHelper::getParams( 'com_invoices' );

		$status = $invoice->status ;
		if(!$status && $params->get('computestatus') && $invoice->type == 1){
			//if the status is not set, we calculate it

			$status = InvoicesHelper::getComputedInvoiceStatus($invoice, $total, $total_payments, $amount_outstanding);
			//$status = $invoice->computed_status;
		}

		return $status;
	}

	static function getComputedInvoiceStatus($invoice, $total, $total_payments = false, $amount_outstanding = false){

		$db = JFactory::getDBO();

		$params = JComponentHelper::getParams( 'com_invoices' );

		if(!$total_payments){
			$query = " SELECT SUM(payment_amount) FROM #__invoices_payments WHERE payment_status = 1 AND invoice_id = ".$invoice->id ;
			$db->setQuery($query);
			$total_payments = $db->loadResult();
		}
		if(!$amount_outstanding){
			$query = " SELECT SUM(payment_amount) FROM #__invoices_payments WHERE payment_status = 0 AND invoice_id = ".$invoice->id ;
			$db->setQuery($query);
			$amount_outstanding = $db->loadResult();
		}

		$total_payments = round($total_payments, $params->get('decimals', 2));
		$total = round($total, $params->get('decimals', 2));

		if($amount_outstanding == 0 && $total_payments >= $total){
			$status = "paid"; //paid in full
		}
		elseif($invoice->invoice_duedate != "0000-00-00" && $invoice->invoice_duedate != "0000-00-00 00:00:00" && $invoice->invoice_duedate != "" ){
			if(strtotime($invoice->invoice_duedate) <= time()) {
				$status = "pastdue"; //past due date
			}
			else {
				if($amount_outstanding && $total_payments){
					$status = "partial_paid"; //partially paid
				}
				else $status = "pending"; //pending
			}
		}
		elseif($invoice->invoice_duedate == "0000-00-00" || $invoice->invoice_duedate == "0000-00-00 00:00:00" || !$invoice->invoice_duedate){

			if($amount_outstanding && $total_payments){
				$status = "partial_paid"; //partially paid
			}
			elseif($total_payments){
				$status = "partial_paid"; //partially paid
			}
			else $status = "pending"; //pending
		}

		return $status;
	}

	static function updateComputedStatus($invoice_id, $calculate_total = false, $create_auth_code = false){
		$db = JFactory::getDBO();

		$query = " SELECT * FROM #__invoices_invoices WHERE id = ".$invoice_id ;
		$db->setQuery($query);
		$invoice = $db->loadObject();

		$sql_total = "";
		$sql_auth_code = "";

		if($calculate_total) {
			$computed_total = InvoicesHelper::get_total_from_id($invoice->id) ;
			$computed_subtotal = InvoicesHelper::get_subtotal_items($invoice->id) ;
			$sql_total = ', computed_total = '.$computed_total.', computed_subtotal = '.$computed_subtotal ;
		}
		else $computed_total = $invoice->computed_total ;

		if(!$invoice->auth_code) {
			$auth_code = InvoicesHelper::genRandomCode() ;
			$sql_auth_code = ', auth_code = "'.$auth_code.'" ' ;
		}
		else $sql_auth_code = "" ;

		$computed_status = InvoicesHelper::getComputedInvoiceStatus($invoice, $computed_total) ;

		$query = 	' UPDATE #__invoices_invoices SET '.
		' computed_status =  "'.$computed_status.'" '.
		$sql_total .
		$sql_auth_code .
		' WHERE id = '.$invoice_id .
		' LIMIT 1 ';

		$db->setQuery($query);
		$db->query();

		//added 2.1
		InvoicesHelper::updateComputedData($invoice_id);
	}

	static function updateComputedData($invoice_id){
		$db = JFactory::getDBO();

		$query = " SELECT * FROM #__invoices_invoices WHERE id = ".$invoice_id ;
		$db->setQuery($query);
		$row = $db->loadObject();

		$computed_total = InvoicesHelper::get_total_from_id($invoice_id, true) ;
		$computed_subtotal = InvoicesHelper::get_subtotal_items($invoice_id);

		$computed = new StdClass();
		$computed->total = $computed_total;
		$computed->subtotal = InvoicesHelper::get_subtotal($invoice_id);
		$computed->subtotal_items = $computed_subtotal;

		$query = ' SELECT SUM(pa.payment_amount) AS total_paid, COUNT(DISTINCT pa.id) AS paid_payments FROM #__invoices_payments AS pa WHERE pa.invoice_id = '.$invoice_id.' AND pa.payment_status = 1 ' ;
		$db->setQuery($query);
		$computed->total_paid = $db->loadObject();

		$query = ' SELECT SUM(pa.payment_amount) AS total_unpaid, COUNT(DISTINCT pa.id) AS unpaid_payments FROM #__invoices_payments AS pa WHERE pa.invoice_id = '.$invoice_id.' AND pa.payment_status = 0 ' ;
		$db->setQuery($query);
		$computed->total_unpaid = $db->loadObject();

		$row->subtotal = $computed->subtotal;
		$row->subtotal_items = $computed_subtotal;

		//store taxes in json
		$computed->taxes = InvoicesHelper::get_display_taxes($row);

		$computed = json_encode($computed);

		$query = $db->getQuery(true);
		// Fields to update.
		$fields = array(
			$db->quoteName('computed') . ' = ' . $db->quote($computed),
			$db->quoteName('computed_subtotal') . ' = ' . $db->quote($computed_subtotal)
		);

		// Conditions for which records should be updated.
		$conditions = array(
			$db->quoteName('id') . ' = '.$invoice_id
		);

		$query->update($db->quoteName('#__invoices_invoices'))->set($fields)->where($conditions);

		$db->setQuery($query);

		$db->execute();
	}

	static function render_status($status){
		switch($status){
			case "paid": case "payed": case "accepted": case "accepted_client":
			$status = "<span class='label label-success'>".JText::_($status)."</span>" ;
			break;
			case "pending":case "partial_paid":
			$status = "<span class='label label-warning'>".JText::_($status)."</span>" ;
			break;
			case "pastdue": case "rejected": case "rejected_client":
			$status = "<span class='label label-important'>".JText::_($status)."</span>" ;
			break;
			case "refunded": case "partial_refunded": case "cancelled": case "expired":
			$status = "<span class='label label-inverse'>".JText::_($status)."</span>" ;
			break;
			case "corrected":
			$status = "<span class='label label-info'>".JText::_($status)."</span>" ;
			break;
			default:
			$status = "<span class='label label-default'>".JText::_("NOT_SETTED")."</span>" ;
			break;
		}

		return $status;
	}

	static function render_status_class($status){
		switch($status){
			case "paid": case "payed": case "accepted": case "accepted_client":
			$status = "success" ;
			break;
			case "pending":case "partial_paid":
			$status = "warning" ;
			break;
			case "pastdue": case "rejected": case "rejected_client":
			$status = "danger" ;
			break;
			case "refunded": case "partial_refunded": case "cancelled": case "expired":
			$status = "inverse" ;
			break;
			case "corrected":
			$status = "info" ;
			break;
			default:
			$status = "default" ;
			break;
		}

		return $status;
	}

	static function getThePaymentStatus($payment){

		if($payment->payment_status){
			$thestatus = 1;

		}
		elseif($payment->payment_duedate != "0000-00-00 00:00:00" && !$payment->payment_status){
			if(strtotime($payment->payment_duedate) <= time()) {

				$thestatus = 0;

			}
			else {

				$thestatus = 2;

			}
		}
		elseif($payment->payment_duedate == "0000-00-00 00:00:00"){
			$thestatus = 2;

		}

		if($payment->payment_status == 2){
			$thestatus = 3;

		}

		return $thestatus ;
	}

	static function render_status_payment($status){

		$payment_status = InvoicesHelper::getPaymentStatus();

		switch($status){
			case 0:
			$status = "<span class='label label-important'>".$payment_status[$status]."</span>" ;
			break;
			case 1:
			$status = "<span class='label label-success'>".$payment_status[$status]."</span>" ;
			break;
			case 2:
			$status = "<span class='label label-warning'>".$payment_status[$status]."</span>" ;
			break;
			case 3:
			$status = "<span class='label label-default'>".$payment_status[$status]."</span>" ;
			break;
		}

		return $status;
	}

	static function render_num_payments_received($num){

		switch($num){
			case 0:
			$status = "<span class='badge badge-default badge-secondary'>".$num."</span>" ;
			break;
			default:
			$status = "<span class='badge badge-success'>".$num."</span>" ;
			break;
		}

		return $status;
	}

	static function render_num_pending_payments($num){

		switch($num){
			case 0:
			$status = "<span class='badge'>".$num."</span>" ;
			break;
			default:
			$status = "<span class='badge badge-warning'>".$num."</span>" ;
			break;
		}

		return $status;
	}

	static function PDFavailable(){
		return InvoicesHelper::pdf_enabled();
	}

	static function genRandomCode($length = 64)
	{
		$salt = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		$base = strlen($salt);
		$makepass = '';

		/*
		* Start with a cryptographic strength random string, then convert it to
		* a string with the numeric base of the salt.
		* Shift the base conversion on each character so the character
		* distribution is even, and randomize the start shift so it's not
		* predictable.
		*/
		$random = JCrypt::genRandomBytes($length + 1);
		$shift = ord($random[0]);

		for ($i = 1; $i <= $length; ++$i)
		{
			$makepass .= $salt[($shift + ord($random[$i])) % $base];
			$shift += ord($random[$i]);
		}

		return $makepass;
	}

	static function get_string_between($string, $start, $end){
		$string = " ".$string;
		$ini = strpos($string,$start);
		if ($ini == 0) return "";
		$ini += strlen($start);
		$len = strpos($string,$end,$ini) - $ini;
		return substr($string,$ini,$len);
	}

	static function replace_string_between($string, $start, $end, $replace){
		$string = " ".$string;
		$ini = strpos($string,$start);
		if ($ini == 0) return $string;
		$ini += strlen($start);
		$len = strpos($string,$end,$ini) - $ini;
		return substr_replace($string,$replace,$ini,$len);
	}

	static function updateSentDate($id){
		$db = JFactory::getDBO();

		$query = " UPDATE #__invoices_invoices SET `last_sent` = NOW() WHERE id = ".$id;
		$db->setQuery($query);
		$db->query();
	}

	static function allowEdit($recordId = 0, $ownerId = 0)
	{
		if(!$recordId){
			$array = JRequest::getVar('cid',  0, '', 'array');
			$recordId = (int)$array[0];
		}

		$user = JFactory::getUser();
		//new item
		if(!$recordId){
			if ($user->authorise('core.create', 'com_invoices' ))
			{
				return true;
			}
			else return false;
		}

		// Check general edit permission first.
		if ($user->authorise('core.edit', 'com_invoices' ))
		{
			return true;
		}

		// Fallback on edit.own.
		// First test if the permission is available.
		if ($user->authorise('core.edit.own', 'com_invoices' ))
		{
			// Now test the owner is the user.
			if(!$ownerId){
				$db = JFactory::getDBO();
				$query = ' SELECT created_by FROM #__invoices_invoices WHERE id = '.$recordId;
				$db->setQuery($query);
				$ownerId = $db->loadResult();
			}

			if (empty($ownerId) && $recordId)
			{

				return false;

			}

			// If the owner matches 'me' then do the test.
			if ($ownerId == $user->id)
			{
				return true;
			}
		}

		return false;
	}


	static function canDelete($recordId = 0, $ownerId = 0)
	{

		$user = JFactory::getUser();

		return $user->authorise('core.delete', 'com_invoices');

	}

	static function canEditState($recordId = 0, $ownerId = 0)
	{
		$user = JFactory::getUser();

		return $user->authorise('core.edit.state', 'com_invoices');
	}

	static function versionBox()
	{
		$db = JFactory::getDBO();
		$query = 	' SELECT manifest_cache FROM #__extensions WHERE element = "com_invoices" AND type = "component" ';
		$db->setQuery( $query );
		$extenison_info = $db->loadObject();
		$extenison_info = json_decode($extenison_info->manifest_cache);
		$installed_version = $extenison_info->version;

		$versionBox = '';
		$versionBox .= "<div class='row-fluid version-box hidden-xs'><div class=''><div class='container-fluid'><div class='row-fluid sys-info-title'><span>".JText::_('SYSTEM_INFO')."</span></div><div class='row-fluid'><span>".JText::sprintf('INSTALLED_VERSION', $installed_version)."</span></div><div class='row-fluid'><span>".JText::_('LATEST_VERSION')."</span><span id='latest-version'>".$installed_version."</span></div><div class='row-fluid'><div id='update-info'>".JText::_('SEARCHING_UPDATES')."</div></div></div></div></div>";

		return $versionBox;
	}

	public static function addSubmenu($vName)
	{

		JHtmlSidebar::addEntry(
			JText::_('INVOICES'),
			'index.php?option=com_invoices',
			$vName == 'invoices'
		);
		JHtmlSidebar::addEntry(
			JText::_('QUOTES'),
			'index.php?option=com_invoices&controller=quotes',
			$vName == 'quotes'
		);
		JHtmlSidebar::addEntry(
			JText::_('PAYMENTS'),
			'index.php?option=com_invoices&controller=payments',
			$vName == 'payments'
		);
		JHtmlSidebar::addEntry(
			JText::_('CONTACTS'),
			'index.php?option=com_invoices&controller=contacts',
			$vName == 'contacts'
		);
		JHtmlSidebar::addEntry(
			JText::_('TAXES'),
			'index.php?option=com_invoices&controller=taxes',
			$vName == 'taxes'
		);
		JHtmlSidebar::addEntry(
			JText::_('TEMPLATES'),
			'index.php?option=com_invoices&controller=templates',
			$vName == 'templates'
		);
		JHtmlSidebar::addEntry(
			JText::_('PRODUCTS'),
			'index.php?option=com_invoices&controller=templateitems',
			$vName == 'products'
		);
		JHtmlSidebar::addEntry(
			JText::_('PAYMENT_OPTIONS'),
			'index.php?option=com_plugins&filter_folder=invoices'
		);
		JHtmlSidebar::addEntry(
			JText::_('CONFIGURATION_OPTIONS'),
			'index.php?option=com_config&view=component&component=com_invoices&path=&return='.urlencode(base64_encode('index.php?option=com_invoices'))
		);
		JHtmlSidebar::addEntry(
			JText::_('CURRENCIES'),
			'index.php?option=com_invoices&controller=currencies',
			$vName == 'currencies'
		);
	}

	static function getOrderOptions(){
		$return = array();

		$option = new stdClass();
		$option->value = "i.invoice_date,desc";
		$option->name = JText::_( 'ORDER_DATE_DESC' );
		$return[] = $option;

		$option = new stdClass();
		$option->value = "i.invoice_date,asc";
		$option->name = JText::_( 'ORDER_DATE_ASC' );
		$return[] = $option;

		$option = new stdClass();
		$option->value = "i.to_name,desc";
		$option->name = JText::_( 'ORDER_NAME_DESC' );
		$return[] = $option;

		$option = new stdClass();
		$option->value = "i.to_name,asc";
		$option->name = JText::_( 'ORDER_NAME_ASC' );
		$return[] = $option;

		$option = new stdClass();
		$option->value = "i.computed_total,asc";
		$option->name = JText::_( 'ORDER_VALUE_DESC' );
		$return[] = $option;

		$option = new stdClass();
		$option->value = "i.computed_total,desc";
		$option->name = JText::_( 'ORDER_VALUE_ASC' );
		$return[] = $option;

		return $return;
	}

	static function build_order_header($name, $value, $filter_order, $filter_order_dir){
		if($filter_order == $value) $hidden = "";
		else $hidden = "style='display:none'" ;

		if(strtoupper($filter_order_dir) == "ASC") {
			$dir = "DESC" ;
			$class = "";
		}
		elseif(strtoupper($filter_order_dir) == "DESC") {
			$dir = "ASC" ;
			$class = "-alt";
		}

		$return = "<a href='#' onclick=\"order_by('".$value."',jQuery(this));return false;\" data-order-dir='".$dir."' >".
		JText::_($name)." <span class='glyphicon glyphicon-sort-by-attributes".$class." order_dir_button' ".$hidden."></span></a>";

		return $return;
	}

	static function getCurrencies()
	{
		$db = JFactory::getDBO();

		$query = 	' SELECT * FROM #__invoices_currencies '.
							' WHERE currency_published = 1 '.
							' ORDER BY id ASC ';
		$db->setQuery( $query );
		$currencies = $db->loadObjectList('id');

		return $currencies;

	}

	static function getDefaultCurrency(){

		$params = JComponentHelper::getParams( 'com_invoices' );

		$db = JFactory::getDBO();
		$query = "SELECT * FROM #__invoices_currencies WHERE id = ".(int)$params->get('currency_id', 1);
		$db->setQuery($query);
		$currency = $db->loadObject();

		return $currency;

	}

	static function percentCurrency($currency = false){

		$params = JComponentHelper::getParams( 'com_invoices' );

		if(!$currency) $currency = InvoicesHelper::getDefaultCurrency();

		$return = new stdClass();
		$return->symbol_before = "";
		$return->symbol_after = "%";
		$return->decimals = (int)$params->get('decimals_tax', 0);
		$return->thousands = $currency->thousands;
		$return->decpoint = $currency->decpoint;

		return $return;

	}

	public static function templateToVue($template)
	{
		//the language tags
		$pattern = '/\[\[(.*?)\]\]/' ;

		$matches = array();
		preg_match_all($pattern, $template, $matches);

		foreach($matches[1] as $value){
		    $template = str_replace("[[".$value."]]", "{{ '".$value."' | translate }}", $template);
		}

		//ITEMS
		$items = InvoicesHelper::get_string_between($template, "<!--ITEMS-->", "<!--/ITEMS-->");

		$search = array(
			"<tr>",

			"{sku}",
			"{name}",
			"{desc}",
			"{value}",
			"{amount}",
			"{discount}",
			"{tax}",
			"{item_tax_value}",
			"{item_with_tax}",
			"{tax_name}",
			"{item_subtotal_no_discount}",
			"{item_subtotal}",
			"{item_total}",
		);
		$replace = array(
			"<tr v-for='(item, index) in invoice.items'>",

			"{{ item.sku }}",
			"{{ item.name }}",
			"{{ item.desc }}",
			"{{ item.value | currency(invoice.currency_id) }}",
			"{{ item.amount }}",
			"{{ item.discount | currency(invoice.currency_id) }}",
			"{{ item.tax | taxpercentage }}",
			"{{ invoice.taxItem(index) | currency(invoice.currency_id) }}",
			"{{ invoice.itemWithTax(index) | currency(invoice.currency_id) }}",
			"{{ item.tax_id | taxname | translate }}",
			"{{ invoice.subtotalItemNoDiscount(index) | currency(invoice.currency_id) }}",
			"{{ invoice.subtotalItem(index) | currency(invoice.currency_id) }}",
			"{{ invoice.totalItem(index) | currency(invoice.currency_id) }}",
		);

		$items = str_replace($search, $replace, $items) ;

		$template = InvoicesHelper::replace_string_between($template, "<!--ITEMS-->", "<!--/ITEMS-->", "{items}");

		//TAXES
		$taxes = InvoicesHelper::get_string_between($template, "<!--TAXES-->", "<!--/TAXES-->");

		$search = array(
			"<tr>",

			"{name}",
			"{value}",
			"{tax_value}",
			"{calculated_on_amount}",
		);
		$replace = array(
			"<tr v-for='(tax, index) in invoice.taxes' v-show='tax.active'>",

			"{{ tax.name | translate }}",
			"{{ invoice.globaltax(tax.id) | currency(invoice.currency_id) }}",
			"{{ tax.tax_value | taxpercentageorflat(tax, invoice.currency_id) }}",
			"{{ tax.calculated_on_amount | currency(invoice.currency_id) }}",
		);

		$taxes = str_replace($search, $replace, $taxes) ;

		$template = InvoicesHelper::replace_string_between($template, "<!--TAXES-->", "<!--/TAXES-->", "{taxes}");

		//GROUPED TAXES
		$grouped_taxes = InvoicesHelper::get_string_between($template, "<!--GROUPED_TAXES-->", "<!--/GROUPED_TAXES-->");

		$search = array(
			"<tr>",

			"{name}",
			"{value}",
			"{tax_value}",
			"{calculated_on_amount}",
		);
		$replace = array(
			"<tr v-for='(tax, index) in invoice.individualTaxes()'>",

			"{{ tax.name | translate }}",
			"{{ tax.value | currency(invoice.currency_id) }}",
			"{{ tax.percent_value | taxpercentage }}",
			"{{ tax.calculated_on_amount | currency(invoice.currency_id) }}",
		);

		$grouped_taxes = str_replace($search, $replace, $grouped_taxes) ;

		$template = InvoicesHelper::replace_string_between($template, "<!--GROUPED_TAXES-->", "<!--/GROUPED_TAXES-->", "{grouped_taxes}");

		//GROUPED TAXES TOTAL
		$grouped_taxes_total = InvoicesHelper::get_string_between($template, "<!--GROUPED_TAXES_TOTAL-->", "<!--/GROUPED_TAXES_TOTAL-->");

		$search = array(
			"<tr>",

			"{name}",
			"{value}",
			"{tax_value}",
			"{calculated_on_amount}",
		);
		$replace = array(
			"<tr v-for='(tax, index) in invoice.individual_taxes_totals'>",

			"{{ tax.name | translate }}",
			"{{ tax.value | currency(invoice.currency_id) }}",
			"{{ tax.tax_value | taxpercentage }}",
			"{{ tax.calculated_on_amount | currency(invoice.currency_id) }}",
		);

		$grouped_taxes_total = str_replace($search, $replace, $grouped_taxes_total) ;

		$template = InvoicesHelper::replace_string_between($template, "<!--GROUPED_TAXES_TOTAL-->", "<!--/GROUPED_TAXES_TOTAL-->", "{grouped_taxes_total}");

		//PAYMENTS
		$payments = InvoicesHelper::get_string_between($template, "<!--PAYMENTS-->", "<!--/PAYMENTS-->");

		$search = array(
			"<tr>",

			"{description}",
			"{duedate}",
			"{payment_datetime}",
			"{amount}",
			"href=\"{payment_link}\"",
			"{payment_status}",
		);
		$replace = array(
			"<tr v-for='(payment, index) in getPaidPayments()'>",

			"{{ payment.payment_description }}",
			"{{ payment.payment_duedate | date('D MMMM YYYY', undefined, invoice.language) }}",
			"{{ payment.payment_datetime | date('D MMMM YYYY', undefined, invoice.language) }}",
			"{{ payment.payment_amount | currency(invoice.currency_id) }}",
			":href=\"payment.payment_link\"",
			"<span :class=\"'label label-' + invoice.getPaymentStatusClass(payment)\">{{ invoice.getPaymentStatusName(payment) | translate }}</span>",
		);

		$payments = str_replace($search, $replace, $payments) ;

		$template = InvoicesHelper::replace_string_between($template, "<!--PAYMENTS-->", "<!--/PAYMENTS-->", "{payments}");

		//PAYMENTS2
		$payments2 = InvoicesHelper::get_string_between($template, "<!--PAYMENTS2-->", "<!--/PAYMENTS2-->");

		$search = array(
			"<tr>",

			"{description}",
			"{duedate}",
			"{payment_datetime}",
			"{amount}",
			"href=\"{payment_link}\"",
			"{payment_status}",
		);
		$replace = array(
			"<tr v-for='(payment, index) in getUnpaidPayments()'>",

			"{{ payment.payment_description }}",
			"{{ payment.payment_duedate | date('D MMMM YYYY', undefined, invoice.language) }}",
			"{{ payment.payment_datetime | date('D MMMM YYYY', undefined, invoice.language) }}",
			"{{ payment.payment_amount | currency(invoice.currency_id) }}",
			":href=\"payment.payment_link\" target='_blank'",
			"<span :class=\"'label label-' + invoice.getPaymentStatusClass(payment)\">{{ invoice.getPaymentStatusName(payment) | translate }}</span>",
		);

		$payments2 = str_replace($search, $replace, $payments2) ;

		$template = InvoicesHelper::replace_string_between($template, "<!--PAYMENTS2-->", "<!--/PAYMENTS2-->", "{payments2}");

		//the tags
		$search = array(
			"{to_name}",
			"{to_company}",
			"{to_email}",
			"{to_address}",
			"{from_name}",
			"{from_address}",
			"{from_num}",
			"{from_url}",
			"{from_email}",
			"{from_phone}",

			"{invoice_date}",
			"{notes}",
			"{invoice_num}",

			"{items}",

			"{subtotal}",

			"{taxes}",

			"{grouped_taxes}",

			"{grouped_taxes_total}",

			"{total}",

			"{payments}",

			"{payments2}",

			"{total_payments}",
			"{amount_outstanding}",

			"{to_zipcode}",
			"{to_city}",
			"{to_state}",
			"{to_country}",
			"{to_vatid}",

			"{discount}",
			"{invoice_duedate}",

			"{status}",
			"{num_payments_received}",
			"{num_pending_payments}",
			"{to_phone}",
			"{invoice_link}",
			"{invoice_unlogged_link}",

			"{subtotal_items}",
			"{subtotal_items_less_total_discount}",

			"{external_ref}",
			"{paynow_button}",

			"{total_items_tax}",
			"{subtotal_items_no_discount}",
			"{total_items_discount}",
			"{accept_button}",
			"{reject_button}"

		);
		$replace = array(
			"{{ invoice.to_name }}",
			"{{ invoice.to_company }}",
			"{{ invoice.to_email }}",
			"<div v-html='nl2br(invoice.to_address)'></div>",
			"{{ invoice.from_name }}",
			"<div v-html='nl2br(invoice.from_address)'></div>",
			"{{ invoice.from_num }}",
			"{{ invoice.from_url }}",
			"{{ invoice.from_email }}",
			"{{ invoice.from_phone }}",

			"{{ invoice.invoice_date | date('D MMMM YYYY', undefined, invoice.language) }}",
			"<div v-html='invoice.notes'></div>",
			"{{ invoice.invoice_num }}",

			//ITEMS
			$items,

			"{{ invoice.subtotal_items() | currency(invoice.currency_id) }}",

			//TAXES
			$taxes,

			//GROUPED TAXES
			$grouped_taxes,

			//GROUPED TAXES TOTAL
			$grouped_taxes_total,

			"{{ invoice.thetotal() | currency(invoice.currency_id) }}",

			//PAYMENTS
			$payments,

			//PAYMENTS2
			$payments2,

			"{{ invoice.total_payments }}",
			"{{ invoice.total_unpaid | currency(invoice.currency_id) }}",
			"{{ invoice.to_zipcode }}",
			"{{ invoice.to_city }}",
			"{{ invoice.to_state }}",
			"{{ invoice.to_country }}",
			"{{ invoice.to_vatid }}",

			"{{ invoice.discount | currency(invoice.currency_id) }}",
			"{{ invoice.invoice_duedate | date('D MMMM YYYY', undefined, invoice.language) }}",

			"<span :class=\"'label label-' + status_class\">{{ status_name }}</span>",
			"{{ invoice.num_payments_received }}",
			"{{ invoice.num_pending_payments }}",
			"{{ invoice.to_phone }}",
			"{{ invoice.link }}",
			"{{ invoice.public_link }}",

			"{{ invoice.subtotal_items() | currency(invoice.currency_id) }}",
			"{{ invoice.subtotal_items() | currency(invoice.currency_id) }}",

			"{{ invoice.external_ref }}",
			"<div v-html='paynow_button'></div>",

			"{{ invoice.individual_taxes_totals | currency(invoice.currency_id) }}",
			"{subtotal_items_no_discount}",
			"{total_items_discount}",
			"<div v-html='accept_button'></div>",
			"<div v-html='reject_button'></div>",

		);
		$template = str_replace($search, $replace, $template) ;

		return $template;
	}

	/**
	* Get an array of all the taxes defined in the system
	* @return array An array of objects, each containing the tax element from the DB
	*/
	public static function getAllTaxes(){

		$db = JFactory::getDBO();
		$query = 	' SELECT * FROM #__invoices_taxes ORDER BY ordering, name ';
		$db->setQuery( $query );
		$alltaxes = $db->loadObjectList();

		return $alltaxes;

	}

	public static function getTemplatesData(){

		$db = JFactory::getDBO();
		$query = ' SELECT * FROM #__invoices_templates '.
				 			' ORDER BY name ';
		$db->setQuery( $query );
		$templates_data = $db->loadObjectList();

		return $templates_data;

	}

	/**
	* Get an array of the taxes that are set to be displayed as columns
	* @return array An array of objects, each containing the tax element from the DB
	*/
	public static function getTaxes(){

		$db = JFactory::getDBO();
		$query = 	' SELECT * FROM #__invoices_taxes WHERE show_column = 1 ORDER BY ordering, name ';
		$db->setQuery( $query );
		$taxes = $db->loadObjectList();

		return $taxes;

	}

	public static function loadStatusLanguageStrings()
	{
		JText::script('PAID');
		JText::script('ACCEPTED');
		JText::script('ACCEPTED_CLIENT');
		JText::script('PENDING');
		JText::script('PARTIAL_PAID');
		JText::script('PASTDUE');
		JText::script('REJECTED');
		JText::script('REJECTED_CLIENT');
		JText::script('REFUNDED');
		JText::script('PARTIAL_REFUNDED');
		JText::script('CANCELLED');
		JText::script('EXPIRED');
		JText::script('CORRECTED');
		JText::script('UNPAID_ONTIME');
		JText::script('PAID_LATE');
	}

	public static function sendJSONResponse($object, $status = 200){

		$app = JFactory::getApplication();

		switch($status){
			case 403:
			header('HTTP/1.0 403 Forbidden');
			break;
			default:
			break;
		}

		header('Content-Type: application/json');

		echo json_encode($object);

		$app->close();

	}

	public static function storepdf($location, $view)
	{
		jimport( 'joomla.html.html');

		require_once(JPATH_SITE.DS.'components'.DS.'com_invoices'.DS.'helpers'.DS.'dompdf'.DS.'autoload.inc.php');

		if(file_exists(JPATH_SITE.DS.'libraries'.DS.'joomla'.DS.'html'.DS.'html.php')) require_once(JPATH_SITE.DS.'libraries'.DS.'joomla'.DS.'html'.DS.'html.php');
		elseif(file_exists(JPATH_SITE.DS.'libraries'.DS.'cms'.DS.'html'.DS.'html.php')) require_once(JPATH_SITE.DS.'libraries'.DS.'cms'.DS.'html'.DS.'html.php');

		if(file_exists(JPATH_SITE.DS.'libraries'.DS.'joomla'.DS.'date'.DS.'date.php')) require_once(JPATH_SITE.DS.'libraries'.DS.'joomla'.DS.'date'.DS.'date.php');
		elseif(file_exists(JPATH_SITE.DS.'libraries'.DS.'cms'.DS.'html'.DS.'date.php')) require_once(JPATH_SITE.DS.'libraries'.DS.'cms'.DS.'html'.DS.'date.php');

		$mainframe = JFactory::getApplication();

		$plantilla = 'email' ;

		$html = $view->loadTemplate($plantilla);

		$search = array("€", "¢", "£", "¤", "¥");
		$replace = array("&euro;", "&cent;", "&pound;", "&curren;", "&yen;");

		$html = str_replace($search, $replace, $html);
		$html = mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8');
		$html = utf8_decode($html);

		$html = '<!DOCTYPE HTML>
				<html>
				<body>
				<style>
				'.$view->template->styles.'
				</style>'
				. $html .
				'</body></html>';

		$options = new Dompdf\Options();
		$options->set( 'isRemoteEnabled', TRUE );

		$dompdf = new Dompdf\Dompdf($options);
		$dompdf->set_paper('a4');
		$dompdf->load_html($html);
		$dompdf->render();

		$pdf = $dompdf->output();

		return file_put_contents($location, $pdf);
	}

}
