<?php

/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link      http://cakephp.org CakePHP(tm) Project
 * @since     0.2.9
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */

namespace App\Controller;

use App\Common\Permission;
use App\Utility\ManageLog;
use Cake\Controller\Controller;
use Cake\Log\Log;
use Cake\ORM\TableRegistry;
use Cake\Datasource\ConnectionManager;
use Cake\Event\Event;
use Cake\Mailer\Email;
use Exception;
use Mandrill;
use stdClass;
use Cake\I18n\I18n;
use Cake\Routing\Router;
use Cake\Mailer\Transport;
use App\Utility\EmailQueue\EmailQueue;

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @link http://book.cakephp.org/3.0/en/controllers.html#the-app-controller
 */
abstract class AppsController extends Controller {

    //public  $global_login_redirect = "Dashboard";

    var $languages = array('en' => 'English', 'ko' => 'Korean', 'chi' => 'Chinese');

    /**
     * Initialization hook method.
     *
     * Use this method to add common initialization code like loading components.
     *
     * e.g. `$this->loadComponent('Security');`
     *
     * @return void
     */
    public function initialize() {
        parent::initialize();


        $this->loadComponent('RequestHandler');
        $this->loadComponent('Cookie', ['expiry' => '1 day']);
        $this->loadComponent('Flash');
        $this->loadModel('Settings');

        $controller = 'Cmsusers';
        $loginRedirect_controller = 'Dashboard';

        $this->loadComponent('Auth', [
            'authorize' => ['Controller'],
            'authenticate' => [
                'Form' => [
                    'userModel' => $controller,
                    'passwordHasher' => [
                        'className' => 'Cms'
                    ],
                    'fields' => [
                        'username' => 'email',
                        'password' => 'password'
                    ]
                ]
            ],
            'loginAction' => [
                'controller' => $controller,
                'action' => 'login'
            ],
            'loginRedirect' => [
                'controller' => $loginRedirect_controller,
                'action' => 'index'
            ],
            'logoutRedirect' => [
                'controller' => $controller,
                'action' => 'login'
            ]
        ]);

        $this->setCompanyID();
        $this->Auth->allow(['display']);

        $setting = $this->Settings->getCurrentSettings();
        $this->set('setting', $setting);
        $this->manageDomainName();

        // pr($_SESSION);exit;
    }

    public function beforeFilter(Event $event) {

        if ($this->request->session()->read('Config.language')) {
            $language = $this->request->session()->read('Config.language');
            if ($language != I18n::defaultLocale()) {
                I18n::locale($language);
                $this->set("current_lang", $language);
            } else {
                $this->set("current_lang", I18n::defaultLocale());
            }

        } else {
            $this->set("current_lang", I18n::defaultLocale());
        }
        if ($this->request->session()->read('Auth.User.id')) {

            $this->set('current_module', $this->getModules());
            $this->set('sub_modules', $this->getSubModules());
            $this->set('module_pages', $this->getPages());
            $current_url = strtolower(Router::url());

        }
        $this->user_id = $user_id = $this->request->session()->read('Auth.User.id');
        $base_url = Router::url('/');
        $this->set('base_url', $base_url);

    }

    public function setCompanyID() {
        $this->set('company_id', $this->Auth->user('company_id'));
    }

    protected function generateRandomString($length = 10) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }


    public function sendEmail($templateName, $templateContent, $to, $sub = "New User registration", $attachment = "", $personalize = null) {
        $APP_SMTP_USERNAME = APP_SMTP_USERNAME;
        $APP_SMTP_FROM_NAME = APP_SMTP_FROM_NAME;
        $APP_EMAIL_CLASS = APP_EMAIL_CLASS;
        $APP_SMTP_HOST = APP_SMTP_HOST;
        $APP_SMTP_PORT = APP_SMTP_PORT;
        $APP_SMTP_TIMEOUT = APP_SMTP_TIMEOUT;
        $APP_SMTP_PASSWORD = APP_SMTP_PASSWORD;
        $APP_SMTP_IS_TLS = APP_SMTP_IS_TLS;

        if (!empty($personalize)) {
            $templateContent['email_signature'] = $personalize->email_signature;
            if ($personalize->is_smtp == 1) {
                $APP_SMTP_USERNAME = $personalize->username;
                $APP_SMTP_FROM_NAME = $personalize->smtp_from;
                $APP_SMTP_HOST = $personalize->smtp_host;
                $APP_SMTP_PORT = $personalize->smtp_port;
                $APP_SMTP_PASSWORD = $personalize->password;
            }
        }

        $SMTP_FORM_EMAIL = $APP_SMTP_USERNAME;

        if($APP_SMTP_HOST == 'sandbox.smtp.mailtrap.io'){
            $SMTP_FORM_EMAIL = $APP_SMTP_FROM_NAME;
        }
        else if($APP_SMTP_HOST == "smtp.mail.yahoo.com"){
            $APP_SMTP_IS_TLS = true;
            $is_yahoo = true;
        }

        $default = [
            'className' => $APP_EMAIL_CLASS,
            'host' => $APP_SMTP_HOST,
            'port' => $APP_SMTP_PORT,
            //'timeout' => $APP_SMTP_TIMEOUT,
            'username' => $APP_SMTP_USERNAME,
            'password' => $APP_SMTP_PASSWORD,
            //'tls' => $APP_SMTP_IS_TLS,
            'tls' => true,
            //'log'=> true
        ];



        if(isset($templateContent['company_email']) && !empty($templateContent['company_email'])){
            $SMTP_FORM_EMAIL = $templateContent['company_email'];
        }

        if(isset($templateContent['company_name']) && !empty($templateContent['company_name'])){
            $APP_SMTP_FROM_NAME = $templateContent['company_name'];
        }

        if(IS_QUEUE_ENABLE){
            $data = $templateContent;
            $options['member_id'] = 0;
            if (!empty($personalize) && $personalize->is_smtp == 1) {
                if($personalize->member_id > 0){
                    $options['member_id'] = $personalize->member_id;
                }
            }
            $new_file_link = "";
            if(!empty($attachment) && file_exists($attachment)){
                $att_email_queue_dir = WWW_ROOT."email_queue/".$this->Auth->user('id');
                if(!is_dir($att_email_queue_dir)){
                    mkdir($att_email_queue_dir,0777,true);
                }
                $extension = pathinfo($attachment, PATHINFO_EXTENSION);
                $new_file_name = time().".".$extension;
                $new_file_link = $att_email_queue_dir."/".$new_file_name;
                @copy($attachment, $new_file_link);
            }
            //$options['from_name'] = $APP_SMTP_FROM_NAME;
            $options['from_name'] = $APP_SMTP_FROM_NAME;
            $options['from_email'] = $SMTP_FORM_EMAIL;
            $options['subject'] = $sub;
            $options['template'] = $templateName;
            $options['format'] = 'html';
            $options['attachments'] = $new_file_link;
            EmailQueue::enqueue($to, $data, $options);

        }
        else{

            try {
                $email = new Email();
                if (!empty($personalize) && $personalize->is_smtp == 1) {
                        Email::configTransport('custom', $default);
                        $email->transport('custom');
                }
                else {
                    $email->transport('default');
                }


                if (isset($templateContent['no_reply']) && !empty($templateContent['no_reply'])) {
                    $email = $email->from($APP_SMTP_FROM_NAME);
                } else {
                    $email = $email->from($SMTP_FORM_EMAIL,$APP_SMTP_FROM_NAME);
                }

                $email->template($templateName)
                    ->emailFormat('html')
                    ->to($to)
                    ->viewVars($templateContent)
                    ->subject($sub);

                if (!empty($attachment)) {
                    $email->addAttachments($attachment);
                }


                $email->send();

            } catch (Exception $ex) {
                $this->log($ex);
            }
        }

    }

    /**
     * Before render callback.
     *
     * @param \Cake\Event\Event $event The beforeRender event.
     * @return void
     */
    public function beforeRender(Event $event) {

        if (!array_key_exists('_serialize', $this->viewVars) &&
            in_array($this->response->type(), ['application/json', 'application/xml'])
        ) {
            $this->set('_serialize', true);
        }
    }

    public function isAuthorized($user) {
        $controller = $this->request->params['controller'];
        $access_controllers_name = array();
        //  echo  $_SESSION["userType"];exit;
        if ($_SESSION["userType"] == CMS_USER_INDICATOR) {
            //echo 'this is';exit;
            // get current controller
            // get CRM controller list from constant
            // if current controller exist in CRM controller list then no need to check further code. Just return true
            // echo "sdfsdf";exit;
            $session = $this->request->session();
            //TODO - Change the logic of saving the user permissions
            $previous_permission_version = $session->read('permission_version');
            $current_permission_version = TableRegistry::get('cmsusers')->get($user['id'])->permission_version;
            if ($current_permission_version !== $previous_permission_version) {
                unset($_SESSION['hasEpicVelocity']);
                unset($_SESSION['hasVelocity']);
                unset($_SESSION['hasLS_Fax_Rtg_user']);
                unset($_SESSION['has_only_super_rtg_user']);
                unset($_SESSION['has_limited_version']);
                unset($_SESSION['has_limited_time']);

                $this->loadModel('MemberPackages');
                $member_id = $user['id'];

                $this->addPermissionsAndVersionToSession($session, $user, $current_permission_version);
                $this->limitedTimePkgCheck();
            }

            $user_permissions = $session->read('user_permissions');

            $request_action = strtolower($this->request->params['action']);

            $pages = $this->getPages();
//             print_r($pages);exit;
            if (array_key_exists($request_action, $pages)) {
                $action_page_id = $pages[$request_action];
                foreach ($user_permissions as $permission) {
                    if ($permission['page_id'] == $action_page_id) {
                        return true;
                    }
                }
            }

            if (!array_key_exists("Dashboard", $this->getModules())) {
                $this->Flash->error(__('You do not have permission to access this page'));
            }
        } else if ($_SESSION["userType"] == CRM_USER_INDICATOR) {
            // CRM user


            foreach ($_SESSION['access_controller'] as $key => $access_conroller) {
                // pr($access_conroller['controller_name']);
                $access_controllers_name[] = $access_conroller['controller_name'];
            }
            if($_SESSION['Auth']['User']['type'] == 1){
                //pr($this->Auth->user());exit;
                if(!in_array("Uploadhtml",$access_controllers_name) && $this->Auth->user('has_analysis_analyzer') == 1){
                    $access_controllers_name[] = "Uploadhtml";
                }

            }

            if (in_array($controller, $access_controllers_name)) {

                $session = $this->request->session();
                //TODO - Change the logic of saving the user permissions
                $previous_permission_version = $session->read('permission_version');
                $current_permission_version = TableRegistry::get('cmsusers')->get($user['id'])->permission_version;


                if ($current_permission_version !== $previous_permission_version) {
                    $this->addPermissionsAndVersionToSession($session, $user, $current_permission_version);
                }

                // $this->Flash->error(__('You do not have permission to access this page'));
                return true;
            }
            // Get current controller name
            // get   controller list from $_SESSION['access_controller']
            // check the current controller name exist in user's DB controller access list or not
            // if not, return false;
            // return true;
        } else if ($_SESSION["userType"] == CONTACT_USER_INDICATOR) {

            $this->loadModel('Contacts');
            $cmsuser_id = $this->Auth->user('id');
            $contact_id = $this->Auth->user('user_id');
            $client_info = $this->Contacts->find('all')->where(['id' => $contact_id, 'cmsuser_id' => $cmsuser_id])->toArray();
            $client_id = $client_info[0]['client_id'];

            $_SESSION['global_client_id'] = $client_id;
            foreach ($_SESSION['access_controller'] as $key => $access_conroller) {
                // pr($access_conroller['controller_name']);
                $access_controllers_name[] = $access_conroller['controller_name'];
            }
            //echo $controller;exit;
            if (in_array($controller, $access_controllers_name)) {
                $session = $this->request->session();
                //TODO - Change the logic of saving the user permissions
                $previous_permission_version = $session->read('permission_version');
                $current_permission_version = TableRegistry::get('cmsusers')->get($user['id'])->permission_version;
                //pr($current_permission_version);exit;
                if ($current_permission_version !== $previous_permission_version) {
                    $this->addPermissionsAndVersionToSession($session, $user, $current_permission_version);
                }
                return true;
            }
        } else if ($_SESSION["userType"] == STAF_USER_INDICATOR) {

            $session = $this->request->session();
            //TODO - Change the logic of saving the user permissions
            $previous_permission_version = $session->read('permission_version');
            $current_permission_version = TableRegistry::get('cmsusers')->get($user['id'])->permission_version;
            if ($current_permission_version !== $previous_permission_version) {
                $this->addPermissionsAndVersionToSession($session, $user, $current_permission_version);
            }

            foreach ($_SESSION['access_controller'] as $key => $access_conroller) {
                // pr($access_conroller['controller_name']);
                $access_controllers_name[] = $access_conroller['controller_name'];
            }
            if (in_array($controller, $access_controllers_name)) {


                return true;
            }
        } elseif ($_SESSION["userType"] == GUEST_USER_INDICATOR) {
            return true;
        }


        //echo $_SESSION["userType"];exit;
    }

    protected function addPermissionsAndVersionToSession($session, $user, $current_permission_version) {
        $connection = ConnectionManager::get('default');

        $permission_sql = 'SELECT  cmsusers.id AS user_id,pages.id AS page_id, pages.name AS page_name, modules.id AS module_id, sub_modules.name AS submodule_name, sub_modules.id AS submodule_id, sub_modules.controller_name AS controller, pages.method_name AS method
FROM            cmsusers
					INNER JOIN cmsuser_usergroups ON cmsusers.id = cmsuser_usergroups.cms_user_id
					INNER JOIN usergroups ON cmsuser_usergroups.usergroup_id = usergroups.id
					INNER JOIN usergroup_roles ON usergroups.id = usergroup_roles.usergroup_id
					INNER JOIN roles ON usergroup_roles.role_id = roles.id
					INNER JOIN role_pages ON roles.id = role_pages.role_id
					INNER JOIN pages ON role_pages.page_id = pages.id
					INNER JOIN sub_modules ON pages.sub_module_id = sub_modules.id
					INNER JOIN modules ON sub_modules.module_id = modules.id
					WHERE cmsusers.id =' . $user['id'] . " order by modules.id,sub_modules.id,pages.id";

        $user_permissions = $connection->execute($permission_sql)->fetchAll('assoc');


        $session->write('user_permissions', $user_permissions);
        $session->write('permission_version', $current_permission_version);

        if ($this->Auth->user('id') == SUPER_SUPER_ADMIN_ID) {
            $modules = TableRegistry::get('modules')->find('all')->contain([
                'SubModules' => [
                    'sort' => ['SubModules.sequence' => 'ASC']
                ],
                'SubModules.Pages' => [
                    'sort' => ['Pages.method_name' => 'ASC']
                ]
            ])
                ->order(['sequence' => 'ASC'])
                ->toArray();
        } else {
            $modules = TableRegistry::get('modules')->find('all')->contain([
                'SubModules' => [
                    'sort' => ['SubModules.sequence' => 'ASC']
                ],
                'SubModules.Pages' => [
                    'sort' => ['Pages.method_name' => 'ASC']
                ]
            ])->where([
                'id NOT IN' => [1001, 1002, 1007]
            ])
                ->order(['sequence' => 'ASC'])
                ->toArray();
        }

        $modules = serialize($modules);
        $session->write('modules', $modules);
        //debug($modules);
//        $session->write('permission_version_db', $user['permission_version']);
//
//        $this->log($session->read('user_permissions'));
//        $this->log($session->read('permission_version'));
//        $this->log($session->read('permission_version_db'));
    }

    public function getModules() {
        $request_controller = strtolower($this->request->params['controller']);
        if ($request_controller == "dashboard") {
            return array('Dashboard' => 'Dashboard');
        }
        $current_module_arr = array();
        $current_submodule_arr = $this->getSubModules();
        $modules = unserialize($this->request->session()->read('modules'));
        if (!empty($modules)) {
            foreach ($modules as $module) {
                foreach ($module['sub_modules'] as $submodule) {
                    if (current($current_submodule_arr) == $submodule['id']) {
                        $current_module_arr = array($module['name'] => $module['id']);
                        break 2;
                    }
                }
            }
        }

        return $current_module_arr;
        //return  ['Master Data' =>'1002'];
    }

    public function getSubModules() {

        $request_controller = strtolower($this->request->params['controller']);
        if ($request_controller == "dashboard") {
            return array();
        }
        $current_submodule_arr = array();
        $modules = unserialize($this->request->session()->read('modules'));
        if (!empty($modules)) {
            foreach ($modules as $module) {
                foreach ($module['sub_modules'] as $submodule) {
                    if ($request_controller == strtolower($submodule['controller_name'])) {
                        $current_submodule_arr = array($submodule['name'] => $submodule['id']);
                        break 2;
                    }
                }
            }
        }
        return $current_submodule_arr; // return ['Page Management' => '2022'];
    }

    public function getPages() {
        $request_controller = strtolower($this->request->params['controller']);
        if ($request_controller == "dashboard") {
            return array();
        }
        $pages_arr = array();
        $current_submodule_arr = $this->getSubModules();
        $modules = unserialize($this->request->session()->read('modules'));
        if (!empty($modules)) {
            foreach ($modules as $module) {
                foreach ($module['sub_modules'] as $submodule) {
                    if (current($current_submodule_arr) == $submodule['id']) {
                        foreach ($submodule['pages'] as $page) {
                            $pages_arr[$page['method_name']] = $page['id'];
                        }
                        break 2;
                    }
                }
            }
        }


        // print_r( $pages_arr);exit;

        return $pages_arr;

        /*
          return ['index' =>'3035',
          'add' => '3036',
          'edit' => '3037',
          'delete' =>'3038']; */
    }

    // Function to get the client IP address
    public function get_client_ip() {
        $ipaddress = '';
        if (isset($_SERVER['HTTP_CLIENT_IP']))
            $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
        else if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
            $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
        else if (isset($_SERVER['HTTP_X_FORWARDED']))
            $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
        else if (isset($_SERVER['HTTP_FORWARDED_FOR']))
            $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
        else if (isset($_SERVER['HTTP_FORWARDED']))
            $ipaddress = $_SERVER['HTTP_FORWARDED'];
        else if (isset($_SERVER['REMOTE_ADDR']))
            $ipaddress = $_SERVER['REMOTE_ADDR'];
        else
            $ipaddress = 'UNKNOWN';

        if (strlen($ipaddress) > 45){
            $ipaddress = substr($ipaddress, 0,45);
        }


        return $ipaddress;
    }

    public function getCategoryNameById($id = null) {
        $categoriesTable = TableRegistry::get('Categories');
        $categories = $categoriesTable->find('all')
            ->select(['id', 'name'])
            ->where([
                'Categories.status' => 1,
                'Categories.id' => $id
            ])
            ->first();
        $category_name = $categories->name;
        return $category_name;
    }

    public function getDateDifference($start_date = null, $end_date = null) {
        if (strtotime($start_date) > strtotime($end_date)) {
            return 0;
        } else {
            $start_date = date_create($start_date);
            $end_date = date_create($end_date);

            $interval = date_diff($start_date, $end_date);
            // return $interval->format($differenceFormat);
            return $interval->days;
        }
    }


    function _getSettingData() {
        $settings = [];
        $settingsTable = TableRegistry::get('Settings');
        $settings = $settingsTable->find('all')
            ->where(['Settings.id' => 1])
            ->first();
        return $settings;
    }

    public function isUser($user) {

        $result = true;

        $userType = 2;
        if (isset($_SESSION["userType"])) {
            $userType = $_SESSION["userType"];
        }


        if (!empty($user) && $userType == 1) {
            $result = false;
        }
        else if ($userType == 2 || $userType == 3) {
            $result = false;
        }

        if($_SESSION["userType"] == CRM_USER_INDICATOR){
            $result = true;
        }
//pr($userType);exit;
        return $result;
    }

    public function setUserType() {

        if (isset($_SESSION['userType'])) {
            $userType = $_SESSION['userType'];
            if ($userType == CRM_USER_INDICATOR && !Permission::isEmployeeAsAdmin()) {
                $this->viewBuilder()->layout("new_user_dashboard");
            } else if ($userType == CMS_USER_INDICATOR || Permission::isEmployeeAsAdmin()) {
                $this->viewBuilder()->layout("new_dashboard");
            } else if ($userType == CONTACT_USER_INDICATOR) {
                $this->viewBuilder()->layout("new_contact_user_dashboard");
            } else if ($userType == STAF_USER_INDICATOR) {
                $this->viewBuilder()->layout("new_dashboard");
            } elseif ($_SESSION["userType"] == 5) {

                $this->viewBuilder()->layout("custom_layout");
            }
        }
    }

    public function checkUser() {
        $user = $this->Auth->user();
        if (!empty($user)) {
            $this->viewBuilder()->layout("custom_layout");
        }
    }

    public function isAccessAllClients() {
        $result = false;
        if ($_SESSION['userType'] == CRM_USER_INDICATOR) {
            $auth_employee_id = $this->Auth->user('user_id');
            $is_show_all_clients = $this->Auth->user('is_show_all_clients');
            if ($is_show_all_clients == 2) {
                $result = true;
            }
        }

        return $result;
    }

    public function setSteps($step_name, $member_id) {
        $this->loadModel('CmsuserStatus');
        $result = 1;
        $memberStatusObj = $this->CmsuserStatus->getCmsuserStatusByMemberId($member_id)->toArray();
        if ($memberStatusObj[$step_name] == 0) {
            $result = 0;
        }

        $this->set("step_status", $result);
        return $result;
    }

    public function manageDomainName($personalizeObject = null, $isSetDefault = 0) {
        if (!defined('APP_SERVER_HOST_URL')) {
            if (!empty($personalizeObject)) {
                $www = "";
                if ($personalizeObject->is_www == 1) {
                    $www = "www.";
                }
                $_SESSION['APP_SERVER_HOST_URL'] = $personalizeObject->domain_type . $www . $personalizeObject->domain . "/";
                if (isset($_SESSION['APP_SERVER_HOST_URL']) && !empty($_SESSION['APP_SERVER_HOST_URL'])) {
                    define('APP_SERVER_HOST_URL', $_SESSION['APP_SERVER_HOST_URL']);
                }
            } else if (isset($_SESSION['APP_SERVER_HOST_URL']) && !empty($_SESSION['APP_SERVER_HOST_URL'])) {
                define('APP_SERVER_HOST_URL', $_SESSION['APP_SERVER_HOST_URL']);
            } elseif ($isSetDefault == 1) {
                define('APP_SERVER_HOST_URL', APP_SERVER_HOST_URL_DEFAULT);
                $_SESSION['APP_SERVER_HOST_URL'] = APP_SERVER_HOST_URL_DEFAULT;
            }
        }

        if (defined('APP_SERVER_HOST_URL')) {
            //unset($_SESSION['APP_SERVER_HOST_URL']);
        }

        //echo APP_SERVER_HOST_URL."<br/>";
    }

    public function getCurrentDomain() {
        $parse_url = parse_url($_SERVER['HTTP_REFERER']);
        if (isset($_SESSION['referer_domain']) && $isFromLogout == 1) {
            $domain = $_SESSION['referer_domain'];
        } else {
            $domain = $parse_url['host'];
            $_SESSION['referer_domain'] = $domain;
        }

        if (empty($domain)) {
            if (!empty($_SERVER['HTTP_HOST'])) {
                $domain = $_SERVER['HTTP_HOST'];
            }
        }

        $domain = str_replace("www.", "", $domain);
        // echo $domain;
        return $domain;
    }


    function getBaseUrl()
    {
        // output: /myproject/index.php
        $currentPath = $_SERVER['PHP_SELF'];

        // output: Array ( [dirname] => /myproject [basename] => index.php [extension] => php [filename] => index )
        $pathInfo = pathinfo($currentPath);

        // output: localhost
        $hostName = $_SERVER['HTTP_HOST'];

        // output: http://
        $protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https'?'https':'http';

        // return: http://localhost/myproject/
        return $protocol.'://'.$hostName;
    }


    public function isUserMembershipActive($member_id) {
        $this->loadModel('Cmsusers');
        if (!$this->Cmsusers->isMembershipActive($member_id)) {
            return $this->redirect(['controller' => 'Cmsusers', 'action' => 'logout']);
        }
    }


    public function limitedTimePkgCheck(){
        $_SESSION['limited_time_days'] = 0;
        $result = false;
        if(isset($_SESSION['has_limited_time']) && $_SESSION['has_limited_time']){

            $this->loadModel('App');
            $this->loadModel('Settings');
            $setting = $this->Settings->getCurrentSettings();
            $required_days = $setting->limited_time_count;
            if($required_days > 0){
                $days = $this->App->daysBetween($this->Auth->user('created_on'),$this->App->getSystemCurrentTimeStamp());
                if($days > $required_days){
                    $result = true;
                    $_SESSION['limited_time_days'] = $required_days;
                }
            }
        }

        return $result;
    }


    // Function for user log
    public function appLog($data){

        $manageLog = new ManageLog();
        $manageLog->userLog($data);
    }

    public function getCurrentUserType(){
        $common = new \App\Utility\Common;
        return $common->getCurrentUserInfo();
    }

    public function splitString($string,$limit = 100){
        $small = "";
        if(!empty($string)){
            $small = substr($string, 0, $limit);
            if(!empty($small) && strlen($string) > $limit){
                $small .= "...";
            }
        }
        return $small;
    }

    protected function getJsonData(){
        $data = file_get_contents("php://input");
        $this->data = (isset($data) && $data != '') ? json_decode($data, true) : array();
    }

    protected function getApiResponse($response){
        $this->response->type('json');  // this will convert your response to json
        $this->response->body(json_encode($response));   // Set your response in body
        $this->response->send();  // It will send your response
        $this->response->stop();  // At the end stop the response
    }

    protected function setClientStatus(){
        $this->loadModel('ClientStatusTypes');
        $client_status_list = $this->ClientStatusTypes->getActiveClientStatusByMemberId($this->Auth->user('id'));
        if(!empty($client_status_list)){
            $_SESSION['client_status_list'] = $client_status_list;
        }
    }

    public function setPermissions(){

        $current_module = $this->getModules();
        $this->set('current_module', $current_module);
        $this->set('module_pages', $this->getPages());
        $this->set('languages', $this->languages);
        $user_permissions = $this->request->session()->read('user_permissions');
        if(!empty($user_permissions)) {
            $permissions = array_filter($user_permissions, function ($permission) {
                return  $permission['controller'] === $this->request->params['controller'];
            });
            $this->set('user_permission', $permissions);
        }
        $this->viewBuilder()->layout("custom_layout");
    }


}