<?php
/** Copyright (C) 2015  miniOrange
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 this program.  If not, see <http://www.gnu.org/licenses/>
 * @package        miniOrange Import Export Users
 * @license        http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
 */
/**
 * This class contains all the utility functions
 **/
defined('_JEXEC') or die('Restricted access');

class MoImportExportUtility
{

    public static function getJoomlaCmsVersion()
    {
        $jVersion   = new JVersion;
        return($jVersion->getShortVersion());
    }

    public static function GetPluginVersion()
    {
        $db = JFactory::getDbo();
        $dbQuery = $db->getQuery(true)
            ->select('manifest_cache')
            ->from($db->quoteName('#__extensions'))
            ->where($db->quoteName('element') . " = " . $db->quote('com_miniorange_importexportusers'));
        $db->setQuery($dbQuery);
        $manifest = json_decode($db->loadResult());
        return($manifest->version);
    }

    public static function exportUserGroups()
    {
        $user_groups = MoImportExportUtility::readUserGroupsTable();
        self::parseDataAndDownloadCSV($user_groups);
    }
    public static function downloadCSVFile($user_data)
    {
        $reports = '';
        $user_count = count($user_data);

        if (is_array($user_data)) {
            foreach ($user_data[0] as $key => $value) {
                $reports .= $key . ',';
            }
            $reports .= 'group' . ',';
            $reports .= "\n";

            for ($i = 0; $i < $user_count; $i++) {
                if (is_array($user_data)) {
                    foreach ($user_data[$i] as $key => $value) {

                        // if param contains comma then replace it by semicolan otherwise it will print in new column for all comma seperated value
                        if($key == 'params'){
                            $value = str_replace(',', ';', $value);
                        }
                        $reports .= $value . ',';

                        // get list of assigned group id's for particular user by using user id of that user
                        $user_id = $user_data[$i]['id'];
                        jimport('joomla.access.access');
                        $groups = JAccess::getGroupsByUser($user_id, false);
                    }
                    // if user contains multiple groups
                    $group_value = '';
                    if(is_array($groups)){
                        $group_name = array();
                        foreach ($groups as $group){
                            $group_name[] = self::getGroupNameByID($group);
                        }
                        $group_value = implode(';', $group_name);
                        $reports .= $group_value . ',';
                    }
                    else{
                        $reports .= $group_value . ',';
                    }
                }
                $reports .= "\n";
            }

            header('Content-Type: application/csv');
            header('Content-Disposition: attachment; filename="reports.csv"');
            print_r($reports);
            exit();
        }

        header('Content-Type: application/csv');
        header('Content-Disposition: attachment; filename="reports.csv"');
        print_r($reports);
        exit();
    }

    public static function readUserGroupsTable()
    {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select('*');
        $query->from($db->quoteName('#__usergroups'));
        $db->setQuery($query);
        return $db->loadAssocList();
    }

    public static function parseDataAndDownloadCSV($user_groups)
    {
        $reports = '';
        $user_count = count($user_groups);

        if (is_array($user_groups)) {
            foreach ($user_groups[0] as $key => $value) {
                $reports .= $key . ',';
            }
            $reports .= "\n";

            for ($i_itr = 0; $i_itr < $user_count; $i_itr++) {
                if (is_array($user_groups)) {
                    foreach ($user_groups[$i_itr] as $key => $value) {

                        $reports .= $value . ',';

                        // This code will require later. Dont delete this
                        // get list of assigned group id's for particular user by using user id of that user
                        /*$i_user_id = $user_groups[$i_itr]['id'];
                        jimport('joomla.access.access');
                        $groups = JAccess::getGroupsByUser($i_user_id, false);*/
                    }
                }
                $reports .= "\n";
            }

            header('Content-Type: application/csv');
            header('Content-Disposition: attachment; filename="reports.csv"');
            print_r($reports);
            exit();
        }

        header('Content-Type: application/csv');
        header('Content-Disposition: attachment; filename="reports.csv"');
        print_r($reports);
        exit();
    }


    public static function getAllGroups()
    {
        $all_groups = MoImportExportUtility::loadGroups();

        $groups = array();
        foreach ($all_groups as $key => $value) {
            array_push($groups, $value['title']);
        }
        return $groups;
    }

    public static function is_customer_registered()
    {
        $result = self::getCustomerDetails();
        $email = $result['email'];
        $customerKey = $result['customer_key'];
        $status = $result['registration_status'];
        if ($email && $customerKey && is_numeric(trim($customerKey)) && $status == 'SUCCESS') {
            return 1;
        } else {
            return 0;
        }
    }

    public static function isBlank( $value )
    {
        if( ! isset( $value ) || empty( $value ) ) return TRUE;
        return FALSE;
    }

    public static function getCustomerDetails()
    {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select('*');
        $query->from($db->quoteName('#__miniorange_importexport_customer_details'));
        $query->where($db->quoteName('id') . " = 1");
        $db->setQuery($query);
        return $db->loadAssoc();
    }

    public static function check_empty_or_null($value)
    {
        if (!isset($value) || empty($value)) {
            return true;
        }
        return false;
    }

    public static function is_curl_installed()
    {
        if (in_array('curl', get_loaded_extensions())) {
            return 1;
        } else
            return 0;
    }

    public static function getCustomerToken()
    {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select('customer_token');
        $query->from($db->quoteName('#__miniorange_importexport_customer_details'));
        $query->where($db->quoteName('id') . " = 1");
        $db->setQuery($query);
        return $db->loadResult();
    }


    public static function is_extension_installed($name)
    {
        if (in_array($name, get_loaded_extensions())) {
            return true;
        } else {
            return false;
        }
    }

    public static function getHostname()
    {
        return 'https://login.xecurify.com';
    }

    public static function updateDBValue($table_name, $column_name, $export_format)
    {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $fields = array(
            $db->quoteName($column_name) . ' = ' . $db->quote($export_format),
        );

        $conditions = array(
            $db->quoteName('id') . ' = 1'
        );

        $query->update($db->quoteName($table_name))->set($fields)->where($conditions);
        $db->setQuery($query);
        $db->execute();
    }

    public static function readUsersTableData()
    {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select('*');
        $query->from($db->quoteName('#__users'));
        $db->setQuery($query);
        return $db->loadAssocList();
    }

    public static function loadGroups(){
        $db = JFactory::getDbo();
        $db->setQuery($db->getQuery(true)
            ->select('*')
            ->from("#__usergroups")
        );
        return  $db->loadAssocList();
    }

    public static function loadUserGroups($user_id){
        $db = JFactory::getDbo();
        $db->setQuery($db->getQuery(true)
            ->select('group_id')
            ->from("#__user_usergroup_map")
            ->where($db->quoteName('user_id'). ' = ' . $db->quote($user_id))
        );
        return  $db->loadAssocList();
    }

    public static function getGroupNameByID($group_id)
    {

        $db = JFactory::getDbo();
        $db->setQuery($db->getQuery(true)
            ->select('title')
            ->from("#__usergroups")
            ->where($db->quoteName('id'). ' = ' . $db->quote($group_id))
        );

        $result = $db->loadAssoc();
        return $result['title'];
    }
}
?>