<?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 PaymentsModelPayment extends JModelLegacy
{

	var $input;

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

		$mainframe = JFactory::getApplication();
		$this->input = $mainframe->input;

		$array = $this->input->get('cid',  0, '', 'array');
		$this->setId((int)$array[0]);

		$this->params = JComponentHelper::getParams( 'com_invoices' );

	}

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

	}

	function &getData()
	{
		// Load the data
		if (empty( $this->_data )) {
			$query = ' SELECT pa.*, i.*, pa.id AS id, co.name, u.username  FROM #__invoices_payments as pa '.
					' LEFT JOIN #__invoices_invoices as i ON i.id = pa.invoice_id ' .
					' LEFT JOIN #__invoices_contacts as co ON i.user_id = co.id ' .
					' LEFT JOIN #__users as u ON co.user_id = u.id ' .
					' WHERE pa.id = '.$this->_id;
			$this->_db->setQuery( $query );
			$this->_data = $this->_db->loadObject();

		}

		if (!$this->_data) {
			$this->_data = new stdClass();

			$this->_data->payment_amount = 0;

			$this->_data->invoice_id = 0;

			$invoice_id = $this->input->getInt('invoice_id');
			if($invoice_id){
				$query = ' SELECT  i.*, i.id AS invoice_id, co.name, u.username  FROM #__invoices_invoices as i '.
						' LEFT JOIN #__invoices_contacts as co ON i.user_id = co.id ' .
						' LEFT JOIN #__users as u ON co.user_id = u.id ' .
						'  WHERE i.id = '.$invoice_id;
				$this->_db->setQuery( $query );
				$this->_data = $this->_db->loadObject();

				//automatically set for the rest of the amount
				$total = InvoicesHelper::get_total_from_id($invoice_id); // the total of the invoice

				$query = " SELECT SUM(payment_amount) FROM #__invoices_payments WHERE invoice_id = " . $invoice_id;
				$this->_db->setQuery($query);
				$already_created = $this->_db->loadResult();

				$therest = $total - $already_created ;
				if($therest < 0) $therest = 0 ;

				$this->_data->payment_amount = $therest ;
			}

			$this->_data->created_datetime = "";
			$this->_data->payment_duedate = "";
			$this->_data->payment_datetime = "";
			$this->_data->payment_id = "";
			$this->_data->payment_type = "";
			$this->_data->payment_details = "";
			$this->_data->payment_description = "";

			$this->_data->currency_before = $this->params->get('currency_before');
			$this->_data->currency_after = $this->params->get('currency_after');
			$this->_data->payment_status = 0;

			$this->_data->id = 0;
		}

		$this->_data->created_datetime = str_replace(" 00:00:00", "", $this->_data->created_datetime);
		$this->_data->payment_duedate = str_replace(" 00:00:00", "", $this->_data->payment_duedate);
		$this->_data->payment_datetime = str_replace(" 00:00:00", "", $this->_data->payment_datetime);

		if($this->_data->created_datetime == "0000-00-00") $this->_data->created_datetime = "";
		if($this->_data->payment_duedate == "0000-00-00") $this->_data->payment_duedate = "";
		if($this->_data->payment_datetime == "0000-00-00") $this->_data->payment_datetime = "";

		return $this->_data;
	}

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

		if (!$payment) {
			$data = $this->input->post->getArray();
		} else {
			$data = $payment;
		}

		// 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;
		}

		InvoicesHelper::updateComputedStatus($data['invoice_id']);

		$import = JPluginHelper::importPlugin( strtolower( 'Invoices' ) );
		$dispatcher = JDispatcher::getInstance();
		$dispatcher->trigger( 'onAfterSavePayment', array( $row ) );

		return $row->id;
	}

	function delete()
	{
		$cids = $this->input->get( 'pid', array(0), 'default', 'array' );

		$row = $this->getTable();

		$import = JPluginHelper::importPlugin( 'invoices' );
		$dispatcher = JDispatcher::getInstance();

		if (count( $cids )) {
			foreach($cids as $cid) {

				$query = " SELECT invoice_id FROM #__invoices_payments WHERE id = ".$cid ;
				$this->_db->setQuery($query);
				$invoice_id = $this->_db->loadResult();

				$dispatcher->trigger( 'onBeforeDeletePayment', array( $row ) );

				if (!$row->delete( $cid )) {
					$this->setError( $row->getErrorMsg() );
					return false;
				}
				else{
					InvoicesHelper::updateComputedStatus($invoice_id);
				}
			}
		}
		return true;
	}

	function publish()
	{
		$cids = $this->input->get( 'cid', array(0), 'default', 'array' );

		if (count( $cids )) {
			foreach($cids as $cid) {
				$query = ' UPDATE #__invoices_payments SET payment_status = 1 WHERE id = '. $cid . ' LIMIT 1 ';
				$this->_db->setQuery($query);
				$this->_db->query();

				$query = " SELECT invoice_id FROM #__invoices_payments WHERE id = ".$cid ;
				$this->_db->setQuery($query);
				$invoice_id = $this->_db->loadResult();

				InvoicesHelper::updateComputedStatus($invoice_id);
			}
		}
		return true;
	}

	function unpublish()
	{
		$cids = $this->input->get( 'cid', array(0), 'default', 'array' );

		if (count( $cids )) {
			foreach($cids as $cid) {
				$query = ' UPDATE #__invoices_payments SET payment_status = 0 WHERE id = '. $cid . ' LIMIT 1 ';
				$this->_db->setQuery($query);
				$this->_db->query();

				$query = " SELECT invoice_id FROM #__invoices_payments WHERE id = ".$cid ;
				$this->_db->setQuery($query);
				$invoice_id = $this->_db->loadResult();

				InvoicesHelper::updateComputedStatus($invoice_id);
			}
		}
		return true;
	}

	function getDataDisplay($id = false)
	{
		if($id) $this->setId($id);

		$query = ' SELECT pa.*, i.*, pa.id AS id, u.name as username, co.name as contact_name, co.user_id as joomla_user_id '.
					' FROM #__invoices_payments as pa '.
					' LEFT JOIN #__invoices_invoices as i ON i.id = pa.invoice_id ' .
					' LEFT JOIN #__invoices_contacts as co ON i.user_id = co.id ' .
					' LEFT JOIN #__users as u ON co.user_id = u.id ' .
					' WHERE pa.id = '.$this->_id;
		$this->_db->setQuery( $query );
		$row = $this->_db->loadObject();

		//AMOUNT
		$row->invoice_total = InvoicesHelper::get_total_from_id($row->invoice_id);

		return $row;
	}

}
