<?php // no direct access

/*------------------------------------------------------------------------
# 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.');

$user = JFactory::getUser();

$items = "";
$taxes = "";
$payments = "";
$payments2 = "";
$subtotal = 0 ;
$subtotal_items = 0 ;
$items_tax = 0 ;
$subtotal_items_no_discount = 0;
$outstanding_payments = 0;
$total_items_discount = 0;

if(!$this->invoice->currency_id) $this->invoice->currency_id = $this->params->get('currency_id', 1);

$db = JFactory::getDBO();
$query = "SELECT * FROM #__invoices_currencies WHERE id = ".$this->invoice->currency_id;
$db->setQuery($query);
$currency = $db->loadObject();

// MULTI LANGUAGE
if($this->invoice->language){
	$lang = JFactory::getLanguage();
	$lang->load('joomla', JPATH_SITE, $this->invoice->language, true);
	$lang->load('com_invoices', JPATH_SITE, $this->invoice->language, true);
}

$pattern = '/\[\[(.*?)\]\]/' ;

$matches = array();
preg_match_all($pattern, $this->template->content, $matches);

foreach($matches[1] as $value){
    $this->template->content = str_replace("[[".$value."]]", JText::_($value), $this->template->content);
}

if(empty($this->template->company_logo)) {
	$this->template->company_logo = 'logo_default.png';
}

//prepare the template iterating parts
if(str_replace(array(" ","\n", "\r"), "", InvoicesHelper::get_string_between($this->template->content, "<!--ITEMS-->", "<!--/ITEMS-->")) != ""){

	$this->template->items = InvoicesHelper::get_string_between($this->template->content, "<!--ITEMS-->", "<!--/ITEMS-->");
	$this->template->taxes = InvoicesHelper::get_string_between($this->template->content, "<!--TAXES-->", "<!--/TAXES-->");
	$this->template->payments = InvoicesHelper::get_string_between($this->template->content, "<!--PAYMENTS-->", "<!--/PAYMENTS-->");
	$this->template->payments2 = InvoicesHelper::get_string_between($this->template->content, "<!--PAYMENTS2-->", "<!--/PAYMENTS2-->");
	$this->template->grouped_taxes = InvoicesHelper::get_string_between($this->template->content, "<!--GROUPED_TAXES-->", "<!--/GROUPED_TAXES-->");
	$this->template->grouped_taxes_total = InvoicesHelper::get_string_between($this->template->content, "<!--GROUPED_TAXES_TOTAL-->", "<!--/GROUPED_TAXES_TOTAL-->");

	$this->template->content = InvoicesHelper::replace_string_between($this->template->content, "<!--ITEMS-->", "<!--/ITEMS-->", "{items}");
	$this->template->content = InvoicesHelper::replace_string_between($this->template->content, "<!--TAXES-->", "<!--/TAXES-->", "{taxes}");
	$this->template->content = InvoicesHelper::replace_string_between($this->template->content, "<!--PAYMENTS-->", "<!--/PAYMENTS-->", "{payments}");
	$this->template->content = InvoicesHelper::replace_string_between($this->template->content, "<!--PAYMENTS2-->", "<!--/PAYMENTS2-->", "{payments2}");
	$this->template->content = InvoicesHelper::replace_string_between($this->template->content, "<!--GROUPED_TAXES-->", "<!--/GROUPED_TAXES-->", "{grouped_taxes}");
	$this->template->content = InvoicesHelper::replace_string_between($this->template->content, "<!--GROUPED_TAXES_TOTAL-->", "<!--/GROUPED_TAXES_TOTAL-->", "{grouped_taxes_total}");

}

$this->individual_taxes = array();

if(!empty($this->items)){
	foreach($this->items as $item){

		$item_subtotal_no_discount = ($item->value * $item->amount);
		$item_subtotal = $item_subtotal_no_discount - $item->discount;
		$item_tax = $item_subtotal * ($item->tax/100);
		$item_total = $item_subtotal + $item_tax;

		$subtotal_items += $item_subtotal ;
		$subtotal_items_no_discount += $item_subtotal_no_discount ;
		$total_items_discount += $item->discount ;
		$items_tax += $item_tax ;
		$subtotal += $item_total ;

		$item_with_tax = $item->value * (1+($item->tax/100));

        //Individual tax items
        $individual_tax_amount = $item_tax;
        $individual_tax_percent = $item->tax;

        if ($individual_tax_amount != 0 || $item->tax_id)
        {
        	if (!isset($this->individual_taxes[$item->tax_id])) $this->individual_taxes[$item->tax_id] = array();

            if (array_key_exists($individual_tax_percent, $this->individual_taxes[$item->tax_id])){
                $this->individual_taxes[$item->tax_id][$individual_tax_percent]->value += $individual_tax_amount;
                $this->individual_taxes[$item->tax_id][$individual_tax_percent]->calculated_on_amount += $item_subtotal;
            } else {
                $this->individual_taxes[$item->tax_id][$individual_tax_percent] = new stdClass();

                if($item->tax_id) $this->individual_taxes[$item->tax_id][$individual_tax_percent]->name = $item->tax_name;
                else $this->individual_taxes[$item->tax_id][$individual_tax_percent]->name = JText::sprintf("GROUPED_TAX", $individual_tax_percent);

                $this->individual_taxes[$item->tax_id][$individual_tax_percent]->value = $individual_tax_amount;
                $this->individual_taxes[$item->tax_id][$individual_tax_percent]->percent_value = $individual_tax_percent;
                $this->individual_taxes[$item->tax_id][$individual_tax_percent]->calculated_on_amount = $item_subtotal;
                $this->individual_taxes[$item->tax_id][$individual_tax_percent]->tax_id = $item->tax_id;
            }
        }

		$search = array(
						"{name}",
						"{desc}",
						"{value}",
						"{amount}",
						"{discount}",
						"{sku}",
						"{tax}",
						"{item_total}",
						//new fields version 1.4
						"{item_subtotal_no_discount}",
						"{item_subtotal}",
						"{item_tax_value}",
						//v 2.1
						"{tax_name}",
						"{item_with_tax}"
					);
		$replace = array(
						$item->name,
						$item->desc,
						InvoicesHelper::format($item->value, $currency),
						$item->amount,
						InvoicesHelper::format($item->discount, $currency),
						$item->sku,
						InvoicesHelper::format($item->tax, InvoicesHelper::percentCurrency($currency)),
						InvoicesHelper::format($item_total, $currency),
						//new fields version 1.4
						InvoicesHelper::format($item_subtotal_no_discount, $currency),
						InvoicesHelper::format($item_subtotal, $currency),
						InvoicesHelper::format($item_tax, $currency),
						//v 2.1
						$item->tax_name,
						InvoicesHelper::format($item_with_tax, $currency)
						);
		$items .= str_replace($search, $replace, $this->template->items) ;

	}
}

$subtotal -= $this->invoice->discount ;

$subtotal_items_less_discount = $subtotal_items - $this->invoice->discount ;

$taxes_value = 0;

$subtotal1 = $subtotal ;
$subtotal1_items = $subtotal_items_less_discount ;

if(!empty($this->taxes)){
	foreach($this->taxes as $tax){

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

				if($tax->ordering == 1){ //first group of taxes
					if($tax->calculate_on == 1) $tax_value = ( $tax->value / 100 ) * $subtotal_items_less_discount ;
					else $tax_value = ( $tax->value / 100 ) * $subtotal ;
				}
				else if($tax->ordering == 2){ //second group of taxes
					if($tax->calculate_on == 1) $tax_value = ( $tax->value / 100 ) * $subtotal1_items ;
					else $tax_value = ( $tax->value / 100 ) * $subtotal1 ;
				}
				$print_tax_value = InvoicesHelper::format($tax->value, InvoicesHelper::percentCurrency($currency));
			break;
			case "static":
				$tax_value = $tax->value ;
				$print_tax_value = InvoicesHelper::format($tax->value, $currency);
			break;
		}

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

		$taxes_value += $tax_value ;

		$search = array(
						"{name}",
						"{value}",
						"{tax_value}"
					);
		$replace = array(
						$tax->name,
						InvoicesHelper::format($tax_value, $currency),
						$print_tax_value
						);
		$taxes .= str_replace($search, $replace, $this->template->taxes) ;

	}

}

$total = $subtotal + $taxes_value ;

//INDIVIDUAL TAX ITERATION
$grouped_taxes = "";
$individual_tax_totals = array();

if(!empty($this->individual_taxes)){
    foreach($this->individual_taxes as $taxid => $tax_array){
    	if(!empty($tax_array)){

    		if(!isset($individual_tax_totals[$taxid])){
            	$individual_tax_totals[$taxid] = new stdClass();
            	$individual_tax_totals[$taxid]->name = "";
            }

    		$individual_tax_total = 0;
    		$individual_tax_calculated_on_amount = 0;

	    	foreach($tax_array as $tax){

		        if (isset($tax->name)){
		            $tax_value = $tax->value ;

		            $individual_tax_total += $tax_value ;
		            $individual_tax_calculated_on_amount += $tax->calculated_on_amount ;
		            $individual_tax_totals[$taxid]->name = $tax->name;

		            $search = array(
		                "{name}",
		                "{value}",
		                "{tax_value}",
		                "{calculated_on_amount}"
		            );
		            $replace = array(
		                $tax->name,
		                InvoicesHelper::format($tax_value, $currency),
		                InvoicesHelper::format($tax->percent_value, InvoicesHelper::percentCurrency($currency)),
		                InvoicesHelper::format($tax->calculated_on_amount, $currency),
		            );
		            $grouped_taxes .= str_replace($search, $replace, $this->template->grouped_taxes) ;
		        }
		    }

		    //the totals on each tax added from individual items. whoaa!! heavy stuff.
		    $individual_tax_totals[$taxid]->value = $individual_tax_total;
		    $individual_tax_totals[$taxid]->calculated_on_amount = $individual_tax_calculated_on_amount;
		}
    }
}

//INDIVIDUAL TAX ITERATION TOTALS
$grouped_taxes_total = "";

if(!empty($individual_tax_totals)){

	foreach($individual_tax_totals as $tax){

        if (isset($tax->name)){
            $tax_value = $tax->value ;

            $search = array(
                "{name}",
                "{value}",
                "{calculated_on_amount}"
            );
            $replace = array(
                $tax->name,
                InvoicesHelper::format($tax_value, $currency),
                InvoicesHelper::format($tax->calculated_on_amount, $currency),
            );
            $grouped_taxes_total .= str_replace($search, $replace, $this->template->grouped_taxes_total) ;
        }
    }
}

//PAYMENTS
$subtotal_payments = 0;

if(!empty($this->payments)){
	foreach($this->payments as $payment){

		$subtotal_payments += $payment->payment_amount ;

		if($payment->payment_duedate == "0000-00-00 00:00:00") $payment_duedate = JText::_('NOT_SPECIFIED');
		else $payment_duedate = JHTML::_('date', strtotime($payment->payment_duedate), JText::_($this->params->get('invoice_date_format', 'DATE_FORMAT_LC3')), false) ;

		if($payment->payment_datetime == "0000-00-00 00:00:00") $payment_datetime = JText::_('NOT_SPECIFIED');
		else $payment_datetime = JHTML::_('date', strtotime($payment->payment_datetime), JText::_($this->params->get('invoice_date_format', 'DATE_FORMAT_LC3')), false) ;

		$thestatus = InvoicesHelper::getThePaymentStatus($payment) ;
		$statuslabel = InvoicesHelper::render_status_payment($thestatus) ;

		$search = array(
						"{description}",
						"{duedate}",
						"{payment_datetime}",
						"{amount}",
						"{payment_link}",
						"{payment_status}"

					);
		$replace = array(
						$payment->payment_description,
						$payment_duedate,
						$payment_datetime,
						InvoicesHelper::format($payment->payment_amount, $currency),
						InvoicesHelper::getPaymentLink($payment->id),
						$statuslabel
						);
		$payments .= str_replace($search, $replace, $this->template->payments) ;

	}
}

$amount_outstanding = $total - $subtotal_payments;

//PAYMENTS 2
if(!empty($this->payments2)){
	foreach($this->payments2 as $payment){

		$outstanding_payments += $payment->payment_amount ;

		if($payment->payment_duedate == "0000-00-00 00:00:00") $payment_duedate = JText::_('NOT_SPECIFIED');
		else $payment_duedate = JHTML::_('date', strtotime($payment->payment_duedate), JText::_($this->params->get('invoice_date_format', 'DATE_FORMAT_LC3')), false) ;

		if($payment->payment_datetime == "0000-00-00 00:00:00") $payment_datetime = JText::_('NOT_SPECIFIED');
		else $payment_datetime = JHTML::_('date', strtotime($payment->payment_datetime), JText::_($this->params->get('invoice_date_format', 'DATE_FORMAT_LC3')), false) ;


		$thestatus = InvoicesHelper::getThePaymentStatus($payment) ;
		$statuslabel = InvoicesHelper::render_status_payment($thestatus) ;

		$search = array(
						"{description}",
						"{duedate}",
						"{payment_datetime}",
						"{amount}",
						"{payment_link}",
						"{payment_status}"
					);
		$replace = array(
						$payment->payment_description,
						$payment_duedate,
						$payment_datetime,
						InvoicesHelper::format($payment->payment_amount, $currency),
						InvoicesHelper::getPaymentLink($payment->id),
						$statuslabel
						);
		$payments2 .= str_replace($search, $replace, $this->template->payments2) ;

	}
}

$amount_outstanding = $outstanding_payments ;

$status = InvoicesHelper::getInvoiceStatus($this->invoice, $total, $subtotal_payments, $amount_outstanding);

$status = InvoicesHelper::render_status($status) ;

if(!$this->invoice->invoice_duedate || $this->invoice->invoice_duedate == "0000-00-00" || $this->invoice->invoice_duedate == "0000-00-00 00:00:00") $duedate = "<span class='muted'>".JText::_('NOT_SETTED')."</span>";
else $duedate = JHTML::_('date', strtotime($this->invoice->invoice_duedate), JText::_($this->params->get('invoice_date_format', 'DATE_FORMAT_LC3')), false) ;

$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}",
				"{total}",
				"{payments}",
				"{total_payments}",
				"{amount_outstanding}",
				//new fields version 1.2
				"{to_zipcode}",
				"{to_city}",
				"{to_state}",
				"{to_country}",
				"{to_vatid}",
				"{discount}",
				"{invoice_duedate}",
				"{payments2}",
				"{status}",
				"{num_payments_received}",
				"{num_pending_payments}",
				//new fields version 1.3
				"{to_phone}",
				"{invoice_link}",
				"{invoice_unlogged_link}",
				//new fields version 1.4
				"{subtotal_items}",
				"{total_items_tax}",
				"{subtotal_items_no_discount}",
				"{total_items_discount}",
				"{accept_button}",
				"{reject_button}",
        "{grouped_taxes}",
				"{company_logo}",
				//new fields version 2.0
				"{external_ref}",
				//v 2.1
				"{grouped_taxes_total}",
				"{subtotal_items_less_total_discount}",
				"{paynow_button}"
				);

if(!$this->invoice->to_vatid) $this->invoice->to_vatid = "&nbsp;" ;
if(!$this->invoice->to_phone) $this->invoice->to_phone = "&nbsp;" ;
if(!$this->invoice->from_num) $this->invoice->from_num = "&nbsp;" ;
if(!$this->invoice->from_phone) $this->invoice->from_phone = "&nbsp;" ;

if($this->invoice->status == "pending" || $this->invoice->status == ""){
	$accept_button = "<a href='".InvoicesHelper::getQuoteAcceptLink($this->invoice->id)."' class='btn btn-large btn-success '>".JText::_('ACCEPT_QUOTE')."</a>";
}
else $accept_button = "" ;

if($this->invoice->status == "pending" || $this->invoice->status == ""){
	$reject_button = "<a href='".InvoicesHelper::getQuoteRejectLink($this->invoice->id)."' class='btn btn-large btn-danger '>".JText::_('REJECT_QUOTE')."</a>";
}
else $reject_button = "" ;

if(!empty($this->payments2)){
	$paynow_button = "<a href='".InvoicesHelper::getPaymentLink($this->payments2[0]->id)."' class='btn btn-large btn-lg btn-block btn-success '>".JText::sprintf('PAY_NOW_AMOUNT', InvoicesHelper::format($this->payments2[0]->payment_amount, $currency))."</a>";
}
else $paynow_button = "" ;

$replace = array(
				$this->invoice->to_name,
				$this->invoice->to_company,
				$this->invoice->to_email,
				str_replace("\n", "<br />",$this->invoice->to_address ),
				$this->invoice->from_name,
				str_replace("\n", "<br />", $this->invoice->from_address),
				$this->invoice->from_num,
				$this->invoice->from_url,
				$this->invoice->from_email,
				$this->invoice->from_phone,
				JHTML::_('date', strtotime($this->invoice->invoice_date), JText::_($this->params->get('invoice_date_format', 'DATE_FORMAT_LC3')), false),
				$this->invoice->notes,
				$this->invoice->invoice_num,
				$items,
				InvoicesHelper::format($subtotal, $currency),
				$taxes,
				InvoicesHelper::format($total, $currency),
				$payments,
				InvoicesHelper::format($subtotal_payments, $currency),
				InvoicesHelper::format($amount_outstanding, $currency),
				//new fields version 1.2
				$this->invoice->to_zipcode,
				$this->invoice->to_city,
				$this->invoice->to_state,
				$this->invoice->to_country,
				$this->invoice->to_vatid,
				InvoicesHelper::format($this->invoice->discount, $currency),
				$duedate,
				$payments2,
				$status,
				InvoicesHelper::render_num_payments_received(count($this->payments)),
				InvoicesHelper::render_num_pending_payments(count($this->payments2)),
				//new fields version 1.3
				$this->invoice->to_phone,
				InvoicesHelper::getInvoiceLink($this->invoice->id),
				InvoicesHelper::getInvoicePublicLink($this->invoice->id),
				//new fields version 1.4
				InvoicesHelper::format($subtotal_items, $currency),
				InvoicesHelper::format($items_tax, $currency),
				InvoicesHelper::format($subtotal_items_no_discount, $currency),
				InvoicesHelper::format($total_items_discount, $currency),
				$accept_button,
				$reject_button,
        $grouped_taxes,
				JURI::root().'media'.DS.'com_invoices'.DS.$this->template->company_logo,
				//new fields version 2.0
				$this->invoice->external_ref,
				//v 2.1
				$grouped_taxes_total,
				InvoicesHelper::format($subtotal_items_less_discount, $currency),
				$paynow_button
				);

echo str_replace($search, $replace, $this->template->content) ;

echo '<div align="center">'. InvoicesHelper::showInvoicesFooter() .'</div>' ;

?>
