<?php

/****************************
 * File :  global.php
 * Author : Cygnusa
 * @2018
 *
 *    All Global Rest Api files
 *
 ***************************/

class globalfunc
{
    // `userid`, `smpin`, `emp_code`, `password`, `fname`, `lname`, `emailid`, `mobileno`, `role`, `dealer_code`, `address_1`, `address_2`, `address_3`, `valid_token`, `validate_time`, `profile_photo`, `dob`, `doj`, `country`, `auth_token`, `otp`, `otp_expiry`, `language`, `is_married`, `marriage_date`, `mpin`, `status`, `last_password_change`, `is_first_login`, `is_profile_updated`, `is_deleted`, `inactivated_on`, `created_on`, `modified_on`
    private static $user_fields = "userid, `smpin`, `emp_code`, `password`, `fname`, `lname`, `emailid`, `mobileno`, `role`, `dealer_code`, `address_1`, `address_2`, `address_3`,`profile_photo`, `dob`, `doj`, `country`, `language`, `is_married`, `marriage_date`, `mpin`, `status`,`last_password_change`,`is_first_login`,`is_profile_updated`,validate_time";

    /* /////////////////////////////////// DEVELOPER ERROR /////////////////////////////////// */
    public static function callErrorMsg($parent, $data)
    {
        if (!isset($data)) {
            $parent->response(array('response' => 'failed', 'message' => 'PHP UNDEFINED ERROR'), 500);
        }

        if (!isset($data['message']) || $data['message'] == '' || $data['message'] == null) {
            $parent->response(array('response' => 'failed', 'message' => 'PHP UNDEFINED ERROR'), 500);
        }

        $parent->response(array('response' => 'failed', 'message' => $data['message']), 500);
    }
    /* ///////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////////// CHECK METHOD TYPE /////////////////////////////////// */
    public static function checkMethodType($parent, $method_array)
    {

        if (is_array($method_array)) {
            $method_array = array_map('strtoupper', $method_array);
            if (!in_array($parent->get_request_method(), $method_array)) {
                $parent->response(array('response' => 'failed'), 406);
            }

        } else {
            self::callErrorMsg($parent, array('message' => 'GLOBAL(checkMethodType):REQUIRED DATA'));
        }
    }
    /* ///////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// CHECK PARAMETER COUNT EXIT ////////////////////////////// */
    public static function checkParamCount($parent, $param_count)
    {

        if (count($parent->params) != $param_count) {
            $parent->response(array('response' => 'failed'), 404);
        }

        if ($param_count != 0) {
            if (!(trim($parent->params[($param_count - 1)]) != '')) {
                $parent->response(array('response' => 'failed'), 404);
            }

        }
    }
    /* ///////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// CHECK ANY KEY ////////////////////////////// */
    public static function checkAnyKey($parent, $element_arr)
    {
        if (!is_array($element_arr)) {
            self::callErrorMsg($parent, array('message' => 'GLOBAL(checkAnyKey):REQUIRED DATA'));
        }

        try {
            $temp = 0;
            //FIELD KEY VALIDATE
            $field_arr = array_keys($element_arr);
            foreach ($field_arr as $single) {
                if (isset($parent->_request[$single])) {$temp = 1;
                    break;}
            }
            if ($temp == 0) {
                $parent->response(array('response' => 'failed', 'message' => 'MISSING FIELDS - ' . strtoupper($single)), 406);
            }

            //FIELD VAKUE TYPE VALIDATE
            foreach ($element_arr as $key => $single) {
                if (isset($parent->_request[$key])) {
                    if (($parent->_request[$key] == '' || $parent->_request[$key] == null) && !is_array($parent->_request[$key]) && !is_object($parent->_request[$key])) {
                        $parent->response(array('response' => 'failed', 'message' => $key . ' FIELD VALUE REQUIRED'), 406);
                    }

                    (!self::validRequestKey($parent->_request[$key], $single)) ? $parent->response(array('response' => 'failed', 'message' => 'INVALID DATA TYPE. `' . $key . '` Required as ' . $single), 406) : '';
                }
            }
        } catch (Exception $e) {
            $parent->response(array('response' => 'failed', 'message' => $e->getMessage()), 406);
        }
    }
    /* ///////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// MANDATORY ////////////////////////////// */
    public static function mandatoryKey($parent, $element_arr)
    {
        if (!is_array($element_arr)) {
            self::callErrorMsg($parent, array('message' => 'GLOBAL(checkAnyKey):REQUIRED DATA'));
        }

        try {
            //FIELD KEY VALIDATE
            $field_arr = array_keys($element_arr);
            foreach ($field_arr as $single) {
                if (!isset($parent->_request[$single])) {
                    $parent->response(array('response' => 'failed', 'message' => 'MISSING FIELDS - ' . strtoupper($single)), 406);
                }

            }
            //FIELD VAKUE TYPE VALIDATE
            foreach ($element_arr as $key => $single) {
                if (($parent->_request[$key] == '' || $parent->_request[$key] == null) && !is_array($parent->_request[$key]) && !is_object($parent->_request[$key])) {
                    $parent->response(array('response' => 'failed', 'message' => strtoupper($key) . ' FIELD VALUE REQUIRED'), 406);
                }

                (!self::validRequestKey($parent->_request[$key], $single)) ? $parent->response(array('response' => 'failed', 'message' => 'INVALID DATA TYPE. `' . $key . '` Required as ' . $single), 406) : '';
            }
        } catch (Exception $e) {
            $parent->response(array('response' => 'failed', 'message' => $e->getMessage()), 406);
        }
    }
    /* ///////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// get ip ////////////////////////////// */
    public static function getIp($parent, $data = array())
    {
        $ip = $_SERVER['REMOTE_ADDR'];
        if ($ip) {
            if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
                $ip = $_SERVER['HTTP_CLIENT_IP'];
            } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
            }
            return $ip;
        }
        // There might not be any data
        return false;
    }

    /* ///////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// CHECK REQUEST PARAMETER CHECK ////////////////////////////// */
    public static function checkElementexist($parent, $elementarr)
    {
        if (!is_array($elementarr)) {
            self::callErrorMsg($parent, array('message' => 'GLOBAL(checkElementexist):REQUIRED DATA'));
        }

        if (count($parent->_request) != count($elementarr)) {
            $parent->response(array('response' => 'failed'), 406);
        }

        foreach ($elementarr as $single) {
            if (!isset($parent->_request[$single])) {
                $parent->response(array('response' => 'failed'), 406);
            }

        }
    }
    /* ///////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// CHECK PARAMETER COUNT EXIT ////////////////////////////// */
    public static function checkRequestKey($parent, $element_arr)
    {
        if (!is_array($element_arr)) {
            self::callErrorMsg($parent, array('message' => 'GLOBAL(checkElementexist):REQUIRED DATA'));
        }

        try {
            $field_arr = array_keys($element_arr);
            if (count($parent->_request) != count($field_arr)) {
                $parent->response(array('response' => 'failed', 'message' => 'MISSING KEYS'), 406);
            }

            foreach ($field_arr as $single) {
                if (!isset($parent->_request[$single])) {
                    $parent->response(array('response' => 'failed', 'message' => 'MISSING FIELDS'), 406);
                }

            }
            //KEY TYPE VALIDATE

            foreach ($element_arr as $key => $single) {
                (!self::validRequestKey($parent->_request[$key], $single)) ? $parent->response(array('response' => 'failed', 'message' => 'INVALID KEY TYPE'), 406) : '';
            }
        } catch (Exception $e) {
            $parent->response(array('response' => 'failed', 'message' => $e->getMessage()), 406);
        }
    }
    /* ///////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// CHECK FILE ////////////////////////////// */
    public static function validateFile($parent, $obj)
    {
        try {

            if (is_object($obj)) {
                (!(isset($obj->filekey) && isset($obj->size) && isset($obj->type) && is_array($obj->type))) ? $parent->response(array('response' => 'failed', 'message' => 'CODE ERROR'), 406) : null;
                (!(isset($_FILES[$obj->filekey]) && ($_FILES[$obj->filekey]["error"] == 0))) ? $parent->response(array('response' => 'failed', 'message' => 'FILE NOT FOUND'), 406) : null;
                $maxsize = $obj->size * 1024 * 1024;
                ($maxsize < $_FILES[$obj->filekey]['size']) ? $parent->response(array('response' => 'failed', 'message' => 'INVALID FILE SIZE'), 406) : null;
                $fileParts = pathinfo($_FILES[$obj->filekey]['name']);

                $fileext_arr = explode('?', $fileParts['extension']);
                (!@in_array(strtolower($fileext_arr[0]), $obj->type)) ? $parent->response(array('response' => 'failed', 'message' => 'You can upload only ', @implode(', ', $obj->type) . " file type."), 406) : null;

            } else {
                self::callErrorMsg($parent, array('message' => 'GLOBAL(validateFile):REQUIRED DATA'));
            }
        } catch (Exception $e) {
            $parent->response(array('response' => 'failed', 'message' => $e->getMessage()), 406);
        }
    }
    /* ///////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// EMAIL VALIDATION ////////////////////////////// */
    public static function isValidDomain($email)
    {

        list($user, $url) = explode('@', $email);
        $validation = false;
        /*Parse URL*/
        $urlparts = parse_url(filter_var($url, FILTER_SANITIZE_URL));
        /*Check host exist else path assign to host*/
        if (!isset($urlparts['host'])) {
            $urlparts['host'] = $urlparts['path'];
        }

        if ($urlparts['host'] != '') {
            /*Add scheme if not found*/
            if (!isset($urlparts['scheme'])) {
                $urlparts['scheme'] = 'http';
            }

            /*Validation*/
            if (checkdnsrr($urlparts['host'], 'A') && in_array($urlparts['scheme'], array('http', 'https')) && ip2long($urlparts['host']) === false) {
                $urlparts['host'] = preg_replace('/^www\./', '', $urlparts['host']);
                $url = $urlparts['scheme'] . '://' . $urlparts['host'] . "/";

                if (filter_var($url, FILTER_VALIDATE_URL) !== false && @get_headers($url)) {
                    $validation = true;
                }
            }
        }
        return $validation;
    }

    public static function isValidEmail($email)
    {
        return filter_var($email, FILTER_VALIDATE_EMAIL)
        && preg_match('/@.+\./', $email);
    }

    public static function emailValidation($parent, $email_address)
    {
        if (!(self::isValidEmail($email_address))) {
            $parent->response(array('response' => 'failed', 'message' => 'INVALID EMAIL'), 406);
        }
        if (!(self::isValidDomain($email_address))) {
            $parent->response(array('response' => 'failed', 'message' => 'INVALID EMAIL DOMAIN'), 406);
        }
    }
    /* ///////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// MOBILE VALIDATION ////////////////////////////// */
    public static function mobileValidation($parent, $mobileno)
    {
        if (!(preg_match('/^[0-9]{10}+$/', $mobileno))) {
            $parent->response(array('response' => 'failed', 'message' => 'INVALID MOBILE'), 406);
        }
    }
    /* ///////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// PASSWORD VALIDATION ////////////////////////////// */
    public static function validPassword($parent, $passstring)
    {
        $containsLetter = preg_match('/[a-zA-Z]/', $passstring);
        $containsDigit = preg_match('/\d/', $passstring);
        //$containsSpecial = preg_match('/[^a-zA-Z\d]/',$passstring);
        if (!(strlen($passstring) >= 6 && strlen($passstring) <= 100 && $containsLetter && $containsDigit))
        //if(!(strlen($passstring)>=6 && strlen($passstring)<=10 && $containsLetter && $containsDigit && $containsSpecial ))
        {
            return false;
        }
        return true;
    }
    /* ///////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// SET DB RECORD SKIP VALUE ////////////////////////////// */
    public static function setRecordSkip($parent, $data)
    {
        if (strstr($data, "record=")) {
            $qry_params = explode('record=', $data);
            $sepraters = explode("&", $qry_params[1]);
            if (isset($sepraters[0])) {
                if ($sepraters[0] == null || $sepraters[0] == '') {
                    $parent->response(array('response' => 'failed'), 404);
                }

                $query_values = explode(",", $sepraters[0]);
                $query_value = (isset($query_values[1])) ? $query_values[0] : 0;
                return $query_value;
            } else {
                return 0;
            }
        } else {
            return 0;
            //$parent->response(array('response'=>'failed'),404);
        }
    }

    /* ////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// SET DB RECORD LIMIT VALUE ////////////////////////////// */
    public static function setRecordLimit($parent, $data)
    {
        if (strstr($data, "record=")) {
            $qry_params = explode('record=', $data);
            $sepraters = explode("&", $qry_params[1]);

            if (isset($sepraters[0])) {
                //echo $sepraters[0];
                $query_values = explode(",", $sepraters[0]);

                (!(isset($query_values[0]) && isset($query_values[1]))) ? $parent->response(array('response' => 'failed', 'invalid limit call'), 403) : null;

                //((int)$query_values[0]>(int)$query_values[1])?$parent->response(array('response'=>'failed','invalid limit call'), 403):NULL;
                /*
                switch (count($query_values)){
                case 1:
                $query_value=(int)$query_values[0];
                break;
                case 2:
                $query_value=(int)$query_values[1];
                break;
                default:
                $query_value='0,'.RECORD_LIMIT;
                break;
                }*/
                $query_value = (int) $query_values[0] . "," . (int) $query_values[1];

                return $query_value;
            } else {
                $parent->current_page = 0;
                return '0,' . RECORD_LIMIT;
            }
        } else {
            $parent->current_page = 0;
            return '0,' . RECORD_LIMIT;
        }
    }

    /* ////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// SET PAGE LIMIT VALUE ////////////////////////////// */
    public static function setPageLimit($parent, $data)
    {
        if (strstr($data, "page=")) {
            $qry_params = explode('page=', $data);
            $sepraters = explode("&", $qry_params[1]);

            if (isset($sepraters[0])) {
                $page_value = intval($sepraters[0]);
                $limit_data = explode('limit=', $data);
                if (strstr($data, "limit=") && isset($limit_data[0])) {
                    $sepraters = explode("&", $limit_data[1]);
                    $limit_arr = explode("&", $limit_data[1]);
                    $limit_value = intval($limit_arr[0]);
                } else {
                    $limit_value = RECORD_LIMIT;
                }

                (!(isset($page_value))) ? $parent->response(array('response' => 'failed', 'Invalid Pagination call'), 406) : null;

                $page_start_value = (int) $page_value * (int) $limit_value;

                $parent->current_page = $page_value;
                $parent->current_limit = $limit_value;
                $query_value = $page_start_value . "," . $limit_value;

                return $query_value;
            } else {
                $parent->current_page = 0;
                $parent->current_limit = RECORD_LIMIT;
                return '0,' . RECORD_LIMIT;
            }
        } else {
            $parent->current_page = 0;
            $parent->current_limit = RECORD_LIMIT;
            return '0,' . RECORD_LIMIT;
        }
    }

    /* ////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// GET DB RECORD FILTER VALUE ////////////////////////////// */
    public static function getFilterValues($parent, $data)
    {
        if (strpos($data, "filter=") !== false) {
            $filter_params = explode("filter=", $data);
            if (!isset($filter_params[1]) || $filter_params[1] == null || $filter_params[1] == '') {
                $parent->response(array('response' => 'failed'), 404);
            }

            $filter_param_items = explode(",", array_values(explode('&', $filter_params[1]))[0]);
            $filter_array = array();
            //print_r($filter_param_items);
            foreach ($filter_param_items as $item) {
                $itemval = explode(":", $item);
                if (isset($itemval[1])) {
                    $itemkey = $itemval[0];
                    $filter_array[$itemkey] = $itemval[1];
                } else {
                    $filter_array[] = $itemval[0];
                }
                //$filter_array[]=(isset($itemval[1]))?array($itemval[0]=>$itemval[1]):array($itemval[0]);
            }
            return $filter_array;
        } else {
            return null;
        }
    }
    /* ////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// GET DB RECORD BETWEEN VALUE ////////////////////////////// */
    public static function getBetweenFilter($parent, $data)
    {
        if (!isset($data) || is_null($data)) {
            return null;
        }

        if (strpos($data, "between=")) {
            $between_params = explode("between=", $data);
            if (!isset($between_params[1]) || $between_params[1] == null || $between_params[1] == '') {
                $parent->response(array('response' => 'failed'), 400);
            }

            $between_param_items = explode(",", array_values(explode('&', $between_params[1]))[0]);

            $between_array = array();
            //$more_params=array();
            foreach ($between_param_items as $item) {
                if ($item != '') {
                    $itemval = explode(":", $item);
                    if (isset($itemval[1])) {
                        $itemvals = explode("|", $itemval[1]);
                        $between_array[] = array($itemval[0] => $itemvals);
                    }
                }
            }
            return (count($between_array) > 0) ? $between_array : null;
        } else {
            return null;
        }
    }

    /* ////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// GET DB RECORD ORDER VALUE ////////////////////////////// */
    public static function getOrderValues($parent, $data)
    {
        $order_array = array();
        if (strpos($data, "orderby=")) {
            $order_params = explode("orderby=", $data);
            if (!isset($order_params[1]) || $order_params[1] == null || $order_params[1] == '') {
                $parent->response(array('response' => 'failed'), 404);
            }

            $order_param_items = explode(",", array_values(explode('&', $order_params[1]))[0]);
            foreach ($order_param_items as $item) {
                $order_array[] = $item;
            }

            return (count($order_array) > 0) ? $order_array : null;
        } else {
            return null;
        }
    }
    /* ////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// TOKEN GENERATION ////////////////////////////// */
    public static function generateToken($parent, $token_type = '', $length = 128)
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }

        //ACCESS TOKEN ALREADY EXIST
        switch (strtolower($token_type)) {
            case "access":
                $query_checkuser = $parent->getQueryCount("SELECT userid FROM " . TABLE_USER . "  WHERE auth_token='" . $randomString . "' LIMIT 1");
                return ($query_checkuser == 1) ? self::generateToken($parent, $token_type, $length) : $randomString;
                break;
            case "forgot":
                $query_checkuser = $parent->getQueryCount("SELECT userid FROM " . TABLE_USER . "  WHERE valid_token='" . $randomString . "' LIMIT 1");
                return ($query_checkuser == 1) ? self::generateToken($parent, $token_type, $length) : $randomString;
                break;
            case "enquiry":
                $query_checkuser = $parent->getQueryCount("SELECT id FROM " . DMS_ENQUIRY_MASTER . "  WHERE share_token='" . $randomString . "' LIMIT 1");
                return ($query_checkuser == 1) ? self::generateToken($parent, $token_type, $length) : $randomString;
                break;
            //case "forgot":
            default:
                return $randomString;
                break;
        }
    }
    /* ///////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// EXPIRY TIME ////////////////////////////// */
    public static function generateExpiryTime($parent, $min = 15)
    {
        $sec = $min * 60;
        //echo $sec.'--';

        $expiry_time = date('Y-m-d H:i:s', strtotime('+' . $sec . ' seconds', strtotime(NOW)));
        //echo $expiry_time;die();
        return $expiry_time;
    }
    /* ///////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// EXPIRY TIME ////////////////////////////// */
    public static function generateExpiryDate($parent, $days = 10)
    {

        $expiry_time = date('Y-m-d H:i:s', strtotime('-' . $days . ' day', strtotime(NOW)));
        //echo $expiry_time;die();
        return $expiry_time;
    }
    /* ///////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// UPDATE USER TOKEN ////////////////////////////// */
    /*
    public static function updateUserToken($parent,$data) {
    if(IS_MULTI_LOGIN==1){
    $parent->executeQuery("INSERT INTO ".TABLE_USER_DEVICES."(`userid`, `devicetype`, `token`, `android_id`, `model`, `manufacture`, `version`, `client_ip`, `created_on`, `modified_on`) VALUES ('".$data['user_id']."','".$data['device_name']."','".$data['device_id']."','".$parent->device_type."','".$data['requester']->ip."','".$data['requester']->city."','".$data['requester']->country."','".$data['access_token']."','".NOW."','".NOW."')");
    return true;
    }else{
    $query_user_devices=$parent->selectQuery(TABLE_USER_DEVICES,"id","user_id='".$data['user_id']."' AND device_type='".$parent->device_type."'","1");
    if($query_user_devices['nr']<= 0){
    $parent->executeQuery("INSERT INTO ".TABLE_USER_DEVICES."( `user_id`,`device_name`,`device_id`,`device_type`,`client_ip`,`city`,`country`,`access_token`, `created_on`, `modified_on`) VALUES ('".$data['user_id']."','".$data['device_name']."','".$data['device_id']."','".$parent->device_type."','".$data['requester']->ip."','".$data['requester']->city."','".$data['requester']->country."','".$data['access_token']."','".NOW."','".NOW."')");
    return true;
    }else{
    $parent->executeQuery(" UPDATE ".TABLE_USER_DEVICES." SET device_name='".$data['device_name']."', device_id ='".$data['device_id']."', client_ip='".$data['requester']->ip."', city ='".$data['requester']->city."', country ='".$data['requester']->city."', access_token ='".$data['access_token']."', modified_on='".NOW."' WHERE user_id='".$data['user_id']."' AND device_type='".$parent->device_type."'");
    return true;
    }
    }
    return false;
    }
     */
    /* ///////////////////////////////////////////////////////////////////////////////////// */

    /* //////////////////////////////////// AUTHROZATION  /////////////////////////////////
    /* /////////////////////////////// GET AUTHROZATION TOKEN////////////////////////////// */
    public static function getAuthrozation($parent)
    {
        $headers = getallheaders();
        $auth = '';
        if (isset($headers['Authorization']) || isset($headers['authorization'])) {
            $auth = (isset($headers['Authorization'])) ? 'Authorization' : 'authorization';
        } else {
            $parent->response(array('response' => 'failed', 'message' => 'Authrozation required'), 401);
        }
        $request_token = $headers[$auth];
        if (is_null($request_token)) {
            $parent->response(array('response' => 'failed', 'message' => 'Authrozation value required'), 401);
        }

        $access_token = explode("Bearer ", $request_token);
        if (!(isset($access_token[1])) || $access_token[1] == '') {
            $parent->response(array('response' => 'failed', 'message' => 'Authrozation value format not matched'), 401);
        }

        return $access_token[1];
    }
    /* ///////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// LOCK ACCESS  ////////////////////////////// */
    public static function secureAccess($parent, $access_token)
    {
        //CHECK LOCK IS ENABLE
        if (LOCK_ACCESS_ENABLE == 1) {
            $sec = LOCK_ACCESS_MINUTES * 60;
            $expiry_time = date('Y-m-d H:i:s', strtotime('-' . $sec . ' seconds', strtotime(NOW)));

            $lock_qry_str = "SELECT * FROM " . TABLE_LOCK_ACCESS . " WHERE is_deleted='0' AND lock_count>='" . LOCK_ACCESS_COUNT . "' AND auth_token='" . $access_token . "' AND modified_on>='" . $expiry_time . "' LIMIT 1 ";
            $lock_value = $parent->getQueryValue($lock_qry_str);
            if (count($lock_value) > 0) {
                $parent->response(array('response' => 'failed', 'message' => 'Sorry Your Access locked.'), 401);
            }
        }
    }
    /* ///////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// OTP AUTHROZATION CHECKING ////////////////////////////// */
    public static function checkAuthrozation($parent, $data)
    {
        /* data is a stdClass values */
        /* type : otp/user */
        if (!isset($data)) {
            self::callErrorMsg($parent, array('message' => 'GLOBAL(checkAuthrozation):REQUIRED DATA'));
        }

        if (!isset($data['type'])) {
            self::callErrorMsg($parent, array('message' => 'GLOBAL(checkAuthrozation):REQUIRED type VALUE'));
        }

        $access_token = escape_str(self::getAuthrozation($parent));
        self::secureAccess($parent, $access_token);
        switch ($data['type']) {
            /*
            case "otp":
            $user_qry_str="SELECT user_id FROM ".TABLE_USER." WHERE otpnumber='".$access_token."' AND is_deleted!='1' AND status='1' LIMIT 1";
            $user_value=$parent->getQueryValue($user_qry_str);
            if(count($user_value)<=0) $parent->response(array('response'=>'failed', 'message'=>'INVALID OTP'), 401);

            $parent->current_user_data=$user_value[0];
            return $user_value[0];
            break;
             */
            case "user":
                $user_qry_str = "SELECT * FROM " . TABLE_USER . " WHERE is_deleted='0' AND status='1' AND  auth_token='" . $access_token . "' AND auth_token!='' LIMIT 1";
                $user_value = $parent->getQueryValue($user_qry_str);
                //if(count($user_value)<=0) $parent->response(array('response'=>'failed', 'message'=>'INVALID USER ACCESS TOKEN'), 401);
                if (count($user_value) <= 0) {
                    self::insertLockLog($parent, $access_token);
                    $parent->response(array('response' => 'failed', 'message' => 'Session expired or You have already logged-in another device'), 401);
                }
                $parent->current_user_data = $user_value[0];
                $parent->current_user_id = $user_value[0]->userid;
                $parent->current_user_role = $user_value[0]->role;

                $parent->current_smpin = $user_value[0]->smpin;
                $parent->current_emp_code = $user_value[0]->emp_code;

                unset($user_value[0]->userid);
                return $user_value[0];
                break;

            case "set_password":
                $user_qry_str = "SELECT " . self::$user_fields . " FROM " . TABLE_USER . " WHERE valid_token='" . $access_token . "'  AND auth_token!='' AND is_deleted='0' AND status='1'  LIMIT 1";
                $user_value = $parent->getQueryValue($user_qry_str);
                if (count($user_value) <= 0) {
                    self::insertLockLog($parent, $access_token);
                    $parent->response(array('response' => 'failed', 'message' => 'Invalid Authentication token'), 401);
                }
                if ($user_value[0]->validate_time == "0000-00-00 00:00:00") {
                    $parent->response(array('response' => 'failed', 'message' => 'Authentication token expired, Please initiate a new password reset request again.'), 406);
                }

                if (strtotime($user_value[0]->validate_time) < strtotime(NOW)) {
                    $parent->response(array('response' => 'failed', 'message' => 'Authentication token expired, Please initiate a new password reset request again.'), 406);
                }

                $parent->current_user_data = $user_value[0];
                $parent->current_user_id = $user_value[0]->userid;
                $parent->current_user_role = $user_value[0]->role;
                $parent->current_smpin = $user_value[0]->smpin;
                $parent->current_emp_code = $user_value[0]->emp_code;

                unset($user_value[0]->userid);
                return $user_value[0];
                break;

            case "explore":
                $user_qry_str = "SELECT * FROM " . TABLE_USER . " WHERE is_deleted='0' AND status='1' AND  auth_token='" . $access_token . "'  AND auth_token!='' LIMIT 1";
                $user_value = $parent->getQueryValue($user_qry_str);

                if (count($user_value) > 0) {
                    $parent->current_user_data = $user_value[0];
                    $parent->current_user_id = $user_value[0]->userid;
                    $parent->current_user_role = $user_value[0]->role;
                    $parent->current_smpin = $user_value[0]->smpin;
                    $parent->current_emp_code = $user_value[0]->emp_code;
                    unset($user_value[0]->userid);
                    return $user_value[0];
                } else {
                    if ($access_token == MODE_ONE_TOKEN) {
                        $parent->exp_model_type = 0;
                    } else if ($access_token == MODE_TWO_TOKEN) {
                        $parent->exp_model_type = 1;
                    } else {
                        self::insertLockLog($parent, $access_token);
                        $parent->response(array('response' => 'failed', 'message' => 'Invalid Authentication token'), 401);
                    }

                    $parent->current_user_data = array();
                    $parent->current_user_role = 0;
                    $parent->current_user_id = 'guest';
                    return null;
                }

                break;

            default:
                self::callErrorMsg($parent, array('message' => 'GLOBAL(checkAuthrozation):TYPE VALUE WAS NOT ACCEPTABLE'));
                break;
        }
    }
    /* ///////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// TOKEN GENERATION ////////////////////////////// */
    public static function generateOTP($length = 4)
    {
        $characters = '0123456789';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        //$randomString='1234';
        //EDIT FOR DEV
        if (IS_LIVE_SERVER == '0') {
            $randomString = '1234';
        }
//        else{ //SMS CHENGE
        //            $randomString='1234';
        //        }
        return $randomString;
    }
    /* ///////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// GET SITE SETTING ////////////////////////////// */
    public static function getSiteSetting($parent, $data)
    {
        if (!isset($data)) {
            self::callErrorMsg($parent, array('message' => 'GLOBAL(getSiteSetting):REQUIRED DATA'));
        }

        if (!isset($data['setting']) || $data['setting'] == '' || $data['setting'] == null) {
            self::callErrorMsg($parent, array('message' => 'GLOBAL(getSiteSetting):REQUIRED setting VALUE'));
        }

        $user_qry_str = "SELECT * FROM " . TABLE_SITE_SETTING . " WHERE setting_type='" . $data['setting'] . "' AND is_active='1'";
        $user_value = $parent->getQueryValue($user_qry_str);

        $out_data = new stdClass();
        foreach ($user_value as $values) {
            $key_name = $values->setting_title;
            $out_data->$key_name = $values->value;
        }

        return $out_data;

    }
    /* ///////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// PASSWORD POLICY ////////////////////////////// */
    public static function passwordPolicy($parent, $data)
    {
        if (!isset($data)) {
            self::callErrorMsg($parent, array('message' => 'GLOBAL(passwordPolicy):REQUIRED DATA'));
        }

        if (!isset($data['password']) || $data['password'] == '' || $data['password'] == null) {
            self::callErrorMsg($parent, array('message' => 'GLOBAL(passwordPolicy):REQUIRED password VALUE'));
        }

        $policy_setting = self::getSiteSetting($parent, array('setting' => 'PASSWORD_POLICY'));

        if (strtolower($policy_setting->POLICY_REQUIRED) == "true") {
            //print_r($policy_setting);
            if (!is_numeric($policy_setting->MINIMUM_LENGTH)) {
                self::callErrorMsg($parent, array('message' => 'GLOBAL(passwordPolicy):ERROR IN PASSWORD MINIMUM_LENGTH SETTING VALUE.'));
            }

            if (!is_numeric($policy_setting->MAXIMUM_LENGTH)) {
                self::callErrorMsg($parent, array('message' => 'GLOBAL(passwordPolicy):ERROR IN PASSWORD MAXIMUM_LENGTH SETTING VALUE.'));
            }

            if (!(strlen($data['password']) >= $policy_setting->MINIMUM_LENGTH && strlen($data['password']) <= $policy_setting->MAXIMUM_LENGTH)) {
                $parent->response(array('response' => 'failed', 'message' => 'PASSWORD LENTH WAS NOT MATCHED IN THE PASSWORD POLICY'), 406);
            }
            if (!is_numeric($policy_setting->POLICY_TYPE)) {
                self::callErrorMsg($parent, array('message' => 'GLOBAL(passwordPolicy):ERROR IN PASSWORD POLICY_TYPE SETTING VALUE.'));
            }

            switch ($policy_setting->POLICY_TYPE) {
                case 1:
                    if (!is_numeric($data['password'])) {
                        $parent->response(array('response' => 'failed', 'message' => 'Password value was not matched in the password policy'), 406);
                    }

                    break;

                case 2:
                    if (!ctype_alpha($data['password'])) {
                        $parent->response(array('response' => 'failed', 'message' => 'Password value was not matched in the password policy'), 406);
                    }

                    break;

                case 3:
                    if (!preg_match("/(?=.*[A-Z])(?=.*[a-z])[A-Za-z]+$/", $data['password'])) {
                        $parent->response(array('response' => 'failed', 'message' => 'Password value was not matched in the password policy'), 406);
                    }

                    break;

                case 4:
                    if (!(preg_match('/[A-Za-z]/', $data['password']) && preg_match('/[0-9]/', $data['password']))) {
                        $parent->response(array('response' => 'failed', 'message' => 'Password value was not matched in the password policy'), 406);
                    }

                    break;

                case 5:
                    if (!(preg_match('/[0-9]/', $data['password']) && preg_match('/[A-Z]/', $data['password']) && preg_match('/[a-z]/', $data['password']))) {
                        $parent->response(array('response' => 'failed', 'message' => 'Password value was not matched in the password policy'), 406);
                    }

                    break;
                case 6:
                    if (!preg_match("/^(?=.*\d)(?=.*[@#!.-])(?=.*[A-Z])(?=.*[a-z])[0-9A-Za-z!-@#.\/]{1,}$/", ($data['password']))) {
                        $parent->response(array('response' => 'failed', 'message' => 'Password value was not matched in the password policy'), 406);
                    }

                    break;
                case 7:

                    break;
                default:
                    self::callErrorMsg($parent, array('message' => 'GLOBAL(passwordPolicy):ERROR IN PASSWORD POLICY_TYPE VALUE SHOULD 1 TO 6 ONLY.'));
                    break;

            }

            /*
        if(is_numeric($policy_setting->PREVIOUS_COUNT) && 0<=(int)$policy_setting->PREVIOUS_COUNT){
        if($policy_setting->PREVIOUS_COUNT!=0){
        if(!isset($data['user_id']) || $data['user_id']=='' || $data['user_id']==NULL) self::callErrorMsg($parent,array('message'=>'GLOBAL(passwordPolicy):REQUIRED user_id VALUE.'));
        $query_previous_passwords=$parent->selectQuery("(SELECT *  FROM ".TABLE_USER_PASSWORD_LOGS." WHERE user_id='".$data['user_id']."' AND is_reseted=0 ORDER BY id DESC LIMIT ".((int)$policy_setting->PREVIOUS_COUNT+1).") as a ","a.user_id","a.password='".md5($data['password'])."' ");
        if($query_previous_passwords['nr']!=0) $parent->response(array('response'=>'failed','message'=>'Your new password value is match with last '.$policy_setting->PREVIOUS_COUNT.' password(s)'),406);
        }
        }else{

        self::callErrorMsg($parent,array('message'=>'GLOBAL(passwordPolicy):ERROR IN PASSWORD PREVIOUS_COUNT SETTING VALUE.'));
        }
         */
        }
    }
    /* ///////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// UPDATE PASSWORD ////////////////////////////// */
    public static function updatePassword($parent, $data)
    {

        if (!isset($data)) {
            self::callErrorMsg($parent, array('message' => 'GLOBAL(updatePassword):REQUIRED DATA'));
        }

        if (!isset($data['password']) || $data['password'] == '' || $data['password'] == null) {
            self::callErrorMsg($parent, array('message' => 'GLOBAL(updatePassword):REQUIRED password VALUE'));
        }

        if (!isset($data['userid']) || $data['userid'] == '' || $data['userid'] == null) {
            self::callErrorMsg($parent, array('message' => 'GLOBAL(updatePassword):REQUIRED userid VALUE'));
        }

        $parent->executeQuery(" UPDATE " . TABLE_USER . " SET password='" . md5($data['password']) . "',last_password_change='" . NOW . "',modified_on='" . NOW . "' WHERE userid='" . $data['userid'] . "'");

        return true;

    }
    /* ///////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// SEND OTP ////////////////////////////// */
    public static function sendOtp($parent, $type, $otp_value, $message, $send_to)
    {

    }
    /* ///////////////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// INSERT LOCK ACCESS ////////////////////////////// */
    public static function insertLockLog($parent, $access_token)
    {
        $lock_qry_str = "SELECT * FROM " . TABLE_LOCK_ACCESS . " WHERE is_deleted='0' AND auth_token='" . $access_token . "' LIMIT 1";
        $lock_value = $parent->getQueryValue($lock_qry_str);
        //LOCK ACCESS
        if (count($lock_value) > 0) {
            $client_ip = self::getIp($parent);
            $parent->executeQuery("UPDATE " . TABLE_LOCK_ACCESS . " SET `ip`='" . $client_ip . "',page='" . escape_str($parent->api_url) . "' ,lock_count=lock_count+1, `modified_on`='" . NOW . "' WHERE id='" . $lock_value[0]->id . "'");
        } else {
            $client_ip = self::getIp($parent);
            $parent->executeQuery("INSERT INTO " . TABLE_LOCK_ACCESS . " ( `auth_token`, `ip`, `lock_count`,page, `is_deleted`, `created_on`, `modified_on`) VALUES ('" . $access_token . "','" . $client_ip . "',1,'" . escape_str($parent->api_url) . "', 0, '" . NOW . "', '" . NOW . "')");
        }
    }
    /* ////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// INSERT LOG ////////////////////////////// */
    public static function insertUserLog($parent, $activity, $module_id = 0)
    {
        if ($parent->current_user_id != null) {
            $client_ip = self::getIp($parent);

            $parent->executeQuery("INSERT INTO " . TABLE_USER_LOG . " ( `userid`,`device_type`, `module`,module_id, `ip`, `created_on`) VALUES ('" . $parent->current_user_id . "','" . $parent->device_type . "','" . $activity . "','" . $module_id . "','" . $client_ip . "','" . NOW . "')");
        }
    }
    /* ////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// MASK MOBILE ////////////////////////////// */
    public static function maskMobileno($number)
    {
        $masked = str_pad(substr($number, -4), strlen($number), 'X', STR_PAD_LEFT);
        //$masked = substr($number,0,1).str_pad(substr($number, -4), (strlen($number)-1), 'X', STR_PAD_LEFT);
        return $masked;
    }
    /* ////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// IMAGE CROP ////////////////////////////// */
    public static function setImageCrop($parent, $file_path, $cord, $targ_w = 200, $targ_h = 300)
    {
        //$targ_w = 200;
        //$targ_h = 300;
        $jpeg_quality = 80;
        $img_r = self::imagecreatefromfile($parent, $file_path);
        $dst_r = ImageCreateTrueColor($targ_w, $targ_h);
        $cords = explode("|", $cord);
        //imagecopyresampled($dst_r,$img_r,0,0,(int)$cords[0],(int)$cords[1],$targ_w,$targ_h,(int)$cords[2],(int)$cords[3]);
        imagecopyresampled($dst_r, $img_r, 0, 0, (int) $cords[0], (int) $cords[1], $targ_w, $targ_h, (int) $cords[2], (int) $cords[3]);
        self::imagesavefile($parent, $dst_r, $file_path, $jpeg_quality);
        //shell_exec("sudo chmod -R 777 ".$file_path);
        chmod($file_path, 0777);
    }
    /* ////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// CREATE FILE ////////////////////////////// */
    public static function imagecreatefromfile($parent, $filename)
    {
        (!file_exists($filename)) ? $parent->response(array('response' => 'failed'), 403) : null;
        switch (strtolower(pathinfo($filename, PATHINFO_EXTENSION))) {
            case 'jpeg':
            case 'jpg':
                return imagecreatefromjpeg($filename);
                break;
            case 'png':
                return imagecreatefrompng($filename);
                break;
            case 'gif':
                return imagecreatefromgif($filename);
                break;
            default:
                $parent->response(array('response' => 'failed', 'message' => 'FILE IS NOT VALID JPG, PNG OR GIF IMAGE.'), 403);
                break;
        }
    }
    /* ////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// SAVE CROP FILE ////////////////////////////// */
    public static function imagesavefile($parent, $dst_r, $file_path, $jpeg_quality)
    {
        (!file_exists($file_path)) ? $parent->response(array('response' => 'failed', 'message' => 'FILE PATH NOT FOUND.'), 403) : null;

        switch (strtolower(pathinfo($file_path, PATHINFO_EXTENSION))) {
            case 'jpeg':
            case 'jpg':
                imagejpeg($dst_r, $file_path, $jpeg_quality);
                break;
            case 'png':
                imagepng($dst_r, $file_path);
                break;
            default:
                $parent->response(array('response' => 'failed', 'message' => 'FILE NOT VALID JPG, PNG OR GIF IMAGE.'), 403);
                break;
        }
    }
    /* ////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// UPLOAD FILE ////////////////////////////// */
    public static function uploadFile($parent, $obj)
    {
        $filekey = $obj->filekey;
        $path = $obj->path;
        $fileprefix = (isset($obj->fileprefix)) ? $obj->fileprefix : 'file';
        if (is_object($obj) && isset($_FILES[$obj->filekey])) {
            $tempFile = $_FILES[$obj->filekey]['tmp_name'];
            $fileParts = pathinfo($_FILES[$obj->filekey]['name']);

            $fileext_arr = explode('?', $fileParts['extension']);
            $fileExtension = strtolower($fileext_arr[0]);

            $file_prehead = (IS_LIVE_SERVER != '1') ? "_development" : "";
            $fileName = (isset($obj->filename)) ? $obj->filename . $file_prehead . '.' . $fileExtension : $fileprefix . '_' . date('YmdHis') . uniqid() . $file_prehead . '.' . $fileExtension;
            $targetFile = $path . $fileName;
            @move_uploaded_file($tempFile, $targetFile);
            //shell_exec("sudo chmod -R 777 ".$targetFile);
            chmod($targetFile, 0777);

            if (isset($obj->cord) && $obj->cord != null) {
                (isset($obj->width) && $obj->width != null && isset($obj->height) && $obj->height != null) ? self::setImageCrop($parent, $targetFile, $obj->cord, $obj->width, $obj->height) : self::setImageCrop($parent, $targetFile, $obj->cord);
            }

            return $fileName;
        }
    }
    /* ////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// USER OTP VALIDATE ////////////////////////////// */
    /*
    public static function validateUserOtp($parent,$otpval)
    {
    if($parent->current_user_id)
    {
    $query_checkvin=$parent->getQueryValue("SELECT * FROM ".TABLE_USER."  WHERE  user_id='".$parent->current_user_id."' LIMIT 1");
    if(count($query_checkvin)>0)
    {
    if($query_checkvin[0]->otp!=$otpval) $parent->response(array('response'=>'failed','message'=>'NOT VALID OTP'),200);
    if(!(strtotime(NOW)<strtotime($query_checkvin[0]->otp_time))) $parent->response(array('response'=>'failed','message'=>'OTP EXPIRED'),200);
    }else{
    $parent->response(array('response'=>'failed'), 401);
    }
    }else{
    $parent->response(array('response'=>'failed'), 401);
    }
    return null;
    }
     */
    /* ////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// GET EXCEL NUMBER ////////////////////////////// */
    public static function getNameFromNumber($num)
    {
        $numeric = $num % 26;
        $letter = chr(65 + $numeric);
        $num2 = intval($num / 26);
        if ($num2 > 0) {
            return self::getNameFromNumber($num2 - 1) . $letter;
        } else {
            return $letter;
        }
    }
    /* ////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// GET INDIAN MOBILE ////////////////////////////// */
    public static function getIndianMobile($mnum)
    {
        return substr($mnum, -10);
    }
    /* ////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// CHECK DATE GREATER ////////////////////////////// */
    public static function checkDateGreater($fdate, $sdate)
    {
        $reval = true;
        if ($fdate && $sdate && $fdate != '0000-00-00 00:00:00' && $sdate != '0000-00-00 00:00:00' && $fdate != '0000-00-00' && $sdate != '0000-00-00') {
            $reval = (strtotime($fdate) > strtotime($sdate)) ? true : false;
        }
        return $reval;
    }
    /* ////////////////////////////////////////////////////////////////////////// */

    /* /////////////////////////////// REMOVE DIRECTORY ////////////////////////////// */
    // rrmdir('../../uploads/zip/');
    public static function rrmdir($dir, $check = false)
    {
        if (is_dir($dir)) {
            $objects = scandir($dir);
            foreach ($objects as $object) {
                if ($object != "." && $object != "..") {
                    if (filetype($dir . "/" . $object) == "dir") {
                        self::rrmdir($dir . "/" . $object, true);
                    } else {
                        unlink($dir . "/" . $object);
                    }

                }
            }
            reset($objects);
            ($check) ? rmdir($dir) : null;
        }
    }
    /* ////////////////////////////////////////////////////////////////////////// */

    /* ////////////////////////////////// ANDRIOD FCM FUNCTION ///////////////////////////// */
    private static function sendGoogleCloudMessage($messagearr, $reg_id)
    {
        //print_r($messagearr);
        //print_r($reg_id);

        $title = $messagearr['title'];
        $message = $messagearr['message'];
        $messagearr['body'] = $messagearr['message'];

        $fields = array(

            'registration_ids' => $reg_id,
            'priority' => "high",
            'notification' => array("title" => $title, "body" => $message, "sound" => "default"),
            'data' => $messagearr,
        );

        $headers = array(
            GOOGLE_FCM_URL,
            'Content-Type: application/json',
            'Authorization: key=' . GOOGLE_API_KEY,
        );

        // $ch = curl_init();
        // curl_setopt($ch, CURLOPT_URL, GOOGLE_FCM_URL);
        // curl_setopt($ch, CURLOPT_POST, true);
        // curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        // $result = curl_exec($ch);
        // //echo  $result;
        // curl_close($ch);
        echo $result="";
    }
    /* ////////////////////////////////////////////////////////////////////////// */

    /* ////////////////////////////////// IOS GCM FUNCTION ///////////////////////////// */
    private static function sendFCMIOSCloudMessage($messagearr, $reg_id)
    {
        //print_r($messagearr);
        //print_r($reg_id);

        $title = $messagearr['title'];
        $message = $messagearr['message'];

        $fields = array(
            //'to'=> $reg_id,
            "content_available" => true,
            'registration_ids' => $reg_id,
            'priority' => "high",
            'aps' => array("content-available" => 1),
            'notification' => $messagearr,
            //'data'                        => $messagearr,
            'data' => array('published' => NOW),
            'notId' => rand(1000, 9999),
        );

        $headers = array(
            GOOGLE_FCM_URL,
            'Content-Type: application/json',
            'Authorization: key=' . GOOGLE_API_KEY,
        );
        //echo "<br>";

        // $ch = curl_init();
        // curl_setopt($ch, CURLOPT_URL, GOOGLE_FCM_URL);
        // curl_setopt($ch, CURLOPT_POST, true);
        // curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        // curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
        // $result = curl_exec($ch);
        // //print_r($result);
        // curl_close($ch);
        echo $result="";
    }
    /* ////////////////////////////////////////////////////////////////////////// */

    /* ////////////////////////////////////// SEND NOTIFICATION ///////////////////////////////// */
    public static function sendUserNotification($message, $usertokenarr)
    {

        //STRUCTURE $usertokenarr =array('android'=>$arr,'ios'=>$arr);
        // $android_ids = (isset($usertokenarr['android'])) ? $usertokenarr['android'] : array();
        // $ios_ids = (isset($usertokenarr['ios'])) ? $usertokenarr['ios'] : array();

        // if (count($android_ids) > 0) {
        //     $ids_arr = array_chunk($android_ids, 1000);
        //     if (count($ids_arr) > 0) {
        //         foreach ($ids_arr as $groupids) {
        //             self::sendGoogleCloudMessage($message, $groupids);
        //         }
        //     }
        // }

        // if (count($ios_ids) > 0) {
        //     $ids_arr = array_chunk($ios_ids, 1000);
        //     if (count($ids_arr) > 0) {
        //         foreach ($ids_arr as $groupids) {
        //             self::sendFCMIOSCloudMessage($message, $groupids);
        //             //self::sendIoCloudMessage($message, $groupids);

        //         }
        //     }
        // }
    }
    /* ////////////////////////////////////////////////////////////////////////// */

    /* ////////////////////////////////////// SLUG ///////////////////////////////// */
    public static function generate_slug($var)
    {
        if ($var) {
            $var = @str_replace(' ', '-', trim($var));
            $var = @strtolower($var);
            $slugname = @preg_replace('/[^A-Za-z0-9\-]/', '', $var);
            $slugname = @preg_replace('/-+/', '-', $slugname);
        }
        return $slugname;
    }
    /* ////////////////////////////////////////////////////////////////////////// */

    //KEY VALIDATION
    public static function validRequestKey($input, $type)
    {
        //TYPES : integer,string,double,array,object,date|Y-m-d
        switch ($type) {
            //VALID CONDITIONS
            case 'integer':return (ctype_digit(strval($input)));
                break;
            case 'string':return is_string($input);
                break;
            case 'number':return is_numeric($input);
                break;
            case 'double':return ((int) $input != $input && is_numeric($input));
                break;
            case 'array':return is_array($input);
                break;
            case 'object':return is_object($input);
                break;
            case 'date|Y-m-d':return self::isValidDateTimeString($input, 'Y-m-d', 'Asia/Kolkata');
                break;
            case 'date|Y-m-d H:i:s':return self::isValidDateTimeString($input, 'Y-m-d H:i:s', 'Asia/Kolkata');
                break;
            case 'date|d-m-Y':return self::isValidDateTimeString($input, 'd-m-Y', 'Asia/Kolkata');
                break;
            default:return false;
                break;
        }
    }
    //DATE VALIDATE
    public static function isValidDateTimeString($str_dt, $str_dateformat, $str_timezone)
    {
        $date = DateTime::createFromFormat($str_dateformat, $str_dt, new DateTimeZone($str_timezone));
        return $date && $date->format($str_dateformat) == $str_dt;
    }
    //MESSAGE RETURN
    public static function getMessage($parent, $lang, $module)
    {

        if (file_exists("../../language/" . $lang . "/common.php")) {
            include_once "../../language/" . $lang . "/common.php";
            if (!isset($string[$module])) {
                $parent->response(array('response' => 'failed', 'message' => 'MODULE LANGUAGE FILE NOT FOUND'), 500);
            }

            return $string[$module];
        } else {
            $parent->response(array('response' => 'failed', 'message' => 'LANGUAGE FILE NOT FOUND'), 500);
            exit;
        }
    }

    //SEND MAIL
    public static function sendMail($parent, $obj)
    {
        // if (IS_LIVE_SERVER != '1') {
        //     $obj['to'] = 'lokesh.b@cygnusa.in';

        //     if (isset($obj['cc'])) {
        //         if (is_string($obj['cc'])) {
        //             $cc = $obj['cc'];
        //             $obj['cc'] = array();
        //             $obj['cc'][] = $cc;
        //         }
        //     }

        //     $obj['cc'][] = 'muthuramanr@cygnusa.in';
        //     $obj['subject'] = 'DEVELOPMENT TESTING : ' . $obj['subject'];
        // }

        // require_once dirname(__FILE__) . '/phpmailer/PHPMailerAutoload.php';
        // require_once dirname(__FILE__) . '/phpmailer/class.phpmailer.php';

        // $mail = null;
        // try {
        //     $mail = new PHPMailer;

        //     $mail->isSMTP(); // telling the class to use SMTP
        //     $mail->SMTPAuth = false; // enable SMTP authentication
        //     //$mail->SMTPSecure = 'tls';    // sets the prefix to the servier
        //     //$mail->SMTPDebug = 2;
        //     $mail->Host = SMTP_HOST; // sets   as the SMTP server
        //     $mail->Port = SMTP_PORT; // set the SMTP port for the   server
        //     //$mail->Username = SMTP_USERNAME; //   username
        //     //$mail->Password = SMTP_PASSWORD; //   password
        //     //            $mail->SMTPOptions = array(
        //     //                'ssl' => array(
        //     //                    'verify_peer' => false,
        //     //                    'verify_peer_name' => false,
        //     //                    'allow_self_signed' => true
        //     //                )
        //     //           );

        //     $mail->setFrom($obj['from']); //Set who the message is to be sent from

        //     if (isset($obj['FromName'])) {
        //         $mail->FromName = $obj['FromName'];
        //     }

        //     if (isset($obj['replayto'])) {
        //         $mail->addReplyTo($obj['replayto']);
        //     }

        //     //TO EMAIL
        //     $to_email = '';
        //     if (isset($obj['to'])) {
        //         if (is_array($obj['to'])) {
        //             foreach ($obj['to'] as $res_to) {
        //                 $mail->addAddress($res_to);
        //             }
        //             $to_email = @implode(',', $obj['to']);
        //         } else if (is_string($obj['to'])) {
        //             $mail->addAddress($obj['to']);
        //             $to_email = $obj['to'];
        //         }
        //     }
        //     $mail->addBCC(SUPPORT_EMAIL);

        //     //CC EMAIL
        //     $cc_email = '';
        //     if (isset($obj['cc'])) {
        //         if (is_array($obj['cc'])) {
        //             foreach ($obj['cc'] as $res_cc) {
        //                 $mail->AddCC($res_cc);
        //             }
        //             $cc_email = @implode(',', $obj['cc']);
        //         } else if (is_string($obj['cc'])) {
        //             $mail->AddCC($obj['cc']);
        //             $cc_email = $obj['cc'];
        //         }
        //     }

        //     //$mail->AddBCC($obj->to);

        //     if (isset($obj['attachment_file'])) {
        //         $file_count = count($obj['attachment_file']);
        //         for ($x = 0; $x < $file_count; $x++) {
        //             if (!empty($obj['attachment_file'][$x])) {
        //                 $mail->addAttachment($obj['attachment_file'][$x]);
        //             }
        //         }
        //     }

        //     $mail->isHTML(true);
        //     $mail->Subject = $obj['subject'];
        //     $contentmail = $obj['message'];
        //     $mail->Body = $contentmail;

        //     $parent->executeQuery("INSERT INTO " . TABLE_EMAIL_LOG . " (`to_mail`, `from_mail`, `cc_mail`, `subject`, `is_success`, `created_on`) VALUES ('" . escape_str($to_email) . "','" . $obj['from'] . "','" . escape_str($cc_email) . "','" . escape_str($obj['subject']) . "', '0','" . NOW . "' )");
        //     $logid = $parent->lastInsertId();
        //     if (!$mail->send()) {
        //         //echo "Mailer Error: " . $mail->ErrorInfo;
        //         $headers = "From: " . $obj['from'] . " \r\n";
        //         //$headers .= "Reply-To: ".$replayto." \r\n";
        //         $headers .= "MIME-Version: 1.0\r\n";
        //         $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
        //         // @mail(SUPPORT_EMAIL, "Mail delivery report", "FROM : " . $obj['from'] . ", TO :" . $obj['to'] . " mail not delivered", $headers);
        //     } else {
        //         $parent->executeQuery("UPDATE " . TABLE_EMAIL_LOG . " SET is_success='1' WHERE id='" . $logid . "' ");
        //     }

        // } catch (phpmailerException $e) {

        //     $headers = "From: " . $obj['from'] . " \r\n";
        //     //$headers .= "Reply-To: ".$replayto." \r\n";
        //     $headers .= "MIME-Version: 1.0\r\n";
        //     $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
        //     // @mail(SUPPORT_EMAIL, "Mail delivery report", "FROM : " . $obj['from'] . ", TO :" . $obj['to'] . " mail not delivered", $headers);

        // }

    }
    /* /////////////////////////////// FORGOTLINK ////////////////////////////// */
    public static function sendForgotPasswordLink($parent, $data)
    {

        switch ($data['type']) {
            case "test":

                $message = '<table width="100%" bgcolor="#dfdfdf" border="0" cellspacing="10" cellpadding="0" style="padding-top:10px;">
			<tbody><tr>
			<td><table width="700" border="0" align="center" cellpadding="0" cellspacing="0" style="background:#ffffff; margin-top:0px;">
			<tbody><tr>
			<td bgcolor="#2d2d2d" height="36" style="font-size:12px;	font-family:Arial, Helvetica, sans-serif;	color:#e4e4e4;	text-align:left;	font-weight:bold; padding-left:14px; border-bottom:2px solid #C71444">Password Reset</td>
			</tr>
			<tr><td><table width="85%" align="center">
			<tbody><tr><td height="30" style="font-size:12px;	font-family:Arial, Helvetica, sans-serif;	color:#3f3f3f;	text-align:left;">Dear <span style="font-size:12px;	font-family:Arial, Helvetica, sans-serif;	color:#3f3f3f;	text-align:left; font-weight:bold; text-transform:uppercase;">' . $data['send_to'] . ',</span></td>
			</tr><tr><td height="30" style="font-size:11px;	font-family:Arial, Helvetica, sans-serif;	color:#3f3f3f;	text-align:left;padding-left: 10px;
			line-height: 1.5;"><div style="font-family:arial; color:#333; font-size:12px; padding:5px;">' . $data['link_value'] . '</div><div style="font-family:arial; color:#333; font-size:12px; padding:5px;" >This is an automatically generated email - please do not reply.</div></td>
			</tr>
			</tbody></table>
			</td>
			</tr>
			<tr>
			<td style="padding-top:0px; padding-bottom:10px;"></td>
			</tr>
			<tr>
			<td style="font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#3f3f3f; background:#fafafa; line-height:30px; text-align:center;border-bottom:2px solid #C71444"><div class="footer-con">
			<p>Thanks &amp; Regards, <strong style="color:#C71444;"> Nissan Support Team</strong></p>
			</div></td>
			</tr>

			</tbody></table></td>
			</tr>
			</tbody></table>';

                $obj = array();
                $obj['from'] = SUPPORT_EMAIL;
                $obj['replayto'] = SUPPORT_EMAIL;
                $obj['to'] = $data['send_to'];
                $obj['subject'] = "Password Reset";
                $obj['message'] = $message;
                // self::sendMai($parent, $obj);
                break;
            case "email":
                $message = '<table width="100%" bgcolor="#dfdfdf" border="0" cellspacing="10" cellpadding="0" style="padding-top:10px;">
			<tbody><tr>
			<td><table width="700" border="0" align="center" cellpadding="0" cellspacing="0" style="background:#ffffff; margin-top:0px;">
			<tbody><tr>
			<td bgcolor="#2d2d2d" height="36" style="font-size:12px;	font-family:Arial, Helvetica, sans-serif;	color:#e4e4e4;	text-align:left;	font-weight:bold; padding-left:14px;  ">Reset Password</td>
			</tr>
			<tr><td><table width="85%" align="center">
			<tbody><tr><td height="30" style="font-size:12px;	font-family:Arial, Helvetica, sans-serif;	color:#3f3f3f;	text-align:left;">Hi <span style="font-size:12px;	font-family:Arial, Helvetica, sans-serif;	color:#3f3f3f;	text-align:left; font-weight:bold; text-transform:uppercase;"> ' . $data['user']->fname . ',</span></td>
			</tr><tr><td height="30" style="font-size:11px;	font-family:Arial, Helvetica, sans-serif;	color:#3f3f3f;	text-align:left;padding-left: 10px;
			line-height: 1.5;"><div style="font-family:arial; color:#333; font-size:12px; padding:5px;">A password reset was requested for your account <a href="#" >' . $data['user']->emailid . '</a> at PACCAR PARTS BIN <br>To confirm this request, and set a new password for your account. please go to the following web address:<br><br><a href="' . $data['link_value'] . '">' . $data['link_value'] . '</a><br>(This link is valid for 30 min from the time this reset was first requested) <br><br>If this password reset was not requested by you, no action is needed.<br>If you need help, please contact the site administrator.</div><div style="font-family:arial; color:#333; font-size:12px; padding:5px;" >This is an automatically generated email - please do not reply.<br><br>Admin User </div></td>
			</tr>
			</tbody></table>
			</td>
			</tr>
			<tr>
			<td style="padding-top:0px; padding-bottom:10px;"></td>
			</tr>
			<tr>
			<td style="font-family:Arial, Helvetica, sans-serif; font-size:12px; color:#3f3f3f; background:#fafafa; line-height:30px; text-align:center;border-bottom:2px solid Black"><div class="footer-con">
			<p>Thanks &amp; Regards, <strong style="color:Black"> Support Team</strong></p>
			</div></td>
			</tr>

			</tbody></table></td>
			</tr>
			</tbody></table>';

                $obj = array();
                $obj['from'] = SUPPORT_EMAIL;
                $obj['replayto'] = SUPPORT_EMAIL;
                $obj['to'] = $data['send_to'];
                $obj['subject'] = "FORGOT PASSWORD LINK";
                $obj['message'] = $message;

                // self::sendMai($parent, $obj);
                break;
        }
    }

    /////////////////////User creation Email /////////
    public static function sendUserWelcomeEmail($parent, $data)
    {
        //print_r($data);
        switch ($data['type']) {

        }
    }

    public static function sendSMS($parent, $mobileno, $message)
    {
        // $test = "0";
        // $username = SMS_USERNAME;
        // $hash = SMS_HASH;
        // $sender = SMS_SENDERID;

        // //SMS LOG
        // $parent->executeQuery("INSERT INTO " . TABLE_SMS_LOG . " (`smpin`, `emp_code`, `userid`, `mobile`, `sms_data`, `status`, `created_on`, `modified_on`) VALUES ('" . $parent->current_smpin . "','" . $parent->current_emp_code . "','" . $parent->current_user_id . "','" . $mobileno . "','" . $message . "','0','" . NOW . "','" . NOW . "')");
        // $sms_log_id = $parent->lastInsertId();

        // $result = '';
        // if (strlen($mobileno) > 9) {

        //     $method = "SendMessage";
        //     $msgType = "TEXT";
        //     $v = "1.1";
        //     $format = "text";
        //     $numbers = "91" . $mobileno;
        //     //$data = "method=" . $method . "&send_to=" . $numbers . "&msg=" . $message . "&msg_type=" . $msgType . "&loginid=" . $username . "&auth_scheme=plain&password=" . $hash . "&v=" . $v . "&format=" . $format . "&mask=" . $sender;
        //     $data = "username=" . $username . "&password=" . $hash . "&to=" . $numbers . "&from=" . $sender . "&text=" . urlencode($message) . "&dlr-mask=19&dlr-url";

        //     $ch = curl_init(SMS_APIURL);
        //     curl_setopt($ch, CURLOPT_POST, true);
        //     curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        //     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //     $result = curl_exec($ch); // This is the result from the API
        //     curl_close($ch);
        // }
        // $status = '0';
        // if ($result == 'Sent.') {
        //     $status = 1;
        // }

        // //UPDATE LOG
        // $parent->executeQuery("UPDATE " . TABLE_SMS_LOG . " SET `status`='" . $status . "', `response`='" . escape_str($result) . "', `modified_on`='" . NOW . "' WHERE id='" . $sms_log_id . "'");
        $result = 'Sent.';
        return $result;
    }
    ////////////////////////////EMD USER EMAIl//////////////////////

}
