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

class InvoicesModelInvoice extends JModelLegacy
{

	function __construct()
	{
		parent::__construct();

		$id = JRequest::getInt('id');
		$this->setId((int)$id);

	}

	function setId($id)
	{
		// Set id and wipe data
		$this->_id		= $id;
		$this->_data	= null;

	}

	function &getData()
	{

		// Load the data
		$query = 	' SELECT i.* '.
					' FROM #__invoices_invoices as i '.
					' WHERE i.id = ' . $this->_id
					;
		$this->_db->setQuery( $query );
		$this->_data = $this->_db->loadObject();

		return $this->_data;
	}

	function &getTemplate()
	{

		$query = 	' SELECT te.* '.
					' FROM #__invoices_templates as te '.
					' WHERE te.id = ' . $this->_data->template_id
					;
		$this->_db->setQuery( $query );
		$this->template = $this->_db->loadObject();

		return $this->template;
	}

	function &getItems()
	{

		$query = 	' SELECT it.*, tax.name AS tax_name FROM #__invoices_items AS it '.
					' LEFT JOIN #__invoices_taxes AS tax ON tax.id = it.tax_id '.
					' WHERE it.invoice_id = ' . $this->_data->id .
					' ORDER BY it.ordering ';
		$this->_db->setQuery( $query );
		$this->items = $this->_db->loadObjectList();

		return $this->items;
	}

	function &getPayments()
	{

		$query = 	' SELECT pa.* '.
					' FROM #__invoices_payments as pa '.
					' WHERE pa.invoice_id = ' . $this->_data->id .
					' AND pa.payment_status = 1 '.
					' ORDER BY ordering '
					;
		$this->_db->setQuery( $query );
		$this->payments = $this->_db->loadObjectList();

		return $this->payments;
	}

	function &getPayments2()
	{

		$query = 	' SELECT pa.* '.
					' FROM #__invoices_payments as pa '.
					' WHERE pa.invoice_id = ' . $this->_data->id .
					' AND pa.payment_status = 0 '.
					' ORDER BY ordering '
					;
		$this->_db->setQuery( $query );
		$this->payments2 = $this->_db->loadObjectList();

		return $this->payments2;
	}

	function &getTaxes()
	{
		if($this->_data->taxes){
			$query = ' SELECT tax.*, tai.value AS value '
					.' FROM #__invoices_taxes AS tax '
					.' LEFT JOIN #__invoices_tax_invoice AS tai ON (tai.tax_id = tax.id AND tai.reference_id = ' . $this->_data->id . ' AND tai.type = 1) '
					.' WHERE tai.active = 1 '
					.' ORDER BY ordering, name ' ;
			$this->_db->setQuery( $query );
			$this->taxes = $this->_db->loadObjectList();
		}
		return $this->taxes;
	}

	function store()
	{
		$row = $this->getTable();

		$data = JRequest::get( 'post' );

		// Bind the form fields to the album table
		if (!$row->bind($data)) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		if (!$row->check()) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		if (!$row->store()) {

			$this->setError( $this->_db->getErrorMsg() );
			return false;
		}

		return $row->id;
	}

	function delete()
	{
		$id = JRequest::getInt( 'id' );

		$row = $this->getTable();

		if ( $id ) {

			if (!$row->delete( $id )) {
				$this->setError( $this->_db->getErrorMsg() );
				return false;
			}

		}

		return true;
	}

	function sendMail(){
		$data = $this->getData();

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

		$from = $params->get('email_email') ;
		$from_name = $params->get('email_name') ;
		$subject = $params->get('email_subject') ;

		if($data->type == 2){//quote
			$subject = $params->get('email_subject_quote') ;
		}

		$subject = str_replace("{invoice_num}", $data->invoice_num, $subject) ;

		$view		= $this->getInvoiceView();

		$view->invoice		= $data;
		$view->template		= $this->getTemplate();
		$view->items		= $this->getItems();
		$view->taxes		= $this->getTaxes();
		$view->payments		= $this->getPayments();
		$view->payments2		= $this->getPayments2();
		$view->params		= $params;

		if($view->template->content_email) $view->template->content = $view->template->content_email ;

		$view->_path['template'][1] = JPATH_SITE.DS.'components'.DS.'com_invoices'.DS.'views'.DS.'invoice'.DS.'tmpl' ;

		$plantilla = 'email' ;

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

		$styles = "<style>".$view->template->styles."</style>" ;
		$message = $styles . $message ;

		$to = $data->to_email;

		$toBlock = str_replace(" ", "", $to); //Delete spaces between emails
		$toMails = explode(",", $toBlock);

		$mail = JFactory::getMailer();
		$mail->addRecipient($toMails);
		$mail->setsender(array($from, $from_name));
		$mail->setSubject($subject);
		$mail->setbody($message);
		$mail->isHTML(true);

		if($params->get('pdfemail') && InvoicesHelper::PDFavailable()){
			//create PDF
			$viewpdf		= $this->getInvoiceView('dompdf');

			$viewpdf->invoice		= $view->invoice	;
			$viewpdf->template		= $this->getTemplate();
			$viewpdf->items			= $view->items	;
			$viewpdf->taxes			= $view->taxes	;
			$viewpdf->payments		= $view->payments;
			$viewpdf->payments2		= $view->payments2;
			$viewpdf->params		= $params;

			if($viewpdf->template->content_pdf) $viewpdf->template->content = $viewpdf->template->content_pdf ;

			$viewpdf->_path['template'][1] = JPATH_SITE.DS.'components'.DS.'com_invoices'.DS.'views'.DS.'invoice'.DS.'tmpl' ;

			if($viewpdf->invoice->invoice_num) $pdfname = $viewpdf->invoice->invoice_num;
			else $pdfname = rand();

			$location = JPATH_SITE.DS.$params->get('pdffolder','pdfinvoices').DS.$pdfname . ".pdf" ;

			$pdf = InvoicesHelper::storepdf($location, $viewpdf);

			if($pdf) $mail->addAttachment($location, $viewpdf->invoice->invoice_num . ".pdf") ;

		}

		$sent = $mail->Send();
		if($sent && $to){
			InvoicesHelper::updateSentDate($data->id);

			//trigger event
			$import = JPluginHelper::importPlugin( 'invoices' );
			$dispatcher = JDispatcher::getInstance();
			$dispatcher->trigger( 'onAfterSendInvoice', array( $data ) );
		}
		return $sent ;

	}

	function getInvoiceView($type = "html")
	{
		if (!class_exists( 'InvoicesViewInvoice' ))
		{
			// Build the path to the model based upon a supplied base path
			$path = JPATH_SITE.DS.'components'.DS.'com_invoices'.DS.'views'.DS.'invoice'.DS.'view.'.$type.'.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( 'InvoicesViewInvoice' )) {
					JError::raiseWarning( 0, 'View class InvoicesViewInvoice not found in file.' );
					return $false;
				}
			} else {
				JError::raiseWarning( 0, 'View InvoicesViewInvoice not supported. File not found.' );
				return $false;
			}
		}

		$view = new InvoicesViewInvoice();
		return $view;
	}

	function accept_quote(){
		$query = ' UPDATE #__invoices_invoices SET status = "accepted_client" WHERE id = '. $this->_id ;
		$this->_db->setQuery($query);
		$this->_db->query();

		$import = JPluginHelper::importPlugin( 'invoices' );
		$dispatcher = JDispatcher::getInstance();
		$dispatcher->trigger( 'onAcceptQuote', array( $this->_id ) );

		return true;
	}

	function reject_quote(){
		$query = ' UPDATE #__invoices_invoices SET status = "rejected_client" WHERE id = '. $this->_id ;
		$this->_db->setQuery($query);
		$this->_db->query();

		$import = JPluginHelper::importPlugin( 'invoices' );
		$dispatcher = JDispatcher::getInstance();
		$dispatcher->trigger( 'onRejectQuote', array( $this->_id ) );

		return true;
	}

}
