<?php

/**
 * @name        Social Pin Board
 * @version	1.0: pincategory.php$
 * @since       Joomla 1.5&1.6&1.7
 * @package	apptha
 * @subpackage	com_socialpinboard
 * @author      Contus Support
 * @copyright   Copyright (C) 2011 powered by Apptha
 * @license     GNU/GPL http://www.gnu.org/copyleft/gpl.html
 */
//No direct acesss
defined('_JEXEC') or die();
jimport('joomla.application.component.model');
jimport('joomla.filesystem.file');

class wishlogueModelsubcatalogues extends WishlogueModel {

	function __construct() {
		parent::__construct();
		//Get configuration
		$app = JFactory::getApplication();
		$config = JFactory::getConfig();
		$limitstart = '';
		// Get the pagination request variables
		$this->setState('limit', $app->getUserStateFromRequest('wishlogue.limit', 'limit', $config->get('list_limit'), 'int'));
		$this->setState('limitstart', JRequest::getVar('limitstart', 0, '', 'int'));
	}

	function phpSlashes($string, $type = 'add') {
		if ($type == 'add') {
			if (get_magic_quotes_gpc()) {
				return $string;
			} else {
				if (function_exists('addslashes')) {
					return addslashes($string);
				} else {
					return mysql_real_escape_string($string);
				}
			}
		} else if ($type == 'strip') {
			return stripslashes($string);
		} else {
			die('error in PHP_slashes (mixed,add | strip)');
		}
	}

	//To get the category from the database and display it
	function getsubcatalogues() {
		global $option, $mainframe;
		$app = JFactory::getApplication();
		$mainframe = JFactory::getApplication();
		$search_filter_subcatalogue = JRequest::getVar('filter_search_subcatalogue'); //get the values for the search
		$status_filter_subcatalogue = JRequest::getInt('filter_subcatalogue'); //get the status of the category
		$db = $this->getDBO(); //to enable db connection
		$limitstart = '';
		$limit = '';

		$filter_order_subcatalogue = $app->getUserStateFromRequest($option . 'filter_order_subcatalogue', 'filter_order', 'subcatalogue_id', 'cmd');
		$filter_order_Dir = $app->getUserStateFromRequest($option . 'filter_order_Dir', 'filter_order_Dir', 'DESC', 'word');
		$search_filter_subcatalogue = $this->phpSlashes($search_filter_subcatalogue);

		if ($search_filter_subcatalogue == null) {
			$search_filter_subcatalogue = '';
		}
		$where = " WHERE subcatalogue_name LIKE '%$search_filter_subcatalogue%' ";
		if ($status_filter_subcatalogue == '2') {
			$where .= " AND status = 0 ";
		} else if ($status_filter_subcatalogue == '1') {
			$where .= " AND status = 1 ";
		}

		$query = "SELECT COUNT(subcatalogue_id) FROM #__pin_subcatalogues $where "; //query for pagination
		$db->setQuery($query);
		$total = $db->loadresult();
		jimport('joomla.html.pagination');
		$pageNav = new JPagination($total, $this->getState('limitstart'), $this->getState('limit'));

		$where = " WHERE a.subcatalogue_name LIKE '%$search_filter_subcatalogue%' AND b.status = 1 AND b.published != -2 ";
		if ($status_filter_subcatalogue == '2') {
			$where .= " AND a.status = 0 ";
		} else if ($status_filter_subcatalogue == '1') {
			$where .= " AND a.status = 1 ";
		}

		//Sorting query
		$where .= '  ORDER BY ' . $filter_order_subcatalogue . ' ' . $filter_order_Dir .
				' LIMIT ' . $pageNav->limitstart . ',' . $pageNav->limit;

		$query = "SELECT a.subcatalogue_name, a.status, a.created_date, a.subcatalogue_id, 
					b.category_name, b.category_id 
					FROM #__pin_subcatalogues a 
					LEFT JOIN #__pin_categories b 
					ON b.category_id = a.catalogue_id 
					$where ";
		$db->setQuery($query);
		$getsubcatalogues = $db->loadObjectList();

		if ($getsubcatalogues === null) {
			JError::raiseError(500, 'Error reading db');
		}

		$getsubcatalogues = array('pageNav' => $pageNav, 'limitstart' => $limitstart, 'sub_catalogues' => $getsubcatalogues, 'order_Dir' => $filter_order_Dir, 'order' => $filter_order_subcatalogue, 'status_value' => $status_filter_subcatalogue); //merging the pagination values and results
		return $getsubcatalogues; //return the final result
	}

	//Function To edit the pin categories
	function editsubcatalogue($id) {
		global $mainframe;
		$option = JRequest::getCmd('option');
		$db = JFactory::getDBO();
		$query = "SELECT a.subcatalogue_name, a.status, a.created_date, a.subcatalogue_id, 
			b.category_name, b.category_id 
			FROM #__pin_subcatalogues a 
			LEFT JOIN #__pin_categories b 
			ON b.category_id = a.catalogue_id 
			WHERE b.status = 1 AND b.published != -2 AND a.subcatalogue_id = $id ";
		$db->setQuery($query);
		$result = $db->loadObject();

		if ($result === null) {
			JError::raiseError(500, 'detail with ID: ' . $id . ' not found.');
		}
		else {
			return $result;
		}
	}

	//Function To get category names
	function getcatalogues() {
		global $mainframe;
		$option = JRequest::getCmd('option');
		$db = JFactory::getDBO();
		$query = "SELECT category_name, category_id 
					FROM #__pin_categories 
					WHERE status = 1 AND published != -2 ";
		$db->setQuery($query);
		$result = $db->loadObjectList();

		if ($result === null) {
			JError::raiseError(500, 'detail with ID: ' . $id . ' not found.');
		} else {
			return $result;
		}
	}

	//To Save the Subcatalogue
	function savesubcatalogue($detail) {

		//print_r($detail); die;
		$db = JFactory::getDbo();
		$app = JFactory::getApplication();

		$catalogue_id = $detail['catalogue_id'];
		$status = $detail['status'];
		$subcatalogue_name = $detail['subcatalogue_name'];
		$subcatalogue_id = $detail['cid'];
		$old_catalogue_name = $detail['old_catalogue_name'];
		$old_catalogue_id = $detail['old_catalogue_id'];
		$old_subcatalogue_name = $detail['old_subcatalogue_name'];
		if( $subcatalogue_id == '' || $subcatalogue_id == null ) {
			$subcatalogue_id = 0;
		}
		$errMsg = '';

		$query = "SELECT category_name  
					FROM #__pin_categories 
					WHERE category_id = $catalogue_id ";
		$db->setQuery($query);
		$catalogueName = $db->loadResult();

		$query = "SELECT subcatalogue_id 
					FROM #__pin_subcatalogues 
					WHERE subcatalogue_name = '$subcatalogue_name' AND catalogue_id = $catalogue_id AND 
					subcatalogue_id != $subcatalogue_id ";
		$db->setQuery($query);
		$subcatalogueExistence = $db->loadResult();
		if ($subcatalogueExistence > 0) {
			$errMsg = "Not saved. Subcatalogue '$subcatalogue_name' is already exist on '$catalogueName' catalogue";
		}

		if ( $errMsg != '' ) {
			JError::raiseError(500, $errMsg);
			$app->redirect(JRoute::_('index.php?option=com_wishlogue&layout=subcatalogues', false));
		} else {

			$detailTableRow = $this->getTable('subcatalogues');
			if (!$detailTableRow->bind($detail)) {
				JError::raiseError(500, 'Error binding data');
			}
			if (!$detailTableRow->check()) {
				JError::raiseError(500, 'Invalid data');
			}
			if (!$detailTableRow->store()) {
				$errorMessage = $detailTableRow->getError();
				JError::raiseError(500, 'Error binding data: '.$errorMessage);
			}

			$catalogue_id = $detailTableRow->catalogue_id;
			$subcatalogue_name = $detailTableRow->subcatalogue_name;
			$admin_subcatalogue = $detailTableRow->subcatalogue_id;
			
			if( $subcatalogue_id == 0 ) {
				$query = " UPDATE `#__pin_boards` SET `admin_subcatalogue`= $admin_subcatalogue 
							WHERE `board_name`='$subcatalogue_name' AND `board_category_id`=$catalogue_id";
				$db->setQuery($query);
				$db->query();
			} else {

				$query = " SELECT `user_id` FROM `#__pin_boards` 
							WHERE `board_name`='$subcatalogue_name' AND `board_category_id`=$catalogue_id 
							AND admin_subcatalogue != $subcatalogue_id ";
				$db->setQuery($query);
				$user_id = $db->loadColumn();
				if( count($user_id) <= 0 ) {
					$user_id = array(-1);
				}
				$user_ids = implode(',', $user_id);

				$query = " UPDATE `#__pin_boards` SET `board_name`='$subcatalogue_name', `board_category_id`=$catalogue_id 
							WHERE admin_subcatalogue = $subcatalogue_id AND `user_id` NOT IN ($user_ids) ";
				$db->setQuery($query);
				$db->query();

				$query = " UPDATE `#__pin_boards` SET admin_subcatalogue = $subcatalogue_id 
							WHERE `board_name`='$subcatalogue_name' AND `board_category_id`=$catalogue_id 
							AND `user_id` IN ($user_ids) ";
				$db->setQuery($query);
				$db->query();

				$query = " UPDATE `#__pin_boards` SET admin_subcatalogue = 0 
							WHERE `board_name`='$old_subcatalogue_name' AND `board_category_id`=$old_catalogue_id 
							AND `user_id` IN ($user_ids) ";
				$db->setQuery($query);
				$db->query();
			}
			$app->redirect(JRoute::_('index.php?option=com_wishlogue&layout=subcatalogues', false), 'Subcatalogue saved!', $msgType = 'message');
		}

	}

	function deletesubcatalogues($arrayIDs) {

		$db = $this->getDBO();

		$query = "DELETE FROM #__pin_subcatalogues WHERE subcatalogue_id IN (" . implode(',', $arrayIDs) . ")";
		$db->setQuery($query);
		$db->query();

		$query = "UPDATE `#__pin_boards` SET admin_subcatalogue = 0 WHERE admin_subcatalogue IN (" . implode(',', $arrayIDs) . ")";
		$db->setQuery($query);
		$db->query();
	}

	// Function To publish or unpublish the subcatalogue
	function pubsubcatalogue($arrayIDs) {
		$db = $this->getDBO();
		if ($arrayIDs['task'] == "publish") {
			$publish = 1; //to publish a category
		} else {
			$publish = 0; //to unpublish a category
		}
		$subcatalogues = implode(',', $arrayIDs['cid']);
		if($subcatalogues == '' || $subcatalogues == null) {
			$subcatalogues = 0;
		}
		$query = "UPDATE #__pin_subcatalogues SET status =" . $publish . " WHERE subcatalogue_id IN ($subcatalogues)";
		$db->setQuery($query);
		$db->query();

		if( $publish == 0 ) {

			$query = "UPDATE `#__pin_boards` SET admin_subcatalogue = 0 WHERE admin_subcatalogue IN ($subcatalogues)";
			$db->setQuery($query);
			$db->query();
		} else {
			$query = " SELECT a.`board_id`, b.`subcatalogue_id` FROM `#__pin_boards` a
							INNER JOIN `#__pin_subcatalogues` b WHERE 
							a.`board_name` = b.`subcatalogue_name` AND 
							a.`board_category_id` = b.`catalogue_id` AND 
							b.`subcatalogue_id` IN ($subcatalogues)";
			$db->setQuery($query);
			$board_ids = $db->loadObjectList();

			foreach( $board_ids as $board_id ) {
				$query = "UPDATE `#__pin_boards` SET admin_subcatalogue = $board_id->subcatalogue_id 
							WHERE board_id = $board_id->board_id";
				$db->setQuery($query);
				$db->query();
			}
		}
		
	}

}

?>