<?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
 */

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

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

class Djcatalog2ModelCategory extends DJCJModelAdmin
{
	protected $text_prefix = 'COM_DJCATALOG2';
    protected $associationsContext = 'com_djcatalog2.category';

	public function __construct($config = array()) {
		//$config['event_after_save'] = 'onCategoryAfterSave';
		//$config['event_after_delete'] = 'onCategoryAfterDelete';
		parent::__construct($config);
	}

    public function getItem($pk = null) {
        if ($item = parent::getItem($pk)) {
            /*
             * Multilang
             */
            if (JLanguageAssociations::isEnabled())
            {
                $item->associations = array();

                if ($item->id != null)
                {
                    $associations = JLanguageAssociations::getAssociations('com_djcatalog2', '#__djc2_categories', 'com_djcatalog2.category', (int) $item->id, 'id', '', '');

                    foreach ($associations as $tag => $association)
                    {
                        $item->associations[$tag] = $association->id;
                    }
                }
            }



            return $item;
        } else {
            return false;
        }
    }

	public function getTable($type = 'Categories', $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.category', 'category', array('control' => 'jform', 'load_data' => $loadData));
		if (empty($form)) {
			return false;
		}

		return $form;
	}

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

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

		return $data;
	}

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

		$table->name		= htmlspecialchars_decode($table->name, ENT_QUOTES);
		$table->alias		= JApplicationHelper::stringURLSafe($table->alias);

		if (empty($table->alias)) {
			$table->alias = JApplicationHelper::stringURLSafe($table->name);
		}

		if (empty($table->id)) {
			if (empty($table->ordering)) {
				$db = JFactory::getDbo();
				$db->setQuery('SELECT MAX(ordering) FROM #__djc2_categories WHERE parent_id = '.$table->parent_id);
				$max = $db->loadResult();

				$table->ordering = $max+1;
			}
		}
	}

	protected function getReorderConditions($table)
	{
		$condition = array();
		$condition[] = 'parent_id = '.(int) $table->parent_id;
		
		$where = implode(' AND ', $condition);
		return $where;
		//return $condition;
	}

	public function delete(&$cid = array())
	{
		if (count( $cid ))
		{
			$categories = Djc2Categories::getInstance();
			$categoryList = $cid;
			foreach($cid as $catid){
				$sublist = array($catid);
				if ($parent = $categories->get($catid) ) {
					$parent->makeChildrenList($sublist);
				}
				$categoryList = array_merge($categoryList, $sublist);
			}
			$categoryList = array_unique($categoryList);
			$cids = implode(',', $categoryList);

			$this->_db->setQuery("SELECT COUNT(*) FROM #__djc2_items WHERE cat_id IN ( ".$cids." )");
			if ($this->_db->loadResult() > 0) {
				$this->setError(JText::_('COM_DJCATALOG2_DELETE_CATEGORIES_HAVE_ITEMS'));
				return false;
			}

			$cid = $categoryList;
			if (parent::delete($cid)){
				// since products may still be assigned to additional categories, we need to break those relations
				$this->_db->setQuery('delete from #__djc2_items_categories where category_id in ('.implode(',', $cid).')');
				if (!$this->_db->execute()) {
					$this->setError($this->_db->getErrorMsg());
					return false;
				}
				return true;
			}
		}
		return false;
	}


	public function save($data) {
		if(isset($data['sections'])) {
			if (!empty($data['sections'])) {
				if (is_array($data['sections'])) {
					$data['sections'] = json_encode($data['sections']);
				}
			} else {
				$data['sections'] = null;
			}
		}
		
		if(isset($data['sections']) && !empty($data['sections']) && $data['sections'] != '[]'  && is_array($data['sections'])) {
			$data['sections'] = json_encode($data['sections']);
		}
		
		return parent::save($data);
	}

	/**
	 * 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.catalogue', $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.catalogue', $this->option);
	}

    /**
     * Method to preprocess the form to add the association fields dynamically
     *
     * @return     none
     */
	protected function preprocessForm(Joomla\CMS\Form\Form $form, $data, $group = 'content')
    {
        // Association content items
        if (JLanguageAssociations::isEnabled())
        {
            $languages = JLanguageHelper::getContentLanguages(false, true, null, 'ordering', 'asc');

            if (count($languages) > 1)
            {
                $addform = new SimpleXMLElement('<form />');
                $fields = $addform->addChild('fields');
                $fields->addAttribute('name', 'associations');
                $fieldset = $fields->addChild('fieldset');
                $fieldset->addAttribute('name', 'item_associations');

                foreach ($languages as $language)
                {
                    $field = $fieldset->addChild('field');
                    $field->addAttribute('name', $language->lang_code);
                    $field->addAttribute('type', 'djcategorymodal');
                    $field->addAttribute('language', $language->lang_code);
                    $field->addAttribute('label', $language->title);
                    $field->addAttribute('translate_label', 'false');
                }

                $form->load($addform, false);
            }
        }

        parent::preprocessForm($form, $data, $group);
    }


    public function batch($pk, $batchData, $cursor)
    {

        $language = ((isset($batchData['language_id'])) ? $batchData['language_id'] : null);
        $language_copy = ((isset($batchData['language_copy'])) ? $batchData['language_copy'] : 'n');
        $move_copy = ((isset($batchData['move_copy'])) ? $batchData['move_copy'] : 'copy');

        $multilangEnabled = JLanguageAssociations::isEnabled();

        $success = false;
        $message = 'invalid language';
        $error = '';

        $db = JFactory::getDbo();

        $table = $this->getTable();
        if ($language && $language_copy) {


            $item = $this->getItem($pk);


            // Get item images
            $query = $db->getQuery(true);
            $query
                ->select('id')
                ->from($db->quoteName('#__djc2_images', 'i'))
                ->where('i.type = ' . $db->quote('category'))
                ->where('i.item_id = ' . (int)$pk);

            $db->setQuery($query);
            $images = $db->loadColumn();

            $baseLang = $item->language;
            $baseName = $item->name;

            if ($baseLang == $language) {
                $error = JText::sprintf('COM_DJCATALOG2_MOVE_DUPLICATE_LANG', $pk);
            }


            $app = JFactory::getApplication();
            $db = JFactory::getDbo();

            if($move_copy == 'copy') {
                $item->id = 0;
                $app->input->set('id', 0);
                $this->setState('category.id', 0);
            }

            $db->setQuery('SELECT Count(*) FROM #__djc2_categories WHERE alias LIKE ' . $db->quote($db->escape('%' . $item->alias . '%')));
            $aliasesCount = $db->loadResult();

            $item->alias = $item->name . '-' . $aliasesCount;

            // Multilang
            if (isset($item->parent_id) && $item->parent_id && $multilangEnabled && $language_copy !== 'n') {
                $associations = JLanguageAssociations::getAssociations('com_djcatalog2', '#__djc2_categories', 'com_djcatalog2.category', (int)$item->parent_id, 'id', '', '');


                if (isset($associations[$language]->id)) {
                    $item->parent_id = $associations[$language]->id;
                }
            }else {
                $item->parent_id = 0;
            }


            // Default values
            $item->published = 0;
            $item->language = $language;

            if($language_copy == 'n') {
                $item->associations = array();
            } else {
                $item->associations[$baseLang] = $pk;
            }





            $app->input->set('image_file_id', $images);
            $currentTask = $app->input->get('task');
            $app->input->set('task', 'save2copy');

            $success =$this->save( Joomla\Utilities\ArrayHelper::fromObject($item));

            $message = '[' . $baseLang . '] ' . $baseName . ' (' . $move_copy . ') => ' . '[' . $language . ']' . $table->name . (($language_copy == 'y') ? ' (' . JText::_('COM_DJCATALOG2_BATCH_LANGUAGE_COPY_ASSIGNMENTS') . ')' : '');
        }

        if ($success) {
            $app = JFactory::getApplication();
            $cid = $app->getUserState('com_djcatalog2.list.categories');

            unset($cid[$cursor]);
            $cid = array_values($cid);
            $app->setUserState('com_djcatalog2.list.categories', $cid);

        }

        return array(
            'success' => $success,
            'message' => $message,
            'error' => $error
        );

    }

    protected function batchCopy($value, $pks, $contexts)
    {
        // Initialize re-usable member properties, and re-usable local variables
        $this->initBatch();


        $language_id = $value;
        // Initialize re-usable member properties, and re-usable local variables

        $newIds = array();
        $db = $this->getDbo();


        // Parent exists so let's proceed
        while (!empty($pks)) {
            // Pop the first ID off the stack
            $pk = array_shift($pks);

            $query = $db->getQuery(true);
            $query
                ->select('id')
                ->from($db->quoteName('#__djc2_images', 'i'))
                ->where('i.type = ' . $db->quote('category'))
                ->where('i.item_id = ' . (int)$pk);

            $db->setQuery($query);
            $images = $db->loadColumn();

            $this->table->load($pk);
            $oldlang = ((isset($this->table->language)) ? $this->table->language : null);

            if ($oldlang == $language_id) {
                // Not fatal error
                $this->setError(\JText::sprintf('COM_DJCATALOG2_MOVE_DUPLICATE_LANG', $pk));
                continue;
            }


            // Reset the ID because we are making a copy
            $this->table->id = 0;

            $app = JFactory::getApplication();
            $db = JFactory::getDbo();
            $db->setQuery('SELECT Count(*) FROM #__djc2_categories WHERE alias LIKE ' . $db->quote($db->escape('%' . $this->table->alias . '%')));
            $aliasesCount = $db->loadResult();

            $this->table->alias .= (($aliasesCount) ? '-' . $aliasesCount : '');

            if (isset($this->table->parent_id) && $this->table->parent_id) {
                $associations = JLanguageAssociations::getAssociations('com_djcatalog2', '#__djc2_categories', 'com_djcatalog2.category', (int)$this->table->parent_id, 'id', '', '');


                if (isset($associations[$language_id]->id)) {
                    $this->table->parent_id = $associations[$language_id]->id;
                }
            }


            // Unpublish because we are making a copy
            if (isset($this->table->published)) {
                $this->table->published = 0;
            }

            // New category ID
            $this->table->language = $language_id;

            if (!$this->table->check()) {
                $this->setError($this->table->getError());

                return false;
            }

            // Store the row.
            if (!$this->table->store()) {
                $this->setError($this->table->getError());

                return false;
            }

            // Get the new item ID
            $newId = $this->table->get('id');


            $dispatcher = Joomla\CMS\Factory::getApplication()->getDispatcher();
            new Djcatalog2Event($dispatcher);

            $app->input->set('image_file_id', $images);
            $currentTask = $app->input->get('task');
            $app->input->set('task', 'import');

            Joomla\CMS\Factory::getApplication()->triggerEvent('onContentAfterSave', array('com_djcatalog2.category', &$this->table, 1));

            $this->cleanupPostBatchCopy($this->table, $newId, $pk);

            if ($language_id !== '*') {
                $data = array(
                    'id' => $newId,
                    'alias' => $this->table->alias,
                    'associations' => array(
                        $oldlang => $pk
                    )
                );


                $this->save($data);
            }

            // Add the new ID to the array
            $newIds[$pk] = $newId;
        }

        $app->input->set('task', $currentTask);
        // Clean the cache
        $this->cleanCache();
        return $newIds;
    }
}
