<?php

if (!defined('ABSPATH'))
    die('Restricted Access');

class JSLEARNMANAGERCommonModel {

    function removeSpecialCharacter($string) {
        $string = strtolower($string);
        $string = strip_tags($string, "");
        //Strip any unwanted characters
        // $string = preg_replace("/[^a-z0-9_\s-]/", "", $string);

        $string = preg_replace("/[@!*&$;%'\\\\#\\/]+/", "", $string);

        //Clean multiple dashes or whitespaces
        $string = preg_replace("/[\s-]+/", " ", $string);
        //Convert whitespaces and underscore to dash
        $string = preg_replace("/[\s_]/", "-", $string);
        return $string;
    }

    function setDefaultForDefaultTable($id, $for) {
        if (is_numeric($id) == false) return false;
        $tablename = $this->getTableNameByFor($for);
        if($tablename == false) return false;
        if (self::checkCanMakeDefault($id, $tablename)) {
            $column = "isdefault";
            $db = new jslearnmanagerdb();
            $query = "UPDATE `#__js_learnmanager_" . $tablename . "` AS t SET t." . $column . " = 0 ";
            $db->setQuery($query);
            $db->query();
            $query = "UPDATE  `#__js_learnmanager_" . $tablename . "` AS t SET t." . $column . " = 1 WHERE id=" . $id;
            $db->setQuery($query);
            if (!$db->query())
                return JSLEARNMANAGER_SET_DEFAULT_ERROR;
            else
                return JSLEARNMANAGER_SET_DEFAULT;
        }else {
            return JSLEARNMANAGER_UNPUBLISH_DEFAULT_ERROR;
        }
    }

    function checkCanMakeDefault($id, $tablename) {
        if (!is_numeric($id)) return false;
        switch ($tablename) {
            default: $column = "status"; break;
        }
        $db = new jslearnmanagerdb();
        $query = "SELECT " . $column . " FROM `#__js_learnmanager_" . $tablename . "` WHERE id=" . $id;
        $db->setQuery($query);
        $res = $db->loadResult();
        if ($res == 1) return true;
        else return false;
    }

    function saveNewInJSLearnManager($data) {

        $data['user_role_id'] = JSLEARNMANAGERincluder::getJSModel('userrole')->getRoleIdbyName("Student");
        $issociallogin = apply_filters("jslm_sociallogin_check_social_loggedin",false);
        if ($issociallogin == true) {
            $data['socialid'] = sanitize_key($_SESSION['jslearnmanager-socialid']);
            $data['socialmedia'] = sanitize_key($_SESSION['jslearnmanager-socialmedia']);
            $data['firstname'] = sanitize_key($_SESSION['jslearnmanager-socialfirstname']);
            $data['lastname'] = sanitize_key($_SESSION['jslearnmanager-sociallastname']);
            $data['email'] = sanitize_email($_SESSION['jslearnmanager-socialemail']);
            $data['name'] = $data['firstname'].' '.$data['lastname'];
            $data['autogenerated'] = 1;
            $data['uid'] = 0;
            $data['issociallogin'] = true;
            $data['bio'] = '';
        } else {
            $currentuser = get_userdata(get_current_user_id());
            $data['socialid'] = '';
            $data['socialmedia'] = '';
            $data['firstname'] = $currentuser->user_nicename;
            $data['lastname'] = '';
            $data['email'] = $currentuser->user_email;
            $data['uid'] = $currentuser->ID;
            $data['name'] = $currentuser->user_nicename;
            $data['username'] = $currentuser->user_login;
            $data['bio'] = '';
            $data['user_role_id'] = $data['roleid'];
        }
        $row = JSLEARNMANAGERincluder::getJSTable('users');
        $data = filter_var_array($data, FILTER_SANITIZE_STRING);
        $data['status'] = 1; // all user autoapprove when registered as JS learnmanager users
        $data['created_at'] = date('Y-m-d H:i:s');
        if (!$row->bind($data)) {
            return JSLEARNMANAGER_SAVE_ERROR;
        }
        if (!$row->check()) {
            return JSLEARNMANAGER_SAVE_ERROR;
        }
        if (!$row->store()) {
            return JSLEARNMANAGER_SAVE_ERROR;
        }
        $data['user_id'] = $row->id;
        // $data['role'] = JSLEARNMANAGERincluder::getObjectClass('user')->getjslearnmanagerusertypebywpid($row->id);
        // if($data['role']->role == 'Student'){
            $studentid = JSLEARNMANAGERincluder::getJSModel('student')->storeStudentProfile($data);
        // }elseif($data['role']->role == 'Instructor'){
        //     $instructorid = JSLEARNMANAGERincluder::getJSModel('instructor')->storeInstructorProfile($data);
        // }
        return JSLEARNMANAGER_SAVED;
    }

    function getDefaultValue($table) {
        $db = new jslearnmanagerdb();
        switch ($table) {
            case "category":
            case "payment_plan":
            case "subcategories":
                $query = "SELECT id FROM `#__js_learnmanager_" . $table . "` WHERE isdefault=1";

                $db->setQuery($query);
                $default_id = $db->loadResult();
                if ($default_id)
                    return $default_id;
                else {
                    $query = "SELECT min(id) AS id FROM `#__js_learnmanager_" . $table . "`";

                    $db->setQuery($query);
                    $min_id = $db->loadResult();
                    return $min_id;
                }
            case "currencies":
                $query = "SELECT id FROM `#__js_learnmanager_" . $table . "` WHERE `default`=1";

                $db->setQuery($query);
                $default_id = $db->loadResult();
                if ($default_id)
                    return $default_id;
                else {
                    $query = "SELECT min(id) AS id FROM `#__js_learnmanager_" . $table . "`";

                    $db->setQuery($query);
                    $min_id = $db->loadResult();
                    return $min_id;
                }
                break;
        }
    }

    function setOrderingUpForDefaultTable($field_id, $for) {
        if (is_numeric($field_id) == false)
            return false;
        $db = new jslearnmanagerdb();
        $tablename = $this->getTableNameByFor($for);
        if($tablename == false) return false;
        $query = "UPDATE `#__js_learnmanager_" . $tablename . "` AS f1, `#__js_learnmanager_" . $tablename . "` AS f2
                    SET f1.ordering = f1.ordering + 1
                    WHERE f1.ordering = f2.ordering - 1
                    AND f2.id = " . $field_id;
        $db->setQuery($query);
        if (false == $db->query()) {
            return JSLEARNMANAGER_ORDER_UP_ERROR;
        }
        $query = " UPDATE `#__js_learnmanager_" . $tablename . "`
                    SET ordering = ordering - 1
                    WHERE id = " . $field_id;
        $db->setQuery($query);
        if (false == $db->query()) {
            return JSLEARNMANAGER_ORDER_UP_ERROR;
        }
        return JSLEARNMANAGER_ORDER_UP;
    }

    function setOrderingDownForDefaultTable($field_id, $for) {
        if (is_numeric($field_id) == false)
            return false;
        $db = new jslearnmanagerdb();
        $tablename = $this->getTableNameByFor($for);
        if($tablename == false) return false;
        $query = "UPDATE `#__js_learnmanager_" . $tablename . "` AS f1, `#__js_learnmanager_" . $tablename . "` AS f2
                    SET f1.ordering = f1.ordering - 1
                    WHERE f1.ordering = f2.ordering + 1
                    AND f2.id = " . $field_id;
        $db->setQuery($query);
        if (false == $db->query()) {
            return JSLEARNMANAGER_ORDER_DOWN_ERROR;
        }
        $query = " UPDATE `#__js_learnmanager_" . $tablename . "`
                    SET ordering = ordering + 1
                    WHERE id = " . $field_id;
        $db->setQuery($query);
        if (false == $db->query()) {
            return JSLEARNMANAGER_ORDER_DOWN_ERROR;
        }
        return JSLEARNMANAGER_ORDER_DOWN;
    }

    private function getTableNameByFor($for){
        $tablename = false;
        switch ($for) {
            case 'category':$tablename = 'category';break;
            case 'paymentplan':$tablename = 'paymentplan';break;
            case 'currency':$tablename = 'currencies';break;

        }
        return $tablename;
    }

    function getYesNo() {
        $yesno = array();
        $yesno[] = (object) array('id' => '1', 'text' => __('Yes', 'learn-manager'));
        $yesno[] = (object) array('id' => '0', 'text' => __('No', 'learn-manager'));
        return $yesno;
    }

    function getStatus() {
        $status = array();
        $status[] = (object) array('id' => '1', 'text' => __('Published', 'learn-manager'));
        $status[] = (object) array('id' => '0', 'text' => __('Unpublished', 'learn-manager'));
        return $status;
    }

    function getAppearenceStatus() {
        $status = array();
        $status[] = (object) array('id' => '1', 'text' => __('One Time Appear', 'learn-manager'));
        $status[] = (object) array('id' => '0', 'text' => __('More than one time', 'learn-manager'));
        return $status;
    }

    function getQueStatus() {
        $status = array();
        $status[] = (object) array('id' => '1', 'text' => __('Approved', 'learn-manager'));
        $status[] = (object) array('id' => '0', 'text' => __('Rejected', 'learn-manager'));
        return $status;
    }

    function getListingStatus() {
        $status = array();
        $status[] = (object) array('id' => '1', 'text' => __('Approved', 'learn-manager'));
        $status[] = (object) array('id' => '-1', 'text' => __('Rejected', 'learn-manager'));
        return $status;
    }

    function getShowAllCombo() {
        $showall = array();
        $showall[] = (object) array('id' => '1', 'text' => __('Show all', 'learn-manager'));
        if(in_array('featuredcourse', jslearnmanager::$_active_addons)){
            $showall[] = (object) array('id' => '2', 'text' => __('Show featured', 'learn-manager'));
        }
        return $showall;
    }

    function getAccessTypeCombo() {
        $access = array();
        $access[] = (object) array('id' => '1', 'text' => __('Free', 'learn-manager'));
        $access[] = (object) array('id' => '2', 'text' => __('Paid', 'learn-manager'));
        return $access;
    }

    function getCourseLevel() {
        $level = array();
        $level[] = (object) array('id' => 'Beginner', 'text' => __('Beginner', 'learn-manager'));
        $level[] = (object) array('id' => 'Intermediate', 'text' => __('Intermediate', 'learn-manager'));
        $level[] = (object) array('id' => 'Expert', 'text' => __('Expert', 'learn-manager'));
        return $level;
    }

    function checkImageFileExtensions($file_name, $file_tmp, $image_extension_allow) {
        $allow_image_extension = explode(',', $image_extension_allow);
        if ($file_name != "" AND $file_tmp != "") {
            $ext = $this->getExtension($file_name);
            $ext = strtolower($ext);
            if (in_array($ext, $allow_image_extension))
                return true;
            else
                return false;
        }
    }

    function checkDocumentFileExtensions($file_name, $file_tmp, $document_extension_allow) {
        $allow_document_extension = explode(',', $document_extension_allow);
        if ($file_name != '' AND $file_tmp != "") {
            $ext = $this->getExtension($file_name);
            $ext = strtolower($ext);
            if (in_array($ext, $allow_document_extension))
                return true;
            else
                return false;
        }
    }

    function makeDir($path) {
        if (!file_exists($path)) { // create directory
            mkdir($path, 0755);
            $ourFileName = $path . '/index.html';
            $ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
            fclose($ourFileHandle);
        }
    }

    function parseID($id){
        if(is_numeric($id)) return $id;
        $id = explode('-', $id);
        $id = $id[count($id) -1];
        return $id;
    }

    function getStatusforCombo($title) {
        $status = array();
        if ($title)
            $status[] = array('value' => '' , 'text' => $title);
            $status[] = array('value' => 1, 'text' => __('Published'));
            $status[] = array('value' => -1, 'text' => __('Unpublished'));
        return $status;
    }

    function getUidByObjectId($actionfor, $id) {
        if (!is_numeric($id))
            return false;
        $db = new jslearnmanagerdb();
        switch ($actionfor) {
            case'course':
                $table = '#__js_learnmanager_course';
                break;
        }
        if(!isset($table))
            return false;
        $query = "SELECT instructor_id FROM `". $table ."` WHERE id =" . $id;
        $db->setQuery($query);
        $result = $db->loadResult();

        return $result;
    }

    function jsMakeRedirectURL($module, $layout,$id=null,$redirectlayout=null){
        if(empty($module) AND empty($layout))
            return null;

        $finalurl = '';
        // login links
        if(is_numeric($id)){
            $jsthisurl = jslearnmanager::makeUrl(array('jslmsmod'=>$module, 'jslmslay'=>$layout, 'jslearnmanagerid'=>$id, 'layout'=>base64_encode($redirectlayout)));
        }else{
            $jsthisurl = jslearnmanager::makeUrl(array('jslmsmod'=>$module, 'jslmslay'=>$layout));
        }
        $jsthisurl = base64_encode($jsthisurl);
        $finalurl = jslearnmanager::makeUrl(array('jslmsmod'=>'jslearnmanager', 'jslmslay'=>'login', 'jslearnmanagerredirecturl'=>$jsthisurl));
        return $finalurl;
    }

    function getMessagekey(){
        $key = 'Common';if(is_admin()){$key = 'admin_'.$key;}return $key;
    }

    function jslm_set_html_content_type() {
        return 'text/html';
    }

    function sendContactUsEmail($name, $email, $message, $recevieremail){
        $headers = 'From: ' . $name . ' <' . $email . '>' . "\r\n";
        add_filter('wp_mail_content_type', array($this,'jslm_set_html_content_type'));
        $body = preg_replace('/\r?\n|\r/', '<br/>', $message);
        $body = str_replace(array("\r\n", "\r", "\n"), "<br/>", $body);
        $body = nl2br($body);
        $subject = esc_html__('Contact us email received','learn-manager');
        wp_mail($recevieremail, $subject, $body, $headers, '');
        return;
    }

}
?>
