<?php

/**
 * @package DJ-Catalog2
 * @copyright Copyright (C) DJ-Extensions.com, All rights reserved.
 * @license http://www.gnu.org/licenses GNU/GPL
 * @author url: http://dj-extensions.com
 * @author email contact@dj-extensions.com
 */

use Joomla\Registry\Registry;

// No direct access.
defined('_JEXEC') or die;

class Djcatalog2ModelQuery extends JModelAdmin
{
	protected $text_prefix = 'COM_DJCATALOG2';

	public function __construct($config = array()) {
		parent::__construct($config);
	}

	public function getTable($type = 'Quotes', $prefix = 'Djcatalog2Table', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}
	public function getForm($data = array(), $loadData = true)
	{
		// Initialise variables.
		$app	= JFactory::getApplication();

		// Get the form.
		$form = $this->loadForm('com_djcatalog2.query', 'query', array('control' => 'jform', 'load_data' => $loadData));
		if (empty($form)) {
			return false;
		}
		return $form;
	}
	
	public function getItem($pk = null)
	{
		$pk = (!empty($pk)) ? $pk : (int) $this->getState($this->getName() . '.id');
		$table = $this->getTable();
	
		if ($pk > 0)
		{
			// Attempt to load the row.
			$return = $table->load($pk);
	
			// Check for a table object error.
			if ($return === false && $table->getError())
			{
				$this->setError($table->getError());
				return false;
			}
		}
	
		// Convert to the JObject before adding other data.
		$properties = $table->getProperties(1);
		
		$item = Joomla\Utilities\ArrayHelper::toObject($properties, 'JObject');
		
		if (!is_array($item->items)) {
			if (isset($item->id)) {
				$this->_db->setQuery('SELECT * FROM #__djc2_quote_items WHERE quote_id=\''.$item->id.'\'');
				$item->items = $this->_db->loadObjectList();
			} else {
				$item->items = array();
			}
		}

		if (property_exists($item, 'params'))
		{
			$registry = new Registry();
			$registry->loadString($item->params);
			$item->params = $registry->toArray();
		}
		
		if (property_exists($item, 'additional_user_data'))
		{
			$registry = new Registry;
			$registry->loadString($item->additional_user_data);
			$registry = $registry->toArray();
			$item->additional_user_data = $registry;
			
			foreach($registry as $set => $values ) {
				foreach($values as $field) {
					$alias = $field['alias'];
					$item->$alias = $field['value_text'];
				}
			}
		}
	
		return $item;
	}
	

	protected function loadFormData()
	{
		$data = JFactory::getApplication()->getUserState('com_djcatalog2.edit.query.data', array());

		if (empty($data)) {
			$data = $this->getItem();
		}

		return $data;
	}
	
	protected function preprocessForm(Joomla\CMS\Form\Form $form, $data, $group = 'content')
	{
		Djcatalog2HelperUser::preprocessQueryForm($form, $data);
	}

	protected function prepareTable($table)
	{
		$db = JFactory::getDbo();
	}

	protected function getReorderConditions($table = null)
	{
		$condition = array();
		return $condition;
	}

	public function delete(&$cid) {
		if (parent::delete($cid)) {
			
			$cids = implode(',', $cid);
			
			$this->_db->setQuery("delete from #__djc2_quote_items WHERE quote_id IN ( ".$cids." )");
			if (!$this->_db->execute()) {
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
			return true;
		}
		return false;
	}
	
	public function save($data) {
		
		$new_status = $data['status'];
		$old_status = false;
		
		$userFields = Djcatalog2HelperUser::getUserFields('query');
		$additionalData = array();
		foreach($userFields as $field) {
			if ($field->is_core) continue;
			if (!isset($additionalData[$field->target_fieldset])) {
				$additionalData[$field->target_fieldset] = array();
			}
			if (isset($data[$field->alias])) {
				$additionalData[$field->target_fieldset][$field->id] = array('field' => $field->name, 'alias' => $field->alias, 'value' => '', 'value_text' => $data[$field->alias]);
			}
		}
		$data['additional_user_data'] = json_encode($additionalData);
		
		if ((int)$data['id'] > 0) {
			$table = $this->getTable();
			$table->load((int)$data['id']);
			$old_status = $table->status;
		}
		
		if (!parent::save($data)) {
			return false;
		}
		
		$id = $this->getState($this->getName() . '.id');
		$table = $this->getTable();
		$db = JFactory::getDbo();
		
		if ($table->load((int)$id) && $table->status != $old_status && !empty($table->email)) {
			$data = $table->getProperties();
			foreach ($data['items'] as $k=>$v) {
				$data['items'][$k] = Joomla\Utilities\ArrayHelper::fromObject($v);
			}
			
			return $this->_sendEmail($data);
		}
		
		return true;
	}
	
	public function set_status($id, $value, $notify = true) {
		
		$date = JFactory::getDate();
		$db = JFactory::getDbo();
		$user = JFactory::getUser();
		
		$db->setQuery('update #__djc2_quotes SET status='.$db->quote($value[0]).', modified='.$db->quote($date->toSql()).', modified_by='.$user->id.' WHERE id='.(int)$id);
		
		if (!$db->execute()) {
			$this->setError($db->getErrorMsg());
			return false;
		}
		
		$table = $this->getTable('Orders');
		
		if ($table->load((int)$id)) {
			$data = $table->getProperties();
			foreach ($data['items'] as $k=>$v) {
				$data['items'][$k] = Joomla\Utilities\ArrayHelper::fromObject($v);
			}
			
			if ($notify) {
				return $this->_sendEmail($data);
			}
		}
		
		return true;
	}
	
	private function _sendEmail($order)
	{
		require_once JPATH_ROOT.'/components/com_djcatalog2/helpers/html.php';
		require_once JPATH_ROOT.'/components/com_djcatalog2/helpers/djcatalog2.php';
		
		Djcatalog2Helper::loadComponentLanguage();
		
		$app		= JFactory::getApplication();
		$params 	= JComponentHelper::getParams('com_djcatalog2');
		$config 	= JFactory::getConfig();
		
		$mailfrom	= $config->get('mailfrom');
		$fromname	= $config->get('fromname');
		$sitename	= $config->get('sitename');
		
		$contact_list = $params->get('contact_list', false);
		$recipient_list = array();
		if ($contact_list !== false) {
			$recipient_list = explode(PHP_EOL, $params->get('contact_list', ''));
		}
		
		$list_is_empty = true;
		foreach ($recipient_list as $r) {
			if (strpos($r, '@') !== false) {
				$list_is_empty = false;
				break;
			}
		}
		
		if ($list_is_empty) {
			$recipient_list[] = $mailfrom;
		}
		
		$recipient_list = array_unique($recipient_list);
		
		$subject	= JText::sprintf('COM_DJCATALOG2_EMAIL_QUOTE_UPDATE_SUBJECT', $sitename);
		
		$attachments = array();		
		$admin_attachments = array();
		
		$client_body = DJCatalog2HtmlHelper::getEmailTemplate($order, 'quote_update', $attachments);
		$admin_body = DJCatalog2HtmlHelper::getEmailTemplate($order, 'admin.quote_update', $admin_attachments);
		
		// Send an email to customer
		foreach ($recipient_list as $recipient) {
			$mail = JFactory::getMailer();
			$mail->addRecipient(trim($recipient));
			$mail->setSender(array($mailfrom, $fromname));
			$mail->setSubject($subject);
			$mail->setBody($admin_body);
			$mail->isHtml(true);
			
			if (is_array($attachments) && count($attachments)) {
				foreach($attachments as $file) {
					$name = basename($file);
					$mail->addAttachment($file, $name);
				}
			}
			
			$mail_sent = $mail->Send();
		}
		
		// Send an email to customer
		$mail = JFactory::getMailer();
		$mail->addRecipient($order['email']);
		$mail->setSender(array($mailfrom, $fromname));
		$mail->setSubject($subject);
		$mail->setBody($client_body);
		$mail->isHtml(true);
		
		if (is_array($admin_attachments) && count($admin_attachments)) {
			foreach($admin_attachments as $file) {
				$name = basename($file);
				$mail->addAttachment($file, $name);
			}
		}
		
		$mail_sent = $mail->Send();
		
		return $mail_sent;
	}
	
	/**
	 * Method to test whether a record can be deleted.
	 *
	 * @param   object  $record  A record object.
	 *
	 * @return  boolean  True if allowed to delete the record. Defaults to the permission for the component.
	 *
	 * @since   1.6
	 */
	protected function canDelete($record)
	{
		return JFactory::getUser()->authorise('core.delete', $this->option) || JFactory::getUser()->authorise('djcatalog2.admin.orders', $this->option);
	}
	
	/**
	 * Method to test whether a record can have its state changed.
	 *
	 * @param   object  $record  A record object.
	 *
	 * @return  boolean  True if allowed to change the state of the record. Defaults to the permission for the component.
	 *
	 * @since   1.6
	 */
	protected function canEditState($record)
	{
		return JFactory::getUser()->authorise('core.edit.state', $this->option)  || JFactory::getUser()->authorise('djcatalog2.admin.orders', $this->option);
	}
}