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


defined('_JEXEC') or die;

/**
 * Private Message model.
 *
 * @since  1.6
 */
class DJCatalog2ModelTemplate extends JModelAdmin
{
    /**
     * Message
     */
    protected $item;

    /**
     * Method to auto-populate the model state.
     *
     * This method should only be called once per instantiation and is designed
     * to be called on the first call to the getState() method unless the model
     * configuration flag to ignore the request is set.
     *
     * Note. Calling getState in this method will result in recursion.
     *
     * @return  void
     *
     * @since   1.6
     */
    protected function populateState()
    {
        parent::populateState();

        $input = JFactory::getApplication()->input;

        $id = (int)$input->getInt('id');
        $this->setState('template.id', $id);
    }

    /**
     * Check that recipient user is the one trying to delete and then call parent delete method
     *
     * @param array  &$pks An array of record primary keys.
     *
     * @return  boolean  True if successful, false if an error occurs.
     *
     * @since  3.1
     */
    public function delete(&$pks)
    {
        return parent::delete($pks);
    }

    /**
     * Returns a Table object, always creating it.
     *
     * @param type $type The table type to instantiate
     * @param string $prefix A prefix for the table class name. Optional.
     * @param array $config Configuration array for model. Optional.
     *
     * @return  JTable  A database object
     *
     * @since   1.6
     */
    public function getTable($type = 'Template', $prefix = 'DJCatalog2Table', $config = array())
    {
        return JTable::getInstance($type, $prefix, $config);
    }

    /**
     * Method to get a single record.
     *
     * @param integer $pk The id of the primary key.
     *
     * @return  mixed    Object on success, false on failure.
     *
     * @since   1.6
     */
    public function getItem($pk = null)
    {
        return parent::getItem($pk);
    }

    /**
     * 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  JForm   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_djmessages.template', 'template', array('control' => 'jform', 'load_data' => $loadData));

        if (empty($form)) {
            return false;
        }

        return $form;
    }

    /**
     * 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_djmessages.edit.template.data', array());

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

        $this->preprocessData('com_djmessages.template', $data);

        return $data;
    }

    protected function preprocessForm(\JForm $form, $data, $group = 'content')
    {
    	parent::preprocessForm($form, $data, $group);
    	
    	if (!empty($data)) {
    		if (is_object($data) && (!empty($data->id) || !empty($data->type))) {
    			$form->setFieldAttribute('type', 'readonly', 'true');
    		} else if (is_array($data) && (!empty($data['id']) || !empty($data['type']))) {
    			$form->setFieldAttribute('type', 'readonly', 'true');
    		}
    	}
    }

    public function save($data)
    {

        $this->preProcessAttachments($data);

        $dispatcher = Joomla\CMS\Factory::getApplication()->getDispatcher();
        $table = $this->getTable();
        $context = $this->option . '.' . $this->name;

        $key = $table->getKeyName();
        $pk = (!empty($data[$key])) ? $data[$key] : (int)$this->getState($this->getName() . '.id');
        $isNew = true;

        // Include the plugins for the save events.
        JPluginHelper::importPlugin($this->events_map['save']);

        // Allow an exception to be thrown.
        try {
            // Load the row if saving an existing record.
            if ($pk > 0) {
                $table->load($pk);
                $isNew = false;
            }

            // Bind the data.
            if (!$table->bind($data)) {
                $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;
            }

            // Trigger the before save event.
            $result = Joomla\CMS\Factory::getApplication()->triggerEvent($this->event_before_save, array($context, $table, $isNew, $data));

            if (in_array(false, $result, true)) {
                $this->setError($table->getError());

                return false;
            }
            $table->attachments = $this->processAttachments($data);

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

                return false;
            }

            // Clean the cache.
            $this->cleanCache();

            // Trigger the after save event.
            Joomla\CMS\Factory::getApplication()->triggerEvent($this->event_after_save, array($context, $table, $isNew, $data));
        } catch (Exception $e) {
            $this->setError($e->getMessage());

            return false;
        }

        if (isset($table->$key)) {
            $this->setState($this->getName() . '.id', $table->$key);
        }

        $this->setState($this->getName() . '.new', $isNew);

        return true;
    }

    protected function preProcessAttachments($data)
    {
        if (empty($data['id'])) return;

        $files = $beforeFiles = array();
        if (!empty($data['attachments']) && $data['attachments'] != '[]') {
            $files = json_decode($data['attachments']);
        }

        $db = JFactory::getDbo();
        $db->setQuery($db->getQuery(true)->select('*')->from('#__djc2_message_templates')->where('id=' . (int)$data['id']));
        $oldData = $db->loadObject();

        if (!empty($oldData->attachments) && $oldData->attachments != '[]') {
            $beforeFiles = json_decode($oldData->attachments);
        }

        if (is_array($beforeFiles) && count($beforeFiles) > 0) {
            foreach ($beforeFiles as $bk => $bfile) {
                $found = false;
                foreach ($files as $k => $file) {
                    if ($file->file_id == $bfile->file_id && $bfile->file_id > 0) {
                        $found = true;
                        break;
                    }
                }

                if (!$found) {
                    // image ($bfile) should be deleted in such case
                    if (!empty($bfile->fullpath) && JFile::exists(JPath::clean(JPATH_ROOT . '/' . $bfile->fullpath))) {
                        JFile::delete(JPath::clean(JPATH_ROOT . '/' . $bfile->fullpath));
                    }
                }
            }
        }

        return true;
    }

    protected function processAttachments($data)
    {
        $files = array();
        if (!empty($data['attachments']) && $data['attachments'] != '[]') {
            $files = json_decode($data['attachments']);
        }
        if (is_array($files) && count($files) > 0) {

            $destination = JPATH_ROOT . '/media/djcatalog2/messages/attachments';
            if (!JFolder::exists($destination)) {
                JFolder::create($destination, 0755);
            }

            foreach ($files as $k => $file) {
                if (!empty($file->file_id)) {
                    // skipping already uploaded Files
                    continue;
                }

                $ext = DJCatalog2FileHelper::getExtension($file->fullname);
                //$newName = $data['name']. '-' . $file->caption . '.' . $ext;
                $newName = $file->caption . '.' . $ext;
                $newName = \Joomla\String\StringHelper::strtolower(DJCatalog2FileHelper::createFileName($newName, $destination));
                $newPath = $destination . '/' . $newName;
                $source = JPath::clean(JPATH_ROOT . '/media/djcatalog2/tmp/' . $file->fullname);

                if (JFile::move($source, $newPath)) {
                    $files[$k]->file_id = md5($data['id'] . ':' . $file->caption . ':' . $file->fullname);
                    $files[$k]->fullname = $newName;
                    $files[$k]->url = 'media/djcatalog2/messages/attachments/' . $newName;
                    $files[$k]->size = filesize($newPath);
                    $files[$k]->path = 'media/djcatalog2/messages/attachments';
                    $files[$k]->fullpath = $files[$k]->path . '/' . $files[$k]->fullname;
                }

            }
        }

        $newFiles = json_encode($files);
        return $newFiles;
    }
}
