<?php
/**
 * @package Joomla
 * @subpackage Abook
 * @copyright (C) 2010 Ugolotti Federica
 * @license GNU/GPL, see LICENSE.php
 * EventList is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License 2
 * as published by the Free Software Foundation.

 * Abook 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 Abook; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
defined( '_JEXEC' ) or die( 'Restricted access' );

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

class AbookModelBook extends JModelAdmin
{
	protected $text_prefix = 'COM_ABOOK';

	protected function canDelete($record)
        {
		if (!empty($record->id)) {
                        if ($record->published != -2) {
                                return ;
                        }
                        $user = JFactory::getUser();

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

	protected function canEditState($record)
        {
		$user = JFactory::getUser();

                // Check for existing article.
                if (!empty($record->id)) {
                        return $user->authorise('core.edit.state', 'com_abook.book.'.(int) $record->id);
                }
                // New article, so check against the category.
                else if (!empty($record->catid)) {
                        return $user->authorise('core.edit.state', 'com_abook.category.'.(int) $record->catid);
                }
                // Default to component settings if neither article nor category known.
                else {
                        return parent::canEditState($record);
                }
        }

	protected function prepareTable(&$table)
        {
		jimport('joomla.filter.output');
                $date = JFactory::getDate();
                $user = JFactory::getUser();
                $table->title            = htmlspecialchars_decode($table->title, ENT_QUOTES);
                $table->alias           = JApplication::stringURLSafe($table->alias);

                if (empty($table->alias)) {
                        $table->alias = JApplication::stringURLSafe($table->title);
                }

                if (empty($table->id)) {
                        // Set the values
                        //$table->created       = $date->toMySQL();

                        // Set ordering to the last item if not set
                        if (empty($table->ordering)) {
                                $db = JFactory::getDbo();
                                $db->setQuery('SELECT MAX(ordering) FROM #__abbook');
                                $max = $db->loadResult();

                                $table->ordering = $max+1;
                        }
                }
                else {
                        // Set the values
                        //$table->modified      = $date->toMySQL();
                        //$table->modified_by   = $user->get('id');
                }
        }

	public function getTable($type = 'Book', $prefix = 'AbookTable', $config = array())
        {
                return JTable::getInstance($type, $prefix, $config);
        }

	/*public function getItem($pk = null)
        {
                if ($item = parent::getItem($pk)) {
                        // Convert the params field to an array.
                        $registry = new JRegistry;
                        $registry->loadJSON($item->attribs);
                        $item->attribs = $registry->toArray();

                        // Convert the params field to an array.
                        $registry = new JRegistry;
                        $registry->loadJSON($item->metadata);
                        $item->metadata = $registry->toArray();
                }

                return $item;
        }*/

	public function getForm($data = array(), $loadData = true)
        {
                // Get the form.
                $form = $this->loadForm('com_abook.book', 'book', array('control' => 'jform', 'load_data' => $loadData));
                if (empty($form)) {
                        return false;
                }

                // Determine correct permissions to check.
                if ($this->getState('book.id')) {
                        // Existing record. Can only edit in selected categories.
                        $form->setFieldAttribute('catid', 'action', 'core.edit');
                }
                else {
                        // 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('ordering', 'disabled', 'true');
                        $form->setFieldAttribute('published', 'disabled', 'true');

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

                return $form;
        }

	protected function loadFormData()
        {
                // Check the session for previously entered form data.
                $data = JFactory::getApplication()->getUserState('com_abook.edit.book.data', array());

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

//bisogna fare l'override della funzione add nel controller e poi l'override della funzione save nel model, copiare da com_modules per l'inserimento nella tabella jos_modules_menu
	public function save($data)
        {
error_log(print_r($data, true), 3, '/var/log/php.log');
                if (parent::save($data)) {
			$this->storeauthor($this->getState('book.id'), $data['idauth']);//aggiunto
			$this->storetag($this->getState('book.id'), $data['idtag']);
                        return true;
                }
                //$cache = JFactory::getCache('com_abook');
                //$cache->clean();

                return false;
        }

	function storeauthor($id, $idauthors)
        {
                $booksauthorslist['id'] = 0;
                $booksauthorslist['idbook'] = $id;

                $row1 =& $this->getTable('bookauth2');
                if (!$row1->delete($id)) {
                        $this->setError($this->_db->getErrorMsg());
                        return false;
                }
                $row2 =& $this->getTable('bookauth');
                //uno per volta
                foreach ($idauthors as $auth) {
                        $booksauthorslist['idauth']=$auth;
                        if (!$row2->bind($booksauthorslist)) {
                                $this->setError($this->_db->getErrorMsg());
                                return false;
                        }

                        // Make sure the record is valid
                        if (!$row2->check()) {
                                $this->setError($this->_db->getErrorMsg());
                                return false;
                        }

                        // Store the web link table to the database
                        if (!$row2->store($booksauthorslist, $booksauthorslist['id'])) {
                                $this->setError( $row2->getErrorMsg() );
                                return false;
                        }
                }
        }

        function storetag($id, $idtags)
        {
                $bookstagslist['id'] = 0;
                $bookstagslist['idbook'] = $id;

                $row1 =& $this->getTable('booktag2');
                if (!$row1->delete($id)) {
                        $this->setError($this->_db->getErrorMsg());
                        return false;
                }
                $row2 =& $this->getTable('booktag');
                //uno per volta
                foreach ($idtags as $tag) {
                        $bookstagslist['idtag']=$tag;
                        if (!$row2->bind($bookstagslist)) {
                                $this->setError($this->_db->getErrorMsg());
                                return false;
                        }

                        // Make sure the record is valid
                        if (!$row2->check()) {
                                $this->setError($this->_db->getErrorMsg());
                                return false;
                        }

                        // Store the web link table to the database
                        if (!$row2->store($bookstagslist, $bookstagslist['id'])) {
                                $this->setError( $row2->getErrorMsg() );
                                return false;
                        }
                }
        }

	public function getAuthorslist() {
                if (empty( $this->_authorslist )) {
                        $query = ' SELECT * '
                        . ' FROM #__abauthor ORDER BY name'
                        ;
                }
                if (empty($this->_authorslist)) {
                        $this->_db->setQuery( $query );
                        $this->_authorslist = $this->_getList( $query );
                }

                return $this->_authorslist;
        }

        public function getBooksAuthorslist() {
                if (empty( $this->_booksauthorslist )) {
		//	$bookId       = (int) $this->form->getValue('id');
                        $query = ' SELECT * '
                        . ' FROM #__abbookauth JOIN #__abauthor ON #__abbookauth.idauth = #__abauthor.id'
                        . ' WHERE idbook = '.(int) $this->getItem()->id
                        . ' ORDER BY #__abauthor.name';
                }
                if (empty($this->_booksauthorslist)) {
                        $this->_db->setQuery( $query );
                        $this->_booksauthorslist = $this->_getList( $query );
                }

                return $this->_booksauthorslist;
        }
	
	public function getTagslist() {
                if (empty( $this->_tagslist )) {
                        $query = ' SELECT * '
                        . ' FROM #__abtag'
                        ;
                }
                if (empty($this->_tagslist)) {
                        $this->_db->setQuery( $query );
                        $this->_tagslist = $this->_getList( $query );
                }

                return $this->_tagslist;
        }

        public function getBooksTagslist() {
                if (empty( $this->_booksTagslist )) {
                //      $bookId       = (int) $this->form->getValue('id');
                        $query = ' SELECT * '
                        . ' FROM #__abbooktag JOIN #__abtag ON #__abbooktag.idtag = #__abtag.id'
                        . '  WHERE idbook = '.(int) $this->getItem()->id;
                }
                if (empty($this->_bookstagslist)) {
                        $this->_db->setQuery( $query );
                        $this->_bookstagslist = $this->_getList( $query );
                }

                return $this->_bookstagslist;
        }

        public function resethits($pks)
        {
                // Sanitize the ids.
                $pks = (array) $pks;
                JArrayHelper::toInteger($pks);

                if (empty($pks)) {
                        $this->setError(JText::_('JGLOBAL_NO_ITEM_SELECTED'));
                        return false;
                }

                $table = $this->getTable();

                try {
                        $db = $this->getDbo();

                        $db->setQuery(
                                'UPDATE #__abbook AS a' .
                                ' SET a.hits = 0'.
                                ' WHERE a.id IN ('.implode(',', $pks).')'
                        );
                        if (!$db->query()) {
                                throw new Exception($db->getErrorMsg());
                        }

                } catch (Exception $e) {
                        $this->setError($e->getMessage());
                        return false;
                }

                return true;
        }
}
