<?php
/**
 * Adodis Blog package
 * @author J-Extension <contact@jextn.com>
 * @link http://www.jextn.com
 * @copyright (C) 2012 - 2013 J-Extension
 * @license GNU/GPL, see LICENSE.php for full license.
**/

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');

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

class AdodisBlogModelComment extends JModelAdmin
{
	/**
	 * Method to test whether a record can be deleted.
	 */
	protected function canDelete($record)
	{
		$user = JFactory::getUser();

		if ($record->catid) {
			return $user->authorise('core.delete', 'com_adodisblog.comment.'.(int) $record->catid);
		} else {
			return parent::canDelete($record);
		}
	}

	/**
	 * Method to test whether a record can be deleted.
	 */
	protected function canEditState($record)
	{
		$user = JFactory::getUser();

		// Check against the category.
		if (!empty($record->catid)) {
			return $user->authorise('core.edit.state', 'com_adodisblog.comment.'.(int) $record->catid);
		}
		// Default to component settings if category not known.
		else {
			return parent::canEditState($record);
		}
	}

	/**
	 * Returns a reference to the a Table object, always creating it.
	 */
	public function getTable($type = 'Comment', $prefix = 'AdodisBlogTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}

	/**
	 * Method to get the row form.
	 */
	public function getForm($data = array(), $loadData = true)
	{
		jimport('joomla.form.form');

		// Get the form.
		$form	= $this->loadForm('com_adodisblog.comment', 'comment', array('control' => 'jform', 'load_data' => $loadData));
		//$postvalue 	= $_POST["video"];

		if (empty($form)) {
			return false;
		}

		// Modify the form based on access controls.
		if (!$this->canEditState((object) $data)) {
			// Disable fields for display.
			$form->setFieldAttribute('published', 'disabled', 'true');
			$form->setFieldAttribute('access', 'disabled', 'true');
			$form->setFieldAttribute('language', 'disabled', 'true');

			// Disable fields while saving.
			// The controller has already verified this is a record you can edit.
			$form->setFieldAttribute('published', 'filter', 'unset');
			$form->setFieldAttribute('access', 'filter', 'unset');
			$form->setFieldAttribute('language', 'filter', 'unset');
		}

		return $form;
	}

	/**
	 * Method to get a single record.
	 */
	public function getItem($pk = null)
	{
		$item = parent::getItem($pk);
		return $item;
	}

	/**
	 * Method to get the data that should be injected in the form.
	 */
	protected function loadFormData()
	{
		// Check the session for previously entered form data.
		$data			= JFactory::getApplication()->getUserState('com_adodisblog.edit.comment.data', array());

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

			// Prime some default values.
			if ($this->getState('comment.id') == 0) {
				$app 	= JFactory::getApplication();
				$data->set('catid', JRequest::getInt('catid', $app->getUserState('com_adodisblog.comments.filter.category_id')));
			}
		}

		return $data;
	}

	/**
	 * Prepare and sanitise the table prior to saving.
	 */
	protected function prepareTable(&$table)
	{
		jimport('joomla.filter.output');
		$date 						= JFactory::getDate();
		$user 						= JFactory::getUser();

		if (empty($table->id)) {
			// Set the values
			$table->modified_date	= $date->toMySQL();
			$table->modified_by		= $user->get('username');
		}
	}

	/**
	 * A protected method to get a set of ordering conditions.
	 */
	protected function getReorderConditions($table)
	{
		$condition		= array();
		$condition[]	= 'catid = '.(int) $table->catid;
		$condition[]	= 'published >= 0';

		return $condition;
	}

	public function reorder($pks, $delta = 0)
	{
		// Clear the component's cache
		$cache = JFactory::getCache();
		$cache->clean('com_adodisblog');

		return parent::reorder($pks, $delta);
	}

	public function mailtoAdmin( $email, $name, $catid, $published, $bid )
	{
		$app				= JFactory::getApplication();
		$config				= JComponentHelper::getParams('com_adodisblog');
		$id					= $catid;
		$urladmin			= JURI::ROOT().'administrator/index.php?option=com_adodisblog&view=comment&layout=edit&id='.$id;
		$urladmin 			= '<a href="'.$urladmin.'" target="_blank">'.$urladmin.'</a>';
		$urlsite			= 'http://'.$_SERVER['SERVER_NAME'].JRoute::_('index.php?option=com_adodisblog&view=blog&id='.$bid);
		$urlsite 			= '<a href="'.$urlsite.' " target="_blank">'.$urlsite.'</a>';
		$to					= $app->getCfg('mailfrom');
		$sett_to			= $config->get('emailid');

		if ( $sett_to == 'admin@emailid.com' || $sett_to == '' ) {
			$to				= $app->getCfg('mailfrom');  //outputs mailfrom
		} else {
			$to				= $sett_to;
		}

		$from				= $email;
		$name				= $name;
		$site				= $app->getCfg('sitename'); //outputs sitename

		$sender 			= array( $from, $name );
		$mailer 			= & JFactory::getMailer();
		$mailer->setSender( $sender );

		$mailer->addRecipient( $to );

		$temp_obj 			= $this->getSettings();
		$template 			= $temp_obj->mail_admin_temp;

		if($published==1){
			$publish 		= "Published";
		}
		if($published==0){
			$publish 		= "unpublished";
		}

		$replace_link_a		= "admin-link";
		$replace_link_u		= "site-link";
		$replace_blog		= "blog/comment";
		$replace_uname		= "username";
		$replace_published	= "published/unpublished";
		$template			= str_replace("[".$replace_link_a."]", $urladmin, $template);
		$template			= str_replace("[".$replace_link_u."]", $urlsite, $template);
		$template			= str_replace("[".$replace_blog."]", "Comment", $template);
		$template			= str_replace("[".$replace_uname."]", $name, $template);
		$template			= str_replace("[".$replace_published."]", $publish , $template);
		$message			= $template;

		if($temp_obj->mail_admin_sub) {
			$subject 		= str_replace("[b/c]", "Comment", $temp_obj->mail_admin_sub);
		} else {
			$subject 		= sprintf ( JText::_( 'ADODIS_COMMENT_MAIL_SUBJECT' ), $name );
		}
		$subject 			= html_entity_decode($subject, ENT_QUOTES);
		$message 			= html_entity_decode($message, ENT_QUOTES);

		$mailer->setSubject( $subject );
		$mailer->setBody( $message );
		$mailer->IsHTML(true);

		if ($mailer->Send() == true) {
			return true;
		} else {
			return false;
		}
	}

	public function mailtoUser( $email, $name, $catid, $published, $bid )
	{
		$app				= JFactory::getApplication();
		$config				= JComponentHelper::getParams('com_adodisblog');
		$id					= $catid;
		$urlsite			= 'http://'.$_SERVER['SERVER_NAME'].JRoute::_('index.php?option=com_adodisblog&view=blog&id='.$bid);
		$urlsite 			= '<a href="'.$urlsite.' " target="_blank">'.$urlsite.'</a>';
		$from					= $app->getCfg('mailfrom');
		$sett_to			= $config->get('emailid');

		if ( $sett_to == 'admin@emailid.com' || $sett_to == '' ) {
			$from			= $app->getCfg('mailfrom');  //outputs mailfrom
		} else {
			$from			= $sett_to;
		}

		$to					= $email;
		$name				= $name;
		$site				= $app->getCfg('sitename'); //outputs sitename

		$sender 			= array( $from, $name );
		$mailer 			= & JFactory::getMailer();
		$mailer->setSender( $sender );

		$mailer->addRecipient( $to );

		$temp_obj 			= $this->getSettings();
		$template 			= $temp_obj->mail_user_temp;

		if($published==1){
			$publish 		= "Published";
		}
		if($published==0){
			$publish 		= "unpublished";
		}

		$replace_link_u		= "site-link";
		$replace_blog		= "blog/comment";
		$replace_uname		= "username";
		$replace_published	= "published/unpublished";
		$template			= str_replace("[".$replace_link_u."]", $urlsite, $template);
		$template			= str_replace("[".$replace_blog."]", "Comment", $template);
		$template			= str_replace("[".$replace_uname."]", $name, $template);
		$template			= str_replace("[".$replace_published."]", $publish , $template);
		$message			= $template;

		if($temp_obj->mail_admin_sub) {
			$subject 		= str_replace("[b/c]", "Comment", $temp_obj->mail_user_sub);
		} else {
			$subject 		= sprintf ( JText::_( 'ADODIS_COMMENT_MAIL_SUBJECT' ), $name );
		}
		$subject 			= html_entity_decode($subject, ENT_QUOTES);
		$message 			= html_entity_decode($message, ENT_QUOTES);

		$mailer->setSubject( $subject );
		$mailer->setBody( $message );
		$mailer->IsHTML(true);

		if ($mailer->Send() == true) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Get the category name.
	 */
	protected function getCategoryName( $catid )
	{
		if ($catid) {
			$db			= $this->getDbo();
			$query		= $db->getQuery(true);
			$query->select('title');
			$query->from('`#__categories`');
			$query->where('`id`='.$db->quote($catid));
			$db->setQuery((string)$query);
			$name		= $db->loadResult();

			if ($db->getErrorNum()) {
				$this->setError($db->getErrorMsg());
				return false;
			}
		} else {
			$name		= JText::_('COM_BANNERS_NOCATEGORYNAME');
		}

		return $name;
	}

	public function getSettings()
	{
		$id				= 1;
		$settings  		= JTable::getInstance('Settings', 'AdodisBlogTable');
		$settings->load($id);

		return $settings;
	}

}
?>
