<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
 
// import Joomla modelform library
jimport('joomla.application.component.modeladmin');
 
/**
 * MassContent Model
 */
class MassContentModelArticles extends JModelAdmin
{
	/**
	 * Method override to check if you can edit an existing record.
	 *
	 * @param	array	$data	An array of input data.
	 * @param	string	$key	The name of the key for the primary key.
	 *
	 * @return	boolean
	 * @since	1.6
	 */
	protected function allowEdit($data = array(), $key = 'id')
	{
		// Check specific edit permission then general edit permission.
		return JFactory::getUser()->authorise('core.edit', 'com_masscontent.message.'.((int) isset($data[$key]) ? $data[$key] : 0)) or parent::allowEdit($data, $key);
	}
	/**
	 * Returns a reference to the a Table object, always creating it.
	 *
	 * @param	type	The table type to instantiate
	 * @param	string	A prefix for the table class name. Optional.
	 * @param	array	Configuration array for model. Optional.
	 * @return	JTable	A database object
	 * @since	1.6
	 */
	public function getTable($type = 'Content', $prefix = 'JTable', $config = array()) 
	{
		return JTable::getInstance($type, $prefix, $config);
	}

	/**
	 * Method to get the record form.
	 *
	 * @param	array	$data		Data for the form.
	 * @param	boolean	$loadData	True if the form is to load its own data (default case), false if not.
	 *
	 * @return	mixed	A JForm object on success, false on failure
	 * @since	1.6
	 */
	public function getForm($data = array(), $loadData = true)
	{
        
		// Get the form.
 		$form = $this->loadForm('com_masscontent.content', 'content', array('control' => 'jform', 'load_data' => $loadData));
 
		if (empty($form)) {
			return false;
		} 


			// New record. Can only create in selected categories.
			$form->setFieldAttribute('catid', 'action', 'core.create');

		// Modify the form based on Edit State access controls.
		if (!$this->canEditState((object) $data)) {
			// Disable fields for display.
			$form->setFieldAttribute('featured', 'disabled', 'true');
			$form->setFieldAttribute('ordering', 'disabled', 'true');
			$form->setFieldAttribute('publish_up', 'disabled', 'true');
			$form->setFieldAttribute('publish_down', 'disabled', 'true');
			$form->setFieldAttribute('state', 'disabled', 'true');

			// Disable fields while saving.
			// The controller has already verified this is an article you can edit.
			$form->setFieldAttribute('featured', 'filter', 'unset');
			$form->setFieldAttribute('ordering', 'filter', 'unset');
			$form->setFieldAttribute('publish_up', 'filter', 'unset');
			$form->setFieldAttribute('publish_down', 'filter', 'unset');
			$form->setFieldAttribute('state', 'filter', 'unset');
		}

		return $form;
	}

	/**
	 * Method to get the script that have to be included on the form
	 *
	 * @return string	Script files
	 */
	public function getScript() 
	{
		return 'administrator/components/com_masscontent/models/forms/content.js';
	}
	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return	mixed	The data for the form.
	 * @since	1.6
	 */
/*	protected function loadFormData() 
	{
		// Check the session for previously entered form data.
		$data = JFactory::getApplication()->getUserState('com_masscontent.edit.masscontent.data', array());
		if (empty($data)) 
		{
			$data = $this->getItem();
		}
		return $data;
	}*/
	
	/**
	 * Prepare and sanitise the table data prior to saving.
	 *
	 * @param	JTable	A JTable object.
	 *
	 * @return	void
	 * @since	1.6
	 */
	protected function prepareTable(&$table)
	{
		// Set the publish date to now
		if($table->state == 1 && intval($table->publish_up) == 0) {
			$table->publish_up = JFactory::getDate()->toMySQL();
		}

		// Increment the content version number.
		$table->version++;

		// Reorder the articles within the category so the new article is first
		if (empty($table->id)) {
			$table->reorder('catid = '.(int) $table->catid.' AND state >= 0');
		}
	}
    
    
    /**
	 * Method to save the form data.
	 *
	 * @param	array	The form data.
	 *
	 * @return	boolean	True on success.
	 * @since	1.6
	 */
	public function save($data)
	{

        $table		= $this->getTable();
        $articlesArr = array();

         
       // $nbArticles = count($data['title']);

   // var_dump($data);
    //create array of articles
         foreach ($data as $k=>$v){
            //echo "<br>new value: $k <br>";
            if (is_array($v)){
                foreach ($v as $k2=>$v2){//process each value and put them into each new article
                    //echo "<br>$k2<br>";
                    if (is_array($v2)){
                        $j=0;
                        foreach ($v2 as $k3=>$v3){//2rd level for attribs  and metadada 
                            $articlesArr[$k3][$k][$k2]=$v3;      
                           //echo "<br>new subsubvalue $k3-$k2-$k: $v3 <br>";
                        }
                    }else{
                      //  echo "<br>new subvalue $k2-$k: $v2 <br>";
                        $articlesArr[$k2][$k]=$v2;                                    
                    }
                    //$i++;
                     //$articlesArr[$k2]["articletext"]=$data["articletext"][$k2-1];
                }   
            }
            //else echo "<br>$v not array<br>"; 
            //add content like that because of editor wysiwyg
           
        }
 
       
        
        
        foreach ($articlesArr as $article){ 
        
       		 if($article["title"]!=""){	     		 
      			  $table		= $this->getTable();
        
            	// Bind the data.
				if (!$table->bind($article)) {
					$this->setError($table->getError());
					return false;
				}

				// Prepare the row for saving
				$this->prepareTable($table);

				// Check the data.
				if (!$table->check()) {
					$this->setError($table->getError());
					return false;
				}
         	   
      	   		if ($ret = parent::save($article)) {
					if (isset($article['featured'])) {
						$this->featured($this->getState($this->getName().'.id'), $article['featured']);
					}
				}
				//echo "<br><PRE>save:$ret------".$this->getState($this->getName().'.id');var_dump($article);		
 				$this->setState($this->getName().'.id',null);
 			}
    	}     
		return true;
	}
 
    
    /**
	 * Method to toggle the featured setting of articles.
	 *
	 * @param	array	The ids of the items to toggle.
	 * @param	int		The value to toggle to.
	 *
	 * @return	boolean	True on success.
	 */
	public function featured($pks, $value = 0)
	{
		// Sanitize the ids.
		$pks = (array) $pks;
		JArrayHelper::toInteger($pks);
        
		if (empty($pks)) {
			$this->setError(JText::_('COM_CONTENT_NO_ITEM_SELECTED'));
			return false;
		}
        
		$table = $this->getTable('Featured', 'ContentTable');
     
		try {
			$db = $this->getDbo();
            
			$db->setQuery(
                          'UPDATE #__content AS a' .
                          ' SET a.featured = '.(int) $value.
                          ' WHERE a.id IN ('.implode(',', $pks).')'
                          );
			if (!$db->query()) {
				throw new Exception($db->getErrorMsg());
			}
            
			if ((int)$value == 0) {
				// Adjust the mapping table.
				// Clear the existing features settings.
				$db->setQuery(
                              'DELETE FROM #__content_frontpage' .
                              ' WHERE content_id IN ('.implode(',', $pks).')'
                              );
				if (!$db->query()) {
					throw new Exception($db->getErrorMsg());
				}
			} else {
				// first, we find out which of our new featured articles are already featured.
				$query = $db->getQuery(true);
				$query->select('f.content_id');
				$query->from('#__content_frontpage AS f');
				$query->where('content_id IN ('.implode(',', $pks).')');
				//echo $query;
				$db->setQuery($query);
                
				if (!is_array($old_featured = $db->loadResultArray())) {
					throw new Exception($db->getErrorMsg());
				}
                
				// we diff the arrays to get a list of the articles that are newly featured
				$new_featured = array_diff($pks, $old_featured);
                
				// Featuring.
				$tuples = array();
				foreach ($new_featured as $pk) {
					$tuples[] = '('.$pk.', 0)';
				}
				if (count($tuples)) {
					$db->setQuery(
                                  'INSERT INTO #__content_frontpage (`content_id`, `ordering`)' .
                                  ' VALUES '.implode(',', $tuples)
                                  );
					if (!$db->query()) {
						$this->setError($db->getErrorMsg());
						return false;
					}
				}
			}
            
		} catch (Exception $e) {
			$this->setError($e->getMessage());
			return false;
		}
        
		$table->reorder();
        
		$this->cleanCache();
        
		return true;
	}
	
		/**
	 * A protected method to get a set of ordering conditions.
	 *
	 * @param	object	A record object.
	 *
	 * @return	array	An array of conditions to add to add to ordering queries.
	 * @since	1.6
	 */
	protected function getReorderConditions($table)
	{
		$condition = array();
		$condition[] = 'catid = '.(int) $table->catid;
		return $condition;
	}

    

    
    /**
	 * Custom clean the cache of com_content and content modules
	 *
	 * @since	1.6
	 */
	protected function cleanCache()
	{
		parent::cleanCache('com_content');
		parent::cleanCache('mod_articles_archive');
		parent::cleanCache('mod_articles_categories');
		parent::cleanCache('mod_articles_category');
		parent::cleanCache('mod_articles_latest');
		parent::cleanCache('mod_articles_news');
		parent::cleanCache('mod_articles_popular');
	}
    
    function validate($form,$data){
        return $data;
    }
    
    
}
