<?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.');

jimport('joomla.application.component.controller');

class InvoicesController extends JControllerLegacy
{

	function display( $cachable = false, $urlparams = array())
	{

		$user = JFactory::getUser();
		$db = JFactory::getDBO();
		$id = JRequest::getInt( 'id' ) ;
		$view = JRequest::getVar( 'view' ) ;

		$params = JComponentHelper::getParams( 'com_invoices' );
		$itemid = $params->get('itemid');
		if($itemid != "") $itemid = "&Itemid=" . $itemid;

		switch($view){
			case "invoice":
			$can_view = $this->check_invoice_permission($id);
			$msg = JText::_('NOT_AUTHORIZED_INVOICE');
			$link = JRoute::_('index.php?option=com_invoices&view=invoices' . $itemid);
			break;
			case "payment":
			$query = ' SELECT invoice_id FROM #__invoices_payments WHERE id = ' . $id ;
			$db->setQuery($query);
			$invoice_id = $db->loadResult();
			//$can_view = $this->check_invoice_permission($invoice_id);
			$can_view = true ;
			$msg = JText::_('NOT_AUTHORIZED_PAYMENT');
			$link = JRoute::_('index.php?option=com_invoices&view=invoices' . $itemid);
			if(!$id){
				$msg = "";
				$can_view = false;
			}
			break;
			case "invoices":
			$can_view = true ;
			break;
		}

		if(!$can_view){

			$link = JRoute::_('index.php?option=com_invoices&view=invoices' . $itemid);

			$this->setRedirect($link, $msg);
		}
		else parent::display($cachable,$urlparams);
	}

	function check_invoice_permission($invoice_id, $auth_code = false){

		$db = JFactory::getDBO();
		$user = JFactory::getUser();
		$app = JFactory::getApplication();

		if(!$auth_code) $auth_code = JRequest::getString('auth_code') ;

		if(in_array(3, $user->getAuthorisedViewLevels())){
			return true;
		}

		$now = date('Y-m-d H:i:s') ;

		$query = ' SELECT co.user_id, i.auth_code FROM #__invoices_invoices AS i '
				.' LEFT JOIN #__invoices_contacts AS co ON co.id = i.user_id '
				.' WHERE i.id = ' . $invoice_id
				.' AND ( i.start_publish <= "'. $now .'" OR i.start_publish = "0000-00-00 00:00:00") '
				.' AND ( i.end_publish >= "'. $now .'" OR i.end_publish = "0000-00-00 00:00:00") '
				.' AND i.publish = 1 ' ;
				;

		$db->setQuery($query);
		$invoice = $db->loadObject();
		$invoice_owner = $invoice->user_id;

		$view = JRequest::getCmd('view');

		if($invoice_owner == $user->id && $user->id) return true;
		elseif($auth_code == $invoice->auth_code && $invoice->auth_code != "") return true;
		elseif($auth_code != $invoice->auth_code && $invoice->auth_code != "" && $view != "payment") {
			$app->enqueueMessage(JText::_('INVALID_AUTH_CODE'));
			return false;
		}
		else return false;

	}

	function send()
	{
		$db = JFactory::getDBO();

		$params = JComponentHelper::getParams( 'com_invoices' );
		$id = JRequest::getInt( 'id' ) ;
		$can_view = $this->check_invoice_permission($id);

		if($can_view){
			$model = $this->getModel('invoice');
			$model->setId($id) ;

			if ($model->sendMail()) {
				$msg = JText::sprintf( 'INVOICE_SENT', $model->_data->invoice_num, $model->_data->to_email );
				$saved_ok = true;

			} else {
				$msg = JText::sprintf( 'ERROR_SENDING_INVOICE', $model->_data->invoice_num, $model->_data->to_email );
				$saved_ok = false;
			}
		}
		else{
			$msg = JText::_( 'NOT_ALLOWED_SEND' );
		}

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

		$this->setRedirect($link, $msg);
	}

	function send_email_payment($payment_id = false)
	{
		if(!$payment_id) $payment_id = JRequest::getInt('id');

		$app = JFactory::getApplication();

		$db = JFactory::getDBO();

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

		$query = ' SELECT invoice_id FROM #__invoices_payments WHERE id = ' . $payment_id ;
		$db->setQuery($query);
		$invoice_id = $db->loadResult();
		$can_view = $this->check_invoice_permission($invoice_id);
		$can_view = true ;

		if($can_view){
			$model = $this->getModel('payment');
			$model->setId($payment_id);

			if ($model->sendMail()) {
				//$msg = JText::sprintf( 'PAYMENT_SENT', $model->_data->to_email );
				$saved_ok = true;

			} else {
				//$msg = JText::sprintf( 'ERROR_SENDING_PAYMENT', $model->_data->to_email );
				$saved_ok = false;
			}
		}
		else{
			$msg = JText::_( 'NOT_ALLOWED_SEND_PAYMENT' );
		}

		$app->enqueueMessage($msg);

	}

	function process_payment(){

		$ptype 		= JRequest::getVar( 'ptype' );
		$payment_id = JRequest::getInt( 'item_number' );
		$paction 	= JRequest::getVar( 'paction' );

		$db = JFactory::getDBO();
		$user = JFactory::getUser();

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

		$import = JPluginHelper::importPlugin( strtolower( 'Invoices' ), $ptype );

		$dispatcher = JDispatcher::getInstance();
		$results = $dispatcher->trigger( 'onProcessPayment', array( $payment, $user ) );

		//print_r($results);die;

		$params = JComponentHelper::getParams( 'com_invoices' );
		$itemid = $params->get('itemid');
		if($itemid != "") $itemid = "&Itemid=" . $itemid;

		$link = JRoute::_('index.php?option=com_invoices&view=payment&id=' . $payment_id . $itemid) ;

		switch ($paction) {
			case "display_message":

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

				switch ($payment->payment_status) {
					case 1:
						$text = JText::_('PAYMENT_COMPLETED');
						$type = "Success" ;
					break;
					case 2:
						$text = JText::_('PAYMENT_PENDING_VALIDATION');
						$type = "message" ;
					break;
					case 0:
						$text = JText::_('PAYMENT_NOT_COMPLETED');
						$type = "message" ;
					break;
				}

			  break;
			case "process":

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

				//we send the emails

				switch ($payment->payment_status) {
					case 1:
						$this->send_email_payment($payment_id);
					break;
					case 2:

					break;
					case 0:

					break;
				}

				$link = JRoute::_('index.php?option=com_invoices&task=process_payment&ptype='.$ptype.'&paction=display_message&tmpl=component&item_number=' . $payment_id . $itemid) ;

			  break;
			case "cancel":
				$text = JText::_( 'PAYMENT_PROCESS_CANCELLED' );
				$type = "message" ;
			  break;
			default:
				$text = JText::_( 'INVALID_ACTION' );
				$type = "error" ;
			  break;
		}

		$this->setRedirect($link, $text);

	}

	function accept_quote(){

		$params = JComponentHelper::getParams( 'com_invoices' );
		$itemid = $params->get('itemid');
		if($itemid != "") $itemid = "&Itemid=" . $itemid;

		$id = JRequest::getInt('id');

		$can_view = $this->check_invoice_permission($id);

		$db = JFactory::getDBO();
		$query = "SELECT status FROM #__invoices_invoices WHERE id = ".$id ;
		$db->setQuery($query);
		$status = $db->loadResult();

		if($can_view && ($status == "pending" || $status == "")){
			$model = $this->getModel('invoice');
			$model->setId($id);

			if ($model->accept_quote()) {
				$msg = JText::_( 'QUOTE_ACCEPTED' );
				$saved_ok = true;

			} else {

				$saved_ok = false;
			}
		}
		else{
			$msg = JText::_( 'NOT_ALLOWED_PERFORM_ACTION' );
		}

		$auth_code = JRequest::getString('auth_code');
		if($auth_code) $auth_code = '&auth_code='.$auth_code;
		else $auth_code = "";

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

		$this->setRedirect($link, $msg);

	}

	function reject_quote(){

		$params = JComponentHelper::getParams( 'com_invoices' );
		$itemid = $params->get('itemid');
		if($itemid != "") $itemid = "&Itemid=" . $itemid;

		$id = JRequest::getInt('id');

		$can_view = $this->check_invoice_permission($id);

		$db = JFactory::getDBO();
		$query = "SELECT status FROM #__invoices_invoices WHERE id = ".$id ;
		$db->setQuery($query);
		$status = $db->loadResult();

		if($can_view && ($status == "pending" || $status == "")){
			$model = $this->getModel('invoice');
			$model->setId($id);

			if ($model->reject_quote()) {
				$msg = JText::_( 'QUOTE_REJECTED' );
				$saved_ok = true;

			} else {

				$saved_ok = false;
			}
		}
		else{
			$msg = JText::_( 'NOT_ALLOWED_PERFORM_ACTION' );
		}

		$auth_code = JRequest::getString('auth_code');
		if($auth_code) $auth_code = '&auth_code='.$auth_code;
		else $auth_code = "";

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

		$this->setRedirect($link, $msg);

	}

}
?>
