<?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()) {
                if (empty($config['filter_fields']))
		{
			$config['filter_fields'] = array(
				'id', 'a.id',
				'package_name', 'a.package_name',
				'package_path', 'a.package_path',
				'message', 'a.message',
				'ip', 'a.ip',
				'result', 'a.result',
				'created', 'a.created',
				'created_by', 'a.created_by',
				'version', 'a.version',
			);

		}
                
                parent::__construct($config);
        }
        
        /**
	 * Method to get a store id based on model configuration state.
	 *
	 * This is necessary because the model is used by the component and
	 * different modules that might need different sets of data or different
	 * ordering requirements.
	 *
	 * @param   string  $id  A prefix for the store id.
	 *
	 * @return  string  A store id.
	 *
	 * @since   1.6
	 */
	protected function getStoreId($id = '')
	{
		// Compile the store id.
		$id .= ':' . $this->getState('filter.search');

		return parent::getStoreId($id);
	}

        public 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)) {
                                        JFactory::getApplication()->enqueueMessage($row->getError(), 'warning');
                                        return FALSE;
                                }
                        }

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

        public function mass_delete() {
                // Initialise variables.
                $user = JFactory::getUser();
                if ($user->authorise('core.delete', 'com_spstgsrv')) {
                        // Get a database connector
                        $db = JFactory::getDBO();
                        $db->truncateTable('#__spstgsrv_log');

                        return true;
                } else {
                        JFactory::getApplication()->enqueueMessage(JText::_('JERROR_CORE_DELETE_NOT_PERMITTED'), 'warning');
                }
        }

        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('a.id, a.package_name, a.package_path, a.message, a.ip, a.result, a.created, a.created_by, a.version');
                $query->from('#__spstgsrv_log as a');

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

                // Add the list ordering clause.
                $orderCol = $this->state->get('list.ordering', 'a.created');
                $orderDirn = $this->state->get('list.direction', 'DESC');
                $query->order($query->escape($orderCol) . ' ' . $query->escape($orderDirn));
               
                return $query;
        }

        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;
        }

        public function export() {
                //get data
                $db = JFactory::getDbo();
                $query = $db->getQuery(true);
                $query->select('*')->from('#__spstgsrv_log');
                $db->setQuery($query);
                $logs = $db->loadAssocList();

                //create file
                $file = JPATH_COMPONENT_ADMINISTRATOR . '/backups/log.csv';
                $fp = fopen($file, 'w');
                fputcsv($fp, array_keys($logs[0]));
                foreach ($logs as $log) {
                        fputcsv($fp, $log);
                }
                fclose($fp);

                //download file
                $dowload = new CYENDDownload();
                $dowload->forceDownload($file);

                return true;
        }

}
