<?php
/**
 * @package BILLETS
 * @link 	http://www.dioscouri.com
 * @license GNU/GPLv2
 */
 
// no direct access
defined('_JEXEC') or die('Restricted access');

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

/**
 * Billets Model
 *
 * @package BILLETS
 */
class BilletsModelTicket extends JModel {
 
	var $_data;
	var $_user;

	/**
	 * constructor
	 * @return array Array of objects containing the data from the database
	 */	
	function __construct() {
		parent::__construct();

		$array = JRequest::getVar('cid',  0, '', 'array');
		$this->setId((int)$array[0]);
	}

	/**
	 * Method to set the identifier
	 *
	 * @access	public
	 * @param	int identifier
	 * @return	void
	 */
	function setId($id) {
		// Set id and wipe data
		$this->_id		= $id;
		$this->_data	= null;
	}
	
	/**
	 * Returns the query
	 * @return string The query to be used to retrieve the rows from the database
	 */
	function _buildQuery() {
		// grab record
		$query = "SELECT r.* FROM #__billets_tickets as r "
		. " WHERE `id` = '".$this->_id."' "
		;
		
		return $query;
	}
	
	/**
	 * Retrieves the data
	 * @return object containing the record/data from the database
	 */
	function getData() {
		global $mainframe;
		// load the data if it doesn't already exist
		if (empty( $this->_data )) {
			$row = new billetsTicket ( $this->_db );
			$row->load( $this->_id );
			$this->_data = $row;
		}
		return $this->_data;
	}

	/**
	 * Retrieves the messages
	 * @return array Array of objects containing the data from the database
	 */
	function getMessages() {
		// grab ticket messages
		$query = " SELECT * FROM #__billets_messages AS msg "
				." WHERE msg.ticketid = '".$this->_id."' "
				." ORDER BY msg.datetime DESC"
				;
		$this->_db->setQuery($query);
		$return = $this->_db->loadObjectList();

		return $return;
	}

	/**
	 * Retrieves the messages
	 * @return array Array of objects containing the data from the database
	 */
	function getUser( ) {
		global $mainframe;

		$id = intval( JArrayHelper::getValue( $_GET, 'userid' ) );
		
		if ($id > 0) {
			// get the user
			$query = "SELECT #__users.* FROM #__users "
			. " WHERE `id` = '".$id."' "
			;
			$this->_db->setQuery( $query );
			$record = $this->_db->loadObject();
			return $record;
		}
		
		return false;
		
	}

	/**
	 * Retrieves the types
	 * @return array Array of objects containing the data from the database
	 */
	function getTypes() {
		if (empty($this->_types)) {
			$database = &JFactory::getDBO();
			// types
			$types = array();
			$allrows = billetsSupportTicketTypeOptions ( );
			$types[] = JHTML::_('select.option', ' ', "- "._BILLETS_SELECTTYPE." -" );
			if ($allrows) { foreach ($allrows as $a) {
				$types[] = JHTML::_('select.option', $a, constant($a) );
			} }	

			$this->_types = JHTML::_('select.genericlist', $types, "type", "size='1' ", "value", "text", $this->_type );
		}

		return $this->_types;
	}
	 
	/**
	 * Method to store a new custom record
	 *
	 * @access	public
	 * @return	boolean	True on success
	 */
	function savenew() {
		global $mainframe;

		$database = &JFactory::getDBO();

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

		$userid 		= intval ( JArrayHelper::getValue( $_POST, "userid" ) );	
		$type 			= strval ( htmlspecialchars ( JArrayHelper::getValue( $_POST, "type" ) ) );
		$subject 		= strval ( htmlspecialchars ( JArrayHelper::getValue( $_POST, "subject" ) ) );
		$description 	= strval ( htmlspecialchars ( JArrayHelper::getValue( $_POST, "description" ) ) );

		$admin =& JFactory::getUser();
		$user =& JFactory::getUser($userid);

		// invalid entries
		if ( !$userid || !$user->id || !$type || !$subject || !$description ) {
        	$this->setError( _BILLETS_INVALIDENTRIES );
        	return false;
		}	
	
		$row = new billetsTicket ( $database );
		
		// init new ticket	
		$row->status					= '0'; 
		$row->type						= $type;
		$row->subject					= $subject;
		$row->description				= $description;
		$row->last_modified_by			= $admin->id;
		$row->last_modified_datetime	= date( "Y-m-d H:i:s" );
		$row->created_datetime			= date( "Y-m-d H:i:s" );
		$row->created_by	 			= $admin->id;
		$row->sender_email 				= $user->email; // varchar(255)
		$row->sender_userid 			= $user->id; // int(11)
		$row->sender_flag_read			= '0'; // int(1)

   		// Store the entry to the database
    	if (!$row->store()) {
        	$this->setError($database->getErrorMsg());
        	return false;
    	}
		
		return $row;
		
	}
	
	/**
	 * Sets followup value
	 * @return boolean yes/no on success/fail
	 */
	function followup() {
		$cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );
		if ($id = intval ( JArrayHelper::getValue( $_POST, "id" ) )) { $cids[0] = $id; }
		
	    // echo $cids[0]; exit();

		// grab info
		$info = new billetsTicket ($this->_db);
		$info->load( (int)$cids[0] );
	
		if (!$info->id) {
			$this->setError( _BILLETS_TICKET." "._BILLETS_UPDATEFAILED );
			return false;
		}
	
		// change published
		if ($info->followup == 1) { $info->followup = 0; } else { $info->followup = 1; }
		

		if (!$info->store()) {
			$this->setError( $info->getError() );
			return false;
		}
	
	    return true;
	}

	/**
	 * Sets followup value
	 * @return boolean yes/no on success/fail
	 */
	function addcomment() {
		global $mainframe;

		$database = &JFactory::getDBO();

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

		$id		 	= intval ( JArrayHelper::getValue( $_POST, "id" ) );
		$message	= strval ( htmlspecialchars ( JArrayHelper::getValue( $_POST, "message" ) ) );

		$admin =& JFactory::getUser();
	
		// invalid entries
		if ( !$message ) {
        	$this->setError( _BILLETS_INVALIDENTRIES );
        	return false;
		}	
	
		$ticket = new billetsTicket ( $database );
		$ticket->load((int) $id );
		
		// invalid ticket
		if ( !$ticket->id ) {
        	$this->setError( _BILLETS_INVALIDTICKET );
        	return false;
		}	
				
		$resMessage = new billetsMessage( $database );
		$resMessage->ticketid			= $ticket->id;
		$resMessage->userid_from		= $admin->id;
		$resMessage->username_from		= $admin->email;
		$resMessage->message			= $message;	
		$resMessage->datetime			= date( "Y-m-d H:i:s" );
		$resMessage->store();
	
		if ($ticket->firstresponse_by == '0') { 
			$ticket->firstresponse_by = $admin->id; 
			$ticket->firstresponse_datetime = date( "Y-m-d H:i:s" );
		}
		$ticket->status					= 3; // requires user feedback	
		$ticket->last_modified_datetime = date( "Y-m-d H:i:s" );

   		// Store the entry to the database
    	if (!$ticket->store()) {
        	$this->setError($database->getErrorMsg());
        	return false;
    	}
		
		return $ticket;
	}		

}
// ************************************************************************
