<?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 ItemsControllerItem extends ItemsController
{

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

		// Register Extra tasks
		$this->registerTask( 'add'  , 	'edit' );
		$this->registerTask( 'apply',	'save' );
	}

	function edit()
	{
		$this->input->set( 'view', 'item' );
		$this->input->set( 'layout', 'form'  );
		$this->input->set('hidemainmenu', 1);

		parent::display();
	}

	function save()
	{
		$model = $this->getModel('item');

		if ($model->store($post)) {
			$msg = JText::_( 'ITEM_SAVED' );
		} else {
			$msg = JText::_( 'ERROR_SAVING_ITEM' );
		}

		$task = $this->input->getCmd( 'task' );
		$id = $this->input->getInt('id');

		switch ($task)
		{
			case 'apply':
				$link = 'index.php?option=com_invoices&controller=item&task=edit&cid[]='. $id ;
				break;

			case 'save':
			default:
				$link = 'index.php?option=com_invoices&controller=items';
				break;
		}


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

	function remove()
	{
		$mainframe = JFactory::getApplication();

		$invoice_id = $this->input->getInt('id');

		$model = $this->getModel('item');

		$tab = $this->input->getCmd( 'tab' );

		if(!$model->delete()) {
			$msg = JText::_( 'ERROR_DELETING_ITEM' );
			$type = "error";
		} else {
			$msg = JText::_( 'ITEMS_DELETED' );
			$type = "message";
		}

		if($this->input->getInt('ajax')) {
			//we fill the notification to return
			$return = new stdClass();
			$return->notifications = array();
			$return->notifications[0] = new stdClass();
			$return->notifications[0]->message = $msg;
			$return->notifications[0]->type = $type;

			//we fill the content to return
			$invoice_model = InvoicesHelper::getInvoiceAdminModel();
			$return->content = $invoice_model->getDataDisplay($invoice_id) ;

			//we return
			echo json_encode($return);

			$mainframe->close();
		}
	}

	function cancel()
	{
		$msg = JText::_( 'OPERATION_CANCELLED' );
		$this->setRedirect( 'index.php?option=com_invoices&controller=items', $msg );
	}
}
