<?php
/**
 * @version $Id: taxrule.php 272 2014-05-21 10:25:49Z michal $
 * @package DJ-Catalog2
 * @copyright Copyright (C) 2012 DJ-Extensions.com LTD, All rights reserved.
 * @license http://www.gnu.org/licenses GNU/GPL
 * @author url: http://dj-extensions.com
 * @author email contact@dj-extensions.com
 * @developer Michal Olczyk - michal.olczyk@design-joomla.eu
 *
 * DJ-Catalog2 is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * DJ-Catalog2 is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with DJ-Catalog2. If not, see <http://www.gnu.org/licenses/>.
 *
 */

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

//jimport('joomla.application.component.modeladmin');
require_once(JPATH_ROOT.'/administrator/components/com_djcatalog2/lib/modeladmin.php');

class Djcatalog2ModelSubscription extends DJCJModelAdmin
{
	protected $text_prefix = 'COM_DJCATALOG2';

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

	public function getTable($type = 'Subscriptions', $prefix = 'Djcatalog2Table', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}
	
	public function getItem($pk = null)
	{
		$item = parent::getItem($pk);
		if (!empty($item)) {
			$item->granted_usergroups = ($item->granted_usergroups && $item->granted_usergroups!='[]') ? json_decode($item->granted_usergroups) : array();
		}
		return $item;
	}
	
	public function getForm($data = array(), $loadData = true)
	{
		// Initialise variables.
		$app	= JFactory::getApplication();

		// Get the form.
		$form = $this->loadForm('com_djcatalog2.subscription', 'subscription', array('control' => 'jform', 'load_data' => $loadData));
		if (empty($form)) {
			return false;
		}
		return $form;
	}

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

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

		return $data;
	}
	
	protected function _prepareTable(&$table)
	{
		jimport('joomla.filter.output');
		$date = JFactory::getDate();
		$user = JFactory::getUser();

	}

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

	public function delete(&$cid) {
		
		$app = JFactory::getApplication();
		
		// Make sure the item ids are integers
		Joomla\Utilities\ArrayHelper::toInteger($cid);
		foreach ($cid as $id) {
			
			$item = $this->getItem($id);
			
			// handle purchase counter if applicable
			if($item->paid && $item->user_id) {
				$users[] = $item->user_id;
			}
		}
		
		$deleted = parent::delete($cid);
		
		/*if($deleted && count($users)) {
			$sub = new DJCatalog2Subscription();
			foreach($users as $uid) {
				$sub->updateCounter($uid);
			}
		}*/
		
		return $deleted;
	}
	
	public function save($data) {
		
		$app = JFactory::getApplication();
		$db 		= JFactory::getDBO();
		
		$date		= JFactory::getDate();
		$customer	= JFactory::getUser($data['user_id']);
		
		if (!intval($data['start_date'])) {
			$data['start_date'] = $date->toSql();
		}
        
        $isNew = false;
		
		if(!$data['id']) { // new subs
		    $isNew = true;
        
			$table = $this->getTable('Items');
			if(!$table->load($data['item_id'])) {
				$this->setError('Product not found');
				return false;
			}
			
			//if(!$table->subscription) {
			if($table->product_type != 'subscription') {
				$this->setError('Product is not a subscription');
				return false;
			}
			
			$data['granted_usergroups'] = $table->grant_usergroups;
			
			if (!intval($data['expire_date'])) {
				//$data['expire_date'] = $table->expiration ? JFactory::getDate($data['expire_date'] .' +'.$table->expiration.' days')->toSql() : $db->getNullDate(); // expire_date
				$data['expire_date'] = $table->expiration ? JFactory::getDate($data['expire_date'] .' +'.$table->expiration.' days')->toSql() : null; // expire_date
			}
		}
		
		$expire = JFactory::getDate($data['expire_date'])->toUnix();
		if($data['status'] == 1 && $expire <= $date->toUnix()) {
			$app->enqueueMessage(JText::_('COM_DJCATALOG2_STATUS_CHANGED_BECAUSE_EXPIRE_DATE'), 'warning');
			$data['status'] = 0;
		}
		
		$saved = parent::save($data);
        
		/*if($data['user_id']) {
			$sub = new DJCatalog2Subscription();
			if(!$sub->updateCounter($data['user_id'])) {
				$app->enqueueMessage($sub->getError(), 'warning');
			}
		}*/
		
		
        if ($saved && $isNew && $data['user_id']) {
            $subId = $this->getState($this->getName() . '.id');
            $subTable = $this->getTable('Subscriptions');
            if ($subTable->load($subId)) {
                $subData = $subTable->getProperties(true);
                $subData= Joomla\Utilities\ArrayHelper::toObject($subData, 'JObject');
                /*if (!$data['extended']) {
                	$this->_sendSubscriptionEmail($subData);
                } else {
                	$this->_sendExtdSubscriptionEmail($subData);
                }*/
                $app->triggerEvent('onDJC2SubscriptionActivation', array($subData));
                $this->_sendSubscriptionEmail($subData);
            }
        }
        
        return $saved;
	}

	protected function _sendSubscriptionEmail($subscription)
    {
        
        require_once JPATH_ROOT.'/components/com_djcatalog2/helpers/html.php';
        require_once JPATH_ROOT.'/components/com_djcatalog2/helpers/djcatalog2.php';
        require_once(JPATH_ROOT.'/administrator/components/com_djcatalog2/helpers/messenger.php');
        
        $db = JFactory::getDbo();
        $db->setQuery('select * from #__users where id='.$subscription->user_id);
        $user = $db->loadObject();
        
        if (empty($user)) {
        	return false;
        }
        
        $subscriptions = array($subscription);
        
        $data = array('user' => $user, 'subscriptions' => $subscriptions);
        
        $mailopts = [
        	'recipient_name' => $user->username,
        	'subscription_items' => DJCatalog2HtmlHelper::getThemeLayout($data, 'subscription_items', 'email/layouts'),
        ];
        
        $messenger = new DJCatalog2HelperMessenger();
        $messenger->notify($user->email, ['type' => 'subscription_new'], [], $mailopts );
        
        return true;
    }

	/*protected function _sendExtdSubscriptionEmail($subscription)
    {
        require_once JPATH_ROOT.'/components/com_djcatalog2/helpers/html.php';
        require_once JPATH_ROOT.'/components/com_djcatalog2/helpers/djcatalog2.php';
    
        $app        = JFactory::getApplication();
        $params     = JComponentHelper::getParams('com_djcatalog2');
        $config     = JFactory::getConfig();
        
        $db = JFactory::getDbo();
        $db->setQuery('select * from #__users where id='.$subscription->user_id);
        $user = $db->loadObject();
        
        if (empty($user)) {
            return false;
        }
    
        $mailfrom   = $config->get('mailfrom');
        $fromname   = $config->get('fromname');
        $sitename   = $config->get('sitename');
        
        $data = array('user' => $user, 'subscriptions' => array($subscription)); 
        
        $body = DJCatalog2HtmlHelper::getEmailTemplate($data, 'extdsubscription');
        
        if (!$body) {
            return false;
        }
        
        $mail = JFactory::getMailer();
        $mail->addRecipient($user->email);
        
        $mail->setSender(array($mailfrom, $fromname));
        $mail->setSubject(JText::sprintf('COM_DJCATALOG2_NOT_EXTD_SUBSCRIPTION_SUBJ', $sitename));
        $mail->setBody($body);
        $mail->isHtml(true);
        
        return $mail->Send();
    }*/
    
    /**
     * 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);
    }
}