<?php

/**
 * @license		GNU General Public License version 2 or later; see LICENSE.txt
 */
// No direct access.
defined('_JEXEC') or die;

// Import library dependencies
jimport('joomla.application.component.modellist');

class SPStgSrvModelLog extends JModelList {

    public function __construct($config = array()) {
        parent::__construct($config);
    }

    protected function populateState($ordering = null, $direction = null) {
        // Initialise variables.
        $app = JFactory::getApplication();
        $filters = JRequest::getVar('filters');
        if (empty($filters)) {
            $data = $app->getUserState($this->context . '.data');
            $filters = $data['filters'];
        } else {
            $app->setUserState($this->context . '.data', array('filters' => $filters));
        }

        $this->setState('filter.search', isset($filters['search']) ? $filters['search'] : '');
        parent::populateState('name', 'asc');
    }

    function delete($eid = array()) {
        // Initialise variables.
        $user = JFactory::getUser();
        if ($user->authorise('core.delete', 'com_spstgsrv')) {

            // Initialise variables.
            $failed = array();

            /*
             * Ensure eid is an array of extension ids in the form id => client_id
             * TODO: If it isn't an array do we want to set an error and fail?
             */
            if (!is_array($eid)) {
                $eid = array($eid => 0);
            }

            // Get a database connector
            $db = JFactory::getDBO();

            // Get an spstgsrv object for the extension type
            $row = $this->getTable();


            // Uninstall the chosen extensions
            foreach ($eid as $id) {
                $id = trim($id);

                if (!$row->delete($id)) {
                    return JError::raiseWarning(500, $row->getError());
                }
            }

            $msg = JText::sprintf('COM_SPSTGSRV_DELETE_SUCCESS', count($eid));
            $app = JFactory::getApplication();
            $app->enqueueMessage($msg);
            return true;
        } else {
            $result = false;
            JError::raiseWarning(403, JText::_('JERROR_CORE_DELETE_NOT_PERMITTED'));
        }
    }

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

    /**
     * Method to get the database query
     *
     * @return	JDatabaseQuery	The database query
     * @since	1.6
     */
    protected function getListQuery() {
        $query = JFactory::getDBO()->getQuery(true);
        $query->select('*');
        $query->from('#__spstgsrv_log');

        // Filter by search in id
        $search = $this->getState('filter.search');
        if (!empty($search)) {
            $query->where('package_name LIKE "%' . $search . '%"');
        }

        return $query;
    }

    /**
     * Method to get the row 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.
        $app = JFactory::getApplication();
        JForm::addFormPath(JPATH_COMPONENT . '/models/forms');
        JForm::addFieldPath(JPATH_COMPONENT . '/models/fields');
        $form = JForm::getInstance('com_spstgsrv.manage', 'log', array('load_data' => $loadData));

        // Check for an error.
        if ($form == false) {
            $this->setError($form->getMessage());
            return false;
        }
        // Check the session for previously entered form data.
        $data = $this->loadFormData();

        // Bind the form data if present.
        if (!empty($data)) {
            $form->bind($data);
        }

        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_spstgsrv.manage.data', array());

        return $data;
    }

    public function getTestConnection() {
        //save options
        $paramsStage = JComponentHelper::getParams('com_spstgsrv');
        $paramsTransfer = JComponentHelper::getParams('com_sptransfer');
        $paramsTransfer->set("new_ids", $paramsStage->get("new_ids", JText::_('COM_SPTRANSFER_NEW_IDS_OPTION_1')));
        $paramsTransfer->set("duplicate_alias", $paramsStage->get("duplicate_alias", '1'));

        //Check connection
        $source = new CYENDSource('com_sptransfer');
        $dbTestConnection = $source->testConnection();
        if (!$dbTestConnection) {
            //require_once(JPATH_ADMINISTRATOR.'/components/com_sptransfer/models/tables.php');
            //$modelSPTransfer = CYENDFactory::getModel('Database', 'SPTransferModel');

            $paramsTransfer->set("driver", $paramsStage->get("driver", 'mysqli'));            // Local Database driver name     
            $paramsTransfer->set("host", $paramsStage->get("host", 'localhost'));    // Database host name
            $paramsTransfer->set("source_user_name", $paramsStage->get("source_user_name", ''));       // User for database authentication
            $paramsTransfer->set("source_password", $paramsStage->get("source_password", ''));   // Password for database authentication
            $paramsTransfer->set("source_database_name", $paramsStage->get("source_database_name", ''));      // Database name
            $paramsTransfer->set("source_db_prefix", $source->modPrefix($paramsStage->get("source_db_prefix", '')));             // Database prefix (may be empty)

            $dbTestConnection = $source->testConnection();
        }

        // Save parameters
        $db = JFactory::getDBO();
        $query = $db->getQuery(true);

        // Build the query
        $query->update('#__extensions AS a');
        $query->set('a.params = ' . $db->quote((string) $paramsTransfer));
        $query->where('a.element = "com_sptransfer"');

        // Execute the query
        $db->setQuery($query);
        if (!$db->query()) {
            $this->setError($db->getErrorMsg());
            return false;
        }

        return $dbTestConnection;
    }

}
