<?php

namespace App\Controller;

use App\Common\Permission;
use App\Controller\AppsController;
use Cake\I18n\I18n;
use Cake\Routing\Router;
use Cake\ORM\TableRegistry;
use Cake\Validation\Validator;
use DateTime;
use Mandrill;
use Cake\Datasource\ConnectionManager;
use App\Utility\forumUtils;
use App\Helper\commonLogic;
use Cake\Network\Response;

/**
 * Cmsusers Controller
 *
 * @property \App\Model\Table\CmsusersTable $Cmsusers
 * @property \App\Model\Table\UsergroupsTable $Usergroups
 * @property \App\Model\Table\PersonalizesTable $Personalizes
 */
class CmsusersController extends AppsController
{

    public function initialize()
    {
        parent::initialize();

        $this->loadModel('Cmsusers');
        $this->loadModel('Usergroups');
        $this->loadModel('Personalizes');
        I18n::locale('en_US');

        $this->Auth->allow(['forgotPassword']);
        $this->Auth->allow(['resetPassword']);
        $this->Auth->allow(['contactedit']);
        $this->Auth->allow(['revokePassword']);
        $this->Auth->allow(['zapierAuth']);
        $this->Auth->allow(['trialaccount']);
        $this->Auth->allow(['changeLanguage']);


    }


    public function revokePassword($cmsuser_id)
    {
        $result = $this->Cmsusers->passwordRevokeActionById($cmsuser_id);
        $message = "Not retored";
        if ($result) {
            $message = "Password restored";
        }

        echo $message;
        exit;
    }


    public function allowaction($cmsuser_id)
    {
        $this->loadModel('Settings');
        $cols = ['default_password'];
        $default_password = "";
        $setting = $this->Settings->getCurrentSettings($cols);

        if (!empty($setting->default_password)) {
            $default_password = $setting->default_password;
        }

        $result = $this->Cmsusers->passwordAllowActionById($cmsuser_id, $default_password);

        if ($result) {
            $this->Flash->success(__('Password Updated successfully.'));
            return $this->redirect($this->referer());
        }

    }

    public function revokeaction($cmsuser_id)
    {

        $result = $this->Cmsusers->passwordRevokeActionById($cmsuser_id);

        if ($result) {
            $this->Flash->success(__('Password restore successfully.'));
        }

        return $this->redirect($this->referer());
    }


    private function setHeaderFooterByDomain()
    {

        // $this->redirectToWWW();

        $isFromLogout = 0;
        $isSetDefault = 1;
        if (isset($_SESSION['logout']) && $_SESSION['logout'] == 1) {
            $isFromLogout = 1;
            unset($_SESSION['logout']);
        }
        $domain = $this->getBaseUrl();
        $main_domain = $this->getCurrentDomain();
        //echo "==".$main_domain;
        if ($main_domain != SITE_DOMAIN && $main_domain != "secureclientportalaccess.com") {
            $cmsuser = $this->Cmsusers->find()->where(['website LIKE ' => "%" . $main_domain . "%"])->first();
            if (!empty($cmsuser)) {
                return $this->redirect(CLIENT_PORTAL_DOMAIN);
            }

        }

//            else{
//                if($domain == SITE_DOMAIN){
//                    $this->manageDomainName(null,1);
//                }else{
//                    $this->manageDomainName();
//                }
//            }
    }


    public function isAuthorized($user)
    {
        $request_action = $this->request->params['action'];
        if ($request_action == "logout" || $request_action == "login" || $request_action == "bulkAction" || $request_action == "terms" || $request_action == "editProfile") {
            return true;
        }
        return parent::isAuthorized($user);
    }

    /**
     * Index method
     *
     * @return void
     */
    public function index($id = null)
    {
        if ($this->request->is('post')) {
            if($id >0){
                   $this->pausemembership($id);
            }
        }
        if ($this->Auth->user()) {
            $page_limit = 10;
            if (isset($this->request->query['page_limit'])) {
                $page_limit = $this->request->query('page_limit');
            }
            $this->paginate = [
                'limit' => $page_limit,
                'contain' => ['Companies']
            ];

            $cmsUserUsergroupAssoc = [];
            $search = '';

            $member = '';
            $req_duery = $this->request->query();
            if (isset($this->request->query['search'])) {
                $search = $this->request->query('search');
            }

            $cmsuser_usergroupTable = TableRegistry::get('cmsuser_usergroups');
            $search_text_condition = '(Cmsusers.username LIKE ' . '"%' . $search . '%"' . ' OR Cmsusers.email LIKE ' . '"%' . $search . '%")';
            if ($this->Auth->user('id') == SUPER_SUPER_ADMIN_ID) {
                $users = $this->Cmsusers->find('all')->where([
                    $search_text_condition
                ]);
            } else {
                $adminAssoc = $this->hasAdminRole($this->Auth->user('id'));
                extract($adminAssoc);
                //pr($cmsuser_ids);exit;
                $condition_member_1 = "CU.usergroup_id != " . ADMIN_USER_GROUP_ID;
                $condition_member_2 = "usergroup_id != " . ADMIN_USER_GROUP_ID;
                $condition_default = "Cmsusers.id NOT IN (" . implode(",", $cmsuser_ids) . ")";
                if ($isAdmin) {
                    $condition_member_1 = "";
                    $condition_member_2 = "";
                    $condition_default = "";
                }

                if (isset($this->request->query['default_password']) && !empty($this->request->query['default_password'])) {
                    $is_default_pass = $this->request->query('default_password');
                    if ($is_default_pass == 2) {
                        $is_default_pass = 0;
                    }
                    if (!empty($condition_default)) {
                        $condition_default .= " AND Cmsusers.is_allow_defult_pass = " . $is_default_pass;
                    } else {
                        $condition_default = "Cmsusers.is_allow_defult_pass = " . $is_default_pass;
                    }
                }
                //echo $condition_default;exit;
                if (isset($this->request->query['member']) && !empty($this->request->query['member'])) {
                    $member = $this->request->query('member');
                    if ($member == 1) {

                        $users = $this->Cmsusers->find('all')->join([
                            'table' => 'cmsuser_usergroups',
                            'alias' => 'CU',
                            'type' => 'LEFT',
                            'conditions' => [
                                'CU.cms_user_id = Cmsusers.id'
                            ]
                        ])->select(['id', 'username', 'stripe_customer_id',
                            'email', 'created_on', 'CU.usergroup_id',
                            'CU.cms_user_id', 'Phone', 'status', 'created_on', 'is_allow_defult_pass'])
                            ->distinct('Cmsusers.id')->where([
                                $search_text_condition,
                                'company_id' => $this->Auth->user('company_id'),
                                'CU.usergroup_id' => CUSTOMER_USER_GROUP_ID,
                                $condition_default
                            ]);
                    } elseif ($member == 2) {
                        $users = $this->Cmsusers->find('all')->where([
                            $search_text_condition,
                            'company_id' => $this->Auth->user('company_id'),
                            'Cmsusers.id NOT IN' => $cmsuser_usergroupTable->find()->where(['usergroup_id' => CUSTOMER_USER_GROUP_ID])->select('cms_user_id'),
                            $condition_default
                        ]);
                    }

                } else {
                    $query = $cmsuser_usergroupTable->find();
                    $users = $this->Cmsusers->find('all')->where([
                        $search_text_condition,
                        'company_id' => $this->Auth->user('company_id'),
                        $condition_default
                    ]);


                    if (!empty($query->toArray())) {
                        foreach ($query as $q) {
                            $cmsUserUsergroupAssoc[$q->cms_user_id][] = $q->usergroup_id;
                        }
                    }


                }


            }

            //echo "<pre>";print_r($users->toArray());exit;
            if (isset($this->request->data['isExport']) && $this->request->data['isExport'] == 1) {
                $this->importMember($users, $cmsUserUsergroupAssoc);
            }


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

            $this->set('user_permission', $user_permissions);
            $this->set('bulk_actions', [BULK_ACTION_DELETE => "Move to trash"]);
            $this->set('cmsusers', $this->paginate($users));
            $this->set('member', $member);
            $this->set('req_duery', $req_duery);
            $this->set('cmsUserUsergroupAssoc', $cmsUserUsergroupAssoc);
            $this->set('searchText', $search);
            $this->set('_serialize', ['cmsusers']);
            //$this->viewBuilder()->layout("user_management");
            $this->set('current_module', $this->getModules());
            $this->set('page_list', $this->getPages());
            $this->set('module_pages', $this->getPages());
            $nav_arr[0] = array('action' => 'add', 'page_id' => '3046', 'icon' => '<i class="fa fa-plus-circle"></i>', 'label' => 'Add');
            $this->set('nav_arr', $nav_arr);
            $this->set('page_limit', $page_limit);
            $this->viewBuilder()->layout("custom_layout");
        } else {
            $this->redirect($this->Auth->redirectUrl());
        }
    }


    private function hasAdminRole($cmsuser_id, $admin_id = null)
    {
        $result = false;
        $isAdmin = false;
        $entityTable = TableRegistry::get('cmsuser_usergroups');
        $cmsuser_usergroups = $entityTable->find()->where(['usergroup_id' => ADMIN_USER_GROUP_ID])->toArray();
        $new_cmsuser_usergroups = $cmsuser_usergroups;
        if (!empty($cmsuser_usergroups)) {
            foreach ($cmsuser_usergroups as $cmsuser_usergroup) {
                if ($cmsuser_usergroup->cms_user_id == $cmsuser_id) {
                    $result = true;
                    break;
                }
            }
        }
        if (!empty($admin_id)) {
            if (!empty($cmsuser_usergroups)) {
                foreach ($cmsuser_usergroups as $cmsuser_usergroup) {
                    if ($cmsuser_usergroup->cms_user_id == $admin_id) {
                        $isAdmin = true;
                        break;
                    }
                }
            }
        }
        $cmsuser_ids = [];
        if (!empty($new_cmsuser_usergroups)) {
            foreach ($cmsuser_usergroups as $cmsuser_usergroup) {
                $cmsuser_ids[] = $cmsuser_usergroup->cms_user_id;
            }
        }

        return ['isAdmin' => $result, 'cmsuser_ids' => $cmsuser_ids, 'is_current_user_admin' => $isAdmin];
    }

    private function importMember($users, $cmsUserUsergroupAssoc)
    {

        if (empty($users->toArray())) {
            $this->Flash->error(__('There is no data for exporting.'));
            return $this->redirect($this->referer());
        }

        $filename = 'member-export.csv';
        //ob_start();
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment;filename=' . $filename);
        $fp = fopen('php://output', 'w');
        $firstLine = 1;
        if ($firstLine == 1) {
            $heading = MEMBER_EXPORT_CSV_HEADING;
            fputcsv($fp, $heading);
            $firstLine = 2;
        }
        if (!empty($users->toArray())) {
            foreach ($users as $user) {
                $member = "No";
                if (isset($user->CU['usergroup_id']) && $user->CU['usergroup_id'] == CUSTOMER_USER_GROUP_ID) {
                    $member = "Yes";
                } elseif (isset($cmsUserUsergroupAssoc[$user->id]) && in_array(CUSTOMER_USER_GROUP_ID, $cmsUserUsergroupAssoc[$user->id])) {
                    $member = "Yes";
                }


                $csv_value = [
                    $user->id,
                    $user->username,
                    $user->email,
                    $member,
                    $user->stripe_customer_id,
                    $user->phone,
                    $user->created_on
                ];
                fputcsv($fp, $csv_value);
            }
        }
        //fputcsv($fp, []);
        // pr($clientValue);exit;
        fclose($fp);
        exit;
    }

    /**
     * View method
     *
     * @param string|null $id Cmsuser id.
     * @return void
     * @throws \Cake\Network\Exception\NotFoundException When record not found.
     */
    public function view($id = null)
    {
        $cmsuser = $this->Cmsusers->get($id, [
            'contain' => ['Companies', 'CmsuserUsergroups']
        ]);

        $usergroup = array();
        if (!(empty($cmsuser->cmsuser_usergroups))) {
            $usergroup = $this->Usergroups->find('all')
                ->where(['Usergroups.id' => $cmsuser->cmsuser_usergroups[0]->usergroup_id])
                ->first();
        }


        $user_permissions = $this->request->session()->read('user_permissions');
        $this->set('user_permission', $user_permissions);
        $this->set('cmsuser', $cmsuser);
        $this->set('usergroup', $usergroup);
        $this->set('_serialize', ['cmsuser']);
        $this->set('current_module', $this->getModules());
        $nav_arr[0] = array('action' => 'index', 'page_id' => '3045', 'icon' => '<i class="fa fa-list"></i>', 'label' => 'List');
        $this->set('nav_arr', $nav_arr);
        $this->viewBuilder()->layout("custom_layout");
    }

    /**
     * Add method
     *
     * @return void Redirects on successful add, renders view otherwise.
     */
    public function add()
    {

        $cmsuser = $this->Cmsusers->newEntity();
        if ($this->request->is('post')) {
//            pr($this->request->data);exit;
            $email = trim($this->request->data['email']);

            $result = $this->Cmsusers->find('all', ['fields' => 'id'])->last();
            $second_last_insert_id = $result->id;
            $last_insert_id = $second_last_insert_id + 1;
            if (!is_dir('media/companies/' . $last_insert_id)) {
                mkdir('media/companies/' . $last_insert_id, 0777, true);
            }

            if (!is_dir('cmsuser_logo')) {
                mkdir('cmsuser_logo', 0777, true);
            }

            $imagedes = $this->request->webroot . 'webroot/media/companies/' . $last_insert_id;
            //$imagepath = 'webroot/media/companies/'.$last_insert_id.'/'.$this->request->data['img_path']['name'];
            $imagepath = 'media/companies/' . $last_insert_id . '/' . $this->request->data['img_path']['name'];
            if (!empty($this->request->data['img_path']['name'])) {
                $file = $this->request->data['img_path']; //put the data into a var for easy use

                $ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
                $arr_ext = array('jpg', 'jpeg', 'gif', 'png'); //set allowed extensions

                //only process if the extension is valid
                if (in_array($ext, $arr_ext)) {
                    //do the actual uploading of the file. First arg is the tmp name, second arg is
                    //where we are putting it
                    move_uploaded_file($_FILES["img_path"]["tmp_name"], WWW_ROOT . 'media/companies/' . $last_insert_id . '/' . basename($_FILES['img_path']['name']));
                } else {
                    $this->Flash->error(__('Profile Picture is not in right format.Please, try again.'));
                    return $this->redirect(['action' => 'add']);
                }
                $this->request->data['img_path'] = $imagepath;
            }


            $cmsuser = $this->createUser($cmsuser);
            $password = $this->request->data('password');
            $isUnique = $this->checkUniqueEmail($email);
            $personalize =  $this->Personalizes->find()->where(['company_id'=> $this->Auth->user('company_id')])->first();

            if ($isUnique) {
                $result = $this->Cmsusers->save($cmsuser);
                if ($result) {
                    if (!empty($this->request->data['logo_path']['name'])) {
                        $insertedId = $result->id;
                        $logofile = $this->request->data['logo_path'];
                        $ext = substr(strtolower(strrchr($logofile['name'], '.')), 1);
                        $logoname = explode('.', $logofile['name'])[0];
                        $newname = $logoname . "_" . $insertedId . "." . $ext;
                        //pr($newname);exit;
                        $cmsuser->logo = $newname;
                        if ($this->Cmsusers->save($cmsuser)) {
                            $this->uploadlogo($newname, $insertedId, $ext);
                            $this->Cmsusers->save($cmsuser);
//                            $this->assignPackageForMember($isMember, $cmsuser->id, $package_ids);
                            $this->Flash->success(__('The user has been saved.'));
                        } else {
                            $this->Flash->error(__('The user could not be saved. Please, try again.'));
                        }

                    }

                    $template_content = array(
                        'firstname' => $cmsuser->username,
                        'user_email' => $cmsuser->email,
                        'password' => $password,
                        'loginurl' => APP_SERVER_HOST_URL.'/login'
                    );
                    $personalize =  $this->Personalizes->find()->where(['company_id'=> $this->Auth->user('company_id')])->first();
                    $this->sendEmail(MANDRILL_TEMPLATE_USER_CREATION, $template_content, $cmsuser->email,'New User registration',null,$personalize);

                    return $this->redirect(['action' => 'index']);
                }
                else {
                    $this->Flash->error(__('The user could not be saved. Please, try again.'));
                    $this->log($cmsuser->errors());
                }
            }
            else {
                $this->Flash->error(__('This email already exist'));
            }
        }

        $user_permissions = $this->request->session()->read('user_permissions');
        $this->set('user_permission', $user_permissions);
        $this->set('cmsuser', $cmsuser);
        $this->set('_serialize', ['cmsuser']);
        $this->set('current_module', $this->getModules());
        $nav_arr[0] = array('action' => 'index', 'page_id' => '3045', 'icon' => '<i class="fa fa-list"></i>', 'label' => 'List');
        $this->set('nav_arr', $nav_arr);
        $this->viewBuilder()->layout("custom_layout");
    }


    /*
    private function assignPackageForMember($isMember, $member_id, $package_ids)
    {
        if (isset($isMember) && $isMember == 1 && !empty($package_ids)) {
            $this->MemberPackages->assignPackagesForNewMember($member_id, $package_ids);
        }
    }
    */

    private function uploadlogo($newname, $id, $ext)
    {
        //get the extension
        $arr_ext = array('jpg', 'jpeg', 'png'); //set allowed extensions


        if (in_array($ext, $arr_ext)) {
            //do the actual uploading of the file. First arg is the tmp name, second arg is
            //where we are putting it
            move_uploaded_file($_FILES["logo_path"]["tmp_name"], WWW_ROOT . 'cmsuser_logo/' . $newname);
        } else {
            $this->Flash->error(__('Profile Picture is not in right format.Please, try again.'));
            return $this->redirect(['action' => 'add']);
        }
    }

    private function checkUniqueEmail($email)
    {
        $result = true;

        $cmsUsersTable = TableRegistry::get('cmsusers');
        $cmsuser = $cmsUsersTable->find()->where(['email' => $email])->first();

        if (!empty($cmsuser)) {
            return false;
        }
/*
        $crmUsersTable = TableRegistry::get('crmusers');
        $crmuser = $crmUsersTable->find()->where(['email' => $email])->first();

        if (!empty($crmuser)) {
            return false;
        }
        $contactTable = TableRegistry::get('contacts');
        $contact = $contactTable->find()->where(['email' => $email])->first();

        if (!empty($contact)) {
            return false;
        }
*/

        return $result;

    }

    /**
     * Edit method
     *
     * @param string|null $id Cmsuser id.
     * @return void Redirects on successful edit, renders view otherwise.
     * @throws \Cake\Network\Exception\NotFoundException When record not found.
     */
    public function edit($id = null)
    {

        $adminAssoc = $this->hasAdminRole($id, $this->Auth->user('id'));
        extract($adminAssoc);
        if (!$is_current_user_admin && $isAdmin) {
            $this->Flash->error(__('You do not have permission this page.'));
            return $this->redirect(['action' => 'index']);
        }

        $cmsuser = $this->Cmsusers->get($id, [
            'contain' => []
        ]);
        if ($this->request->is(['patch', 'post', 'put'])) {
            //pr($this->request->data);exit;
            if (!empty($this->request->data['img_path']['name'])) {
                $id = $this->request->params['pass'][0];
                if (!empty($this->request->data['previous_img_path'])) {
                    unlink(WWW_ROOT . '/' . $this->request->data['previous_img_path']);
                }
                $imagedes = $this->request->webroot . 'webroot/media/companies/' . $id;
                //$imagepath = 'webroot/media/companies/'.$last_insert_id.'/'.$this->request->data['img_path']['name'];
                $imagepath = 'media/companies/' . $id . '/' . $this->request->data['img_path']['name'];
                $file = $this->request->data['img_path']; //put the data into a var for easy use

                $ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
                $arr_ext = array('jpg', 'jpeg', 'gif', 'png'); //set allowed extensions

                //only process if the extension is valid
                if (in_array($ext, $arr_ext)) {
                    //do the actual uploading of the file. First arg is the tmp name, second arg is
                    //where we are putting it
                    move_uploaded_file($_FILES["img_path"]["tmp_name"], WWW_ROOT . 'media/companies/' . $id . '/' . basename($_FILES['img_path']['name']));
                } else {
                    $this->Flash->error(__('Profile Picture is not in right format.Please, try again.'));
                    return $this->redirect(['action' => 'edit']);
                }
                $this->request->data['img_path'] = $imagepath;
            } else {
                $this->request->data['img_path'] = $this->request->data['previous_img_path'];
            }

            if (!empty($this->request->data['logo_path']['name'])) {
                if (!is_dir('cmsuser_logo')) {
                    mkdir('cmsuser_logo', 0777, true);
                }
                $previous_logo = $this->request->data('previous_logo');
                $logofile = $this->request->data['logo_path'];
                $strArray = explode('.', $logofile['name']);
                $logoname = $strArray[0];
                $ext = $strArray[1];

                $newImageName = $logoname . "_" . $id . "." . $ext;
                unlink(WWW_ROOT . 'cmsuser_logo/' . $previous_logo);
                $cmsuser->logo = $newImageName;
                $this->uploadlogo($newImageName, $id, $ext);

                //echo $newImageName."====".$previous_logo;exit;


            } else {
                $cmsuser->logo = $this->request->data['previous_logo'];
            }
            $email = trim($this->request->data['email']);
            $cmsuser = $this->Cmsusers->patchEntity($cmsuser, $this->request->data);
            // pr();exit;
            // $isUnique = $this->Cmsusers->isUniqueCheckEmail($email, $id);
            $errors = $cmsuser->errors();

            if (empty($errors)) {
                if ($this->Cmsusers->save($cmsuser)) {
                    $this->Flash->success(__('The cmsuser has been updated.'));
                    return $this->redirect(['action' => 'index']);
                } else {
                    $this->Flash->error(__('The cmsuser could not be saved. Please, try again.'));
                }
            } else {
                if (isset($errors['email']['validemail']) && !empty($errors['email']['validemail'])) {
                    $this->Flash->error(__('This email already exist'));
                }

            }
        }

        $user_permissions = $this->request->session()->read('user_permissions');
        $this->set('user_permission', $user_permissions);
        $this->set('cmsuser', $cmsuser);
        $this->set('_serialize', ['cmsuser']);
        $this->set('current_module', $this->getModules());
        $nav_arr[0] = array('action' => 'index', 'page_id' => '3045', 'icon' => '<i class="fa fa-list"></i>', 'label' => 'List');
        $this->set('nav_arr', $nav_arr);
        $this->viewBuilder()->layout("custom_layout");
    }


    /**
     * Delete method
     *
     * @param string|null $id Cmsuser id.
     * @return \Cake\Network\Response|null Redirects to index.
     * @throws \Cake\Network\Exception\NotFoundException When record not found.
     */
    public function delete($id = null)
    {

        $adminAssoc = $this->hasAdminRole($id, $this->Auth->user('id'));
        extract($adminAssoc);
        if (!$is_current_user_admin && $isAdmin) {
            $this->Flash->error(__('You do not have permission this page.'));
            return $this->redirect(['action' => 'index']);
        }

        $this->request->allowMethod(['post', 'delete']);

        $cmsuser = $this->Cmsusers->get($id, [
            'contain' => ['Companies', 'CmsuserUsergroups']
        ]);

        if (empty($cmsuser->cmsuser_usergroups)) {
            if ($this->Cmsusers->delete($cmsuser)) {
                $this->Flash->success(__('The user has been deleted.'));
            } else {
                $this->Flash->error(__('The user could not be deleted. Please, try again.'));
            }
        }
        else {
            $usergroup = $this->Usergroups->get($cmsuser->cmsuser_usergroups[0]['usergroup_id']);
            $this->Flash->error(__('The user is assigned to a usergroup ' . $usergroup->group_name .'. So could not be deleted.'));
        }

        return $this->redirect(['action' => 'index']);
    }


    public function addmembership($id = null)
    {

        $this->request->allowMethod(['post', 'delete']);

        $table_user_groups_user = TableRegistry::get("CmsuserUsergroups");

        $selectedusergroups = $table_user_groups_user->find('all')->where(['cms_user_id' => $id, 'usergroup_id' => CUSTOMER_USER_GROUP_ID])->toArray();


        if (empty($selectedusergroups)) {

            if ($this->createRelationCmsuserUserGroup($id, CUSTOMER_USER_GROUP_ID)) {
                $activeStatus = STATUS_ACTIVE;

                $this->loadModel('LetterEmailSchedules');
                $this->loadModel('FaxNumbers');
                $this->loadModel('AutomationSchedules');
                $this->loadModel('AutomationScheduleExports');
                $this->Cmsusers->setIsActive($id, $activeStatus);
                $this->LetterEmailSchedules->setIsActiveByMemberId($id, $activeStatus);
                $this->FaxNumbers->setIsActiveByMemberId($id, $activeStatus);
                $this->AutomationSchedules->setIsActiveByMemberId($id, $activeStatus);
                $this->AutomationScheduleExports->setIsActiveByMemberId($id, $activeStatus);

                $this->Flash->success(__('The membership has been assigned successfully.'));
            } else {
                $this->Flash->error(__('The membership could not be assigned successfully. Please, try again.'));
            }

        } else {
            $this->Flash->error(__('The membership already has  been assgined to the user.'));
        }

        return $this->redirect(['action' => 'index']);
    }

    public function revokemembership($id = null)
    {
        $this->request->allowMethod(['post', 'delete']);

        $table_user_groups_user = TableRegistry::get("CmsuserUsergroups");

        $selectedusergroups = $table_user_groups_user->find('all')->where(['cms_user_id' => $id, 'usergroup_id' => CUSTOMER_USER_GROUP_ID])->toArray();

        if (!empty($selectedusergroups)) {

            if ($table_user_groups_user->deleteAll(['cms_user_id' => $id, 'usergroup_id' => CUSTOMER_USER_GROUP_ID])) {
                $inactiveStatus = STATUS_NOT_ACTIVE;

                $this->loadModel('LetterEmailSchedules');
                $this->loadModel('FaxNumbers');
                $this->loadModel('AutomationSchedules');
                $this->loadModel('AutomationScheduleExports');
                $this->Cmsusers->setIsActive($id, $inactiveStatus);
                $this->LetterEmailSchedules->setIsActiveByMemberId($id, $inactiveStatus);
                $this->FaxNumbers->setIsActiveByMemberId($id, $inactiveStatus);
                $this->AutomationSchedules->setIsActiveByMemberId($id, $inactiveStatus);
                $this->AutomationScheduleExports->setIsActiveByMemberId($id, $inactiveStatus);

                $this->Flash->success(__('The membership has been revoked successfully.'));
            } else {
                $this->Flash->error(__('The membership could not be revoked. Please, try again.'));
            }

        } else {
            $this->Flash->error(__('The user is not a member yet!.'));
        }

        return $this->redirect(['action' => 'index']);
    }

    public function pausemembership($id = null)
    {

        $this->request->allowMethod(['post', 'delete']);

        $table_user_groups_user = TableRegistry::get("CmsuserUsergroups");

        $selectedusergroups = $table_user_groups_user->find('all')->where(['cms_user_id' => $id, 'usergroup_id' => CUSTOMER_USER_GROUP_ID])->toArray();

        $cmsuser = $this->Cmsusers->find()->where(['id'=>$id])->first();

        $operation_type = 'paused';

        if (!empty($selectedusergroups)) {

                $activeStatus = STATUS_PAUSE_MEMBERSHIP;

                if($cmsuser->is_active == 2){
                    $operation_type = 'assigned';
                    $activeStatus = STATUS_ACTIVE;
                }

                $this->loadModel('LetterEmailSchedules');
                $this->loadModel('FaxNumbers');
                $this->loadModel('AutomationSchedules');
                $this->loadModel('AutomationScheduleExports');
                $this->Cmsusers->setIsActive($id, $activeStatus);
                $this->LetterEmailSchedules->setIsActiveByMemberId($id, $activeStatus);
                $this->FaxNumbers->setIsActiveByMemberId($id, $activeStatus);
                $this->AutomationSchedules->setIsActiveByMemberId($id, $activeStatus);
                $this->AutomationScheduleExports->setIsActiveByMemberId($id, $activeStatus);

                $message = 'The membership has been '.$operation_type.' successfully.';

                $this->Flash->success(__($message));

        } else {
            $message = 'The membership already has  been '.$operation_type.' to the user.';
            $this->Flash->error(__($message));
        }

        return $this->redirect(['action' => 'index']);
    }


    public function bulkAction()
    {
        $this->request->allowMethod(['post', 'delete']);
        $selectedUsers = $this->request->data('selected_content');
        $bulkAction = $this->request->data('bulk_action');

        if ($bulkAction == BULK_ACTION_DELETE) {
            if ($selectedUsers == "")
                return $this->redirect(['action' => 'index']);
            $usersToDelete = explode(',', $selectedUsers);
            $error = $this->deleteAll($usersToDelete);
            if (!$error) {
                $this->Flash->success(__('All the selected users has been deleted.'));
            } else {
                $this->Flash->error($error);
            }
        }

        return $this->redirect(['action' => 'index']);
    }

    private function deleteAll($users)
    {
        foreach ($users as &$user) {
            $user = str_replace('content_', '', $user);

            $cmsuser = $this->Cmsusers->get($user, [
                'contain' => ['Companies', 'CmsuserUsergroups']
            ]);

            if (empty($cmsuser->cmsuser_usergroups)) {
                if (!($this->Cmsusers->updateAll(['status' => STATUS_NOT_ACTIVE], ['id' => $user]))) {
                    return (__('The user ' . $cmsuser->username . ' could not be deleted. Please, try again.'));
                }
            } else {
                return (__('The user ' . $cmsuser->username . ' is assigned to a usergroup so could not be deleted.'));
            }
        }
    }

    public function forgotPassword()
    {
        $this->viewBuilder()->layout('new_before_login');
        $this->set('msg', '');
        $this->set('errors', array());
        if ($this->request->is('post')) {

            $validator = new Validator();
            $validator
                ->requirePresence('email')
                ->notEmpty('email', 'Email field is required')
                ->add('email', 'validFormat', [
                    'rule' => 'email',
                    'message' => 'E-mail must be valid'
                ]);

            $errors = $validator->errors($this->request->data(), false);

            if (empty($errors)) {

                $email = $this->request->data('email');
                $user = $this->Cmsusers->find('all')->where(['email' => $email])->first();

                if (!empty($user)) {
                    $token = $this->generateRandomString('20');
                    $query = $this->Cmsusers->query();
                    $query->update()->set(['reset_password_token' => $token])->where(['id' => $user->id])->execute();

                    $emailData['username'] = $user->username;
                    $emailData['pin'] = base64_encode($user->id);
                    $emailData['token'] = base64_encode($token);

                    $reset_url = APP_SERVER_HOST_URL_DEFAULT . '/reset_password/' . $emailData['pin'] . '/' . $emailData['token'];

                    //echo $reset_url;exit;
                    $template_content = array(
                        'username' => $emailData['username'],
                        'reset_url' => $reset_url,
                        'pin' => $emailData['pin'],
                        'token' => $emailData['token']
                    );

                    $personalize =  $this->Personalizes->find()->where(['member_id'=> DEFAULT_MEMBER_ID])->first();
                    $this->sendEmail(MANDRILL_TEMPLATE_FORGOT_PASSWORD, $template_content, $user->email, 'Forgot Password', "", $personalize);
                    //var_dump($result);exit;
                    $this->Flash->success(__('An email has been successfully sent to your email with instructions to reset your password.'));

                    return $this->redirect('/forgot_password');
                }
                else {
                    $this->Flash->loginError(__('Email id you entered is not registered with us. Please try again.'));
                }
            } else {
                $this->set('errors', $errors);
            }
        }

    }

    // function to reset password
    public function resetPassword($uid=null, $token=null)
    {
        $this->viewBuilder()->layout('new_before_login');
        $this->set('errors', array());

        if(!empty($uid) && !empty($token)) {
            $uid = base64_decode($uid);
            $token = base64_decode($token);

            $user = $this->Cmsusers->find('all')->where(['id' => $uid, 'reset_password_token' => $token])->first();

            if (!empty($user)) {

                if ($this->request->is('post')) {
                    $validator = new Validator();
                    $validator
                        ->requirePresence('password')
                        ->notEmpty('password', 'Password field is required')
                        ->add('password', [
                            'length' => [
                                'rule' => ['minLength', 4],
                                'message' => 'Password need to be at least 4 characters long',
                            ]
                        ])
                        ->requirePresence('confirm_password')
                        ->notEmpty('confirm_password', 'Confirm password field is required')
                        ->add('confirm_password', [
                            'match' => [
                                'rule' => ['equalTo', $this->request->data('password')],
                                'message' => 'Password confirmation does not match password.'
                            ]
                        ]);
                    $errors = $validator->errors($this->request->data(), false);

                    if (empty($errors)) {
                        $query = $this->Cmsusers->query();
                        $query->update()->set(['reset_password_token' => '', 'password' => md5($this->request->data('password'))])->where(['id' => $user->id])->execute();
//                    $forumUtil = new forumUtils();
//                    $forumUtil->updateForumPasswordById($user->id, $this->request->data('password'));

                        $this->Flash->success(__('Password reset successful'));
                        return $this->redirect('/login');


                    } else {
                        $this->set('errors', $errors);
                    }
                } else {
                    $this->setHeaderFooterByDomain();
                    if (isset($_SESSION['client_logo_path']) && !empty($_SESSION['client_logo_path'])) {
                        $this->set('cmsuser', $_SESSION['client_logo_path']);
                    }
                }
            } else {
                $errors['bad_request'] = __('reset_password_error', '<a href="' . Router::url(['controller' => 'Cmsusers', 'action' => 'forgotPassword']) . '">');
                $this->set('errors', $errors);
            }
        }else {

            return $this->redirect('/forgot_password');
        }
    }

    private function redirectToWWW()
    {

        $domain = $_SERVER[HTTP_HOST];
        $protocol = isset($_SERVER['HTTPS']) ? 'https' : 'http';
        $subDomain = 'www';
        // echo $domain.' == '.$protocol.' == '.$subDomain; die;

        if (($domain == PRODUCTION_DOMAIN) && ($protocol == 'http')) {
            $redirectURL = "https://" . PRODUCTION_DOMAIN;
            return $this->redirect($redirectURL);
        } else {
            $isWWW = strpos($_SERVER[REQUEST_URI], $subDomain);
            if ($isWWW === false && $protocol == 'http') {
                $redirectURL = $protocol . "://" . $subDomain . '.' . $domain;
                return $this->redirect($redirectURL);
            }
        }
    }



    public function login()
    {
        $this->viewBuilder()->layout('new_before_login');
//        $this->viewBuilder()->layout('outside/layout');

        $this->set('msg', '');
        $this->set('errors', array());
        $actual_url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

        if ($this->Auth->user()) {
            $params_array = $this->getParamFromURL($actual_url);
            if (isset($params_array['client_id']) && $params_array['client_id'] > 0) {
                return $this->redirect(['controller' => 'Client', 'action' => 'edit', $params_array['client_id']]);
            }
        }
        $this->setRedirectUrl();

        if ($this->request->is('post')) {

            $user = $this->Auth->identify();
            $email = $this->request->data['email'];
            $password = md5($this->request->data['password']);
            if (empty($user) && !empty($email) && !empty($password)) {
                $user = $this->Cmsusers->find()->where(['email' => $email, 'backup_old_password' => $password, 'is_allow_defult_pass' => 1])->first();
                if (!empty($user)) {
                    $user = json_decode(json_encode($user), true);
                }
            }

            // paused user return to login

            if($user['is_active'] == 2)
            {
                $this->Flash->loginError('Please, contact your administrator.');
                return ;
            }

            if ($user) {

                // if membership is revoked member id redirected to the login page
                $this->isUserMembershipActive($user['id']);

                $parent_cms_user_id = $user['parent_cms_user_id'];
                $user_type = $user['user_type'];

                // 1 for cmsuser Type
                if ($parent_cms_user_id == 0) {

                    $this->loadModel('VideoSettings');
                    $this->loadModel('Cmsusers');

                    if ($user['is_trial_user'] == 1) {

                        $this->loadModel('Settings');
                        $this->loadModel('App');
                        $setting = $this->Settings->getCurrentSettings();
                        $total_trial_days = $this->App->daysBetween($user['created_on'], $this->App->getSystemCurrentTimeStamp());

                        if ($total_trial_days > $setting['limited_time_count']) {
                            $this->Flash->loginError('Your trial account has been expired.');
                            $_SESSION['is_expired'] = true;
                            return $this->redirect($this->referer());
                        }
                    }
                    else{
                        $_SESSION["adminType"] = 1;
                    }
                    $this->Cmsusers->setLoginTime($user['id']);
                    $this->Auth->setUser($user);
                    $_SESSION['userType'] = 1;
                    $this->memberPermissionSet($user);

                    return $this->redirect($this->Auth->redirectUrl());

                }
                else {

                    $staffUserArray = [
                        'id' => $user['parent_cms_user_id'],
                        'user_id' => $user['id'],
                        'email' => $user['email'],
                        'is_first_login' => $user['is_first_login'],
                        'created_on' => $user['created_on'],
                        'is_employee_to_member' => $user['user_type'] == 1 ? true : false
                    ];
                    $access_controllerArray = array();
                    $id = $user['crm_contact_user_id'];

                    if ($user_type == 1) {

                        $this->loadModel('Crmuserhascontroller');
                        $crm_controllers = $this->Crmuserhascontroller->find()->contain(['Controllers'])->where(['Crmuserhascontroller.crmuser_id' => $id])->toArray();
                        //pr($controllers);exit;
                        foreach ($crm_controllers as $controller) {
                            $controllersArray = [
                                'module_name' => $controller->controller->module_name,
                                'controller_name' => $controller->controller->contrloller_name,
                                'controller_url' => $controller->controller->controller_url,
                                'controller_icon' => $controller->controller->controller_icon
                            ];
                            $access_controllerArray[] = $controllersArray;

                        }


                    } else if ($user_type == 2) {

                        $this->loadModel('ContactHasController');
                        $contact_controllers = $this->ContactHasController->find()->contain(['Controllers'])->where(['ContactHasController.contact_id' => $id])->toArray();
                        //pr($controllers);exit;
                        foreach ($contact_controllers as $controller) {
                            $controllersArray = [
                                'id' => $controller->controller->id,
                                'module_name' => $controller->controller->module_name,
                                'controller_name' => $controller->controller->contrloller_name,
                                'controller_url' => $controller->controller->controller_url,
                                'controller_icon' => $controller->controller->controller_icon
                            ];
                            $access_controllerArray[] = $controllersArray;

                        }

                    }
                    $this->Auth->setUser($staffUserArray);
                    // $this->setPersonalize();    //commented by pranak
                    $_SESSION['userType'] = 4;
                    $_SESSION['access_controller'] = $access_controllerArray;

                    //pr($_SESSION);exit;
                    $redirectController = $_SESSION['access_controller'][0]['controller_name'];
                    $this->setClientStatus(); // get client status list
                    return $this->redirect(['controller' => $redirectController, 'action' => 'index']);
                }
            }

        } else {
            $actual_url = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        }

    }


    private function getParamFromURL($url)
    {
        $paramsArray = explode("/", $url);
        $array_ids = [];
        if (!empty($paramsArray)) {
            foreach ($paramsArray as $arr) {
                if (!empty($arr) && $arr > 0) {
                    $array_ids[] = $arr;
                }
            }
        }
        $cmsuser_id = "";
        $client_id = "";
        if (isset($array_ids[0]) && !empty($array_ids[0])) {
            $cmsuser_id = $array_ids[0];
        }

        if (isset($array_ids[1]) && !empty($array_ids[1])) {
            $client_id = $array_ids[1];
        }

        return ['cmsuser_id' => $cmsuser_id, 'client_id' => $client_id];
    }


    private function setPersonalize()
    {
        $domain = $this->getCurrentDomain();
        $cmsUserId = $this->Auth->user("id");
        $this->loadModel('Personalizes');

        $personalize = $this->Personalizes->getPersonalizeByMemberId($cmsUserId);
        //$personalize = $this->Personalizes->getPersonalizeByDomain($domain);

        if (!empty($personalize)) {
            $this->manageDomainName($personalize, 1); // 1 for isSetDefault
            $_SESSION['personalize'] = $personalize;
            if (!empty($personalize->footer)) {
                $this->request->session()->write('Auth.User.member_footer', $personalize->footer);
            }
        } else {
            $this->manageDomainName(null, 1);
        }
        $cmsuser = $this->Cmsusers->find()->where(['id' => $cmsUserId])->first();
        if (!empty($cmsuser)) {
            $_SESSION['client_logo_path'] = $cmsuser->logo;
        }
        //pr($_SESSION);exit;
        //get personalize object from personalize table by $cmsuser_id
        //if record not empty, set personalize object in se
    }

    private function setRedirectUrl()
    {      // for type wise redirect
        if (isset($_SESSION['userType'])) {
            if (($_SESSION['userType'] == CMS_USER_INDICATOR) || ($_SESSION['userType'] == STAF_USER_INDICATOR)) {
                return $this->redirect($this->Auth->redirectUrl());
            } else if ($_SESSION['userType'] == CONTACT_USER_INDICATOR) {
                $redirectController = 'Clientdashboard';
                return $this->redirect(['controller' => $redirectController, 'action' => 'index']);
            } else if ($_SESSION['userType'] == CRM_USER_INDICATOR || $_SESSION['userType'] == 2) {
                $redirectController = 'AffiliateDashboard';
                return $this->redirect(['controller' => $redirectController, 'action' => 'index']);
            }
        }
    }


    public function editProfile()
    {
        $id = $this->Auth->user('id');

        $cmsuser = $this->Cmsusers->get($id, [
            'contain' => []
        ]);
        if ($this->request->is(['patch', 'post', 'put'])) {
            //pr($this->request->data());exit;
            if (!empty($this->request->data['img_path']['name'])) {
                $id = $this->request->session()->read('Auth.User.id');
                if (!empty($this->request->data['previous_img_path'])) {
                    unlink(WWW_ROOT . '/' . $this->request->data['previous_img_path']);
                }
                if (!is_dir('media/companies/' . $id)) {
                    mkdir('media/companies/' . $id, 0777, true);
                }
                $imagedes = $this->request->webroot . 'webroot/media/companies/' . $id;
                //$imagepath = 'webroot/media/companies/'.$last_insert_id.'/'.$this->request->data['img_path']['name'];
                $imagepath = 'media/companies/' . $id . '/' . $this->request->data['img_path']['name'];
                //echo $imagepath;exit;
                $file = $this->request->data['img_path']; //put the data into a var for easy use

                $ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
                $arr_ext = array('jpg', 'jpeg', 'gif', 'png'); //set allowed extensions

                //only process if the extension is valid
                if (in_array($ext, $arr_ext)) {
                    //do the actual uploading of the file. First arg is the tmp name, second arg is
                    //where we are putting it
                    move_uploaded_file($_FILES["img_path"]["tmp_name"], WWW_ROOT . 'media/companies/' . $id . '/' . basename($_FILES['img_path']['name']));
                } else {
                    $this->Flash->error(__('Profile Picture is not in right format.Please, try again.'));
                    return $this->redirect(['action' => 'edit']);
                }
                $this->request->data['img_path'] = $imagepath;
                $this->request->session()->write('Auth.User.img_path', $imagepath);
            } else {
                $this->request->data['img_path'] = $this->request->data['previous_img_path'];
            }
            $this->request->session()->write('Auth.User.username', $this->request->data['username']);

            $cmsuser = $this->Cmsusers->patchEntity($cmsuser, $this->request->data);

            if ($this->Cmsusers->save($cmsuser)) {
                $this->Flash->success(__('Profile has been updated.'));
                $this->redirect('/dashboard');
            } else {
                $this->Flash->error(__('The Profile could not be saved. Please, try again.'));
            }
        }

        // $this->userIPreset($id);
//        $packageInfo = $this->getUserPackages($id);
        //pr($cmsuser);exit;
        $this->set('packageInfo', $packageInfo);

        $user_permissions = $this->request->session()->read('user_permissions');
        $this->set('user_permission', $user_permissions);
        $this->set('cmsuser', $cmsuser);
        $this->set('_serialize', ['cmsuser']);
        $this->viewBuilder()->layout("custom_layout");
    }

    private function userIPreset($id)
    {
        $cmsuser = $this->Cmsusers->get($id, [
            'contain' => []
        ]);
        $cmsuser->ip = '';
        $this->Cmsusers->save($cmsuser);
    }

    /*
    private function getUserPackages($user_id)
    {
        $table_member_packages = TableRegistry::get("MemberPackages");
        $memberPackage = $table_member_packages->find('all')
            ->where(['MemberPackages.member_id' => $user_id])
            ->contain(['Packages'])
            ->order('MemberPackages.id desc')
            // ->contain(['Cmsusers', 'Packages'])
            ->toArray();
        return $memberPackage;
    }
    */

    public function logout($message = 'You are now logged out.')
    {

        $this->logoutForumUser();
        $session = $this->request->session();
        $session->delete("user_permissions");
        $session->delete('permission_version');
        $session->delete('modules');
        $session->delete('access_controller');
        $session->delete('userType');
        //  $session->delete('adminType');
        $session->delete('outstandingSum');
        $session->delete('paid');
        $session->delete('itemSum');

        $client_logo_path = $_SESSION['client_logo_path'];
        $referer_domain = $_SESSION['referer_domain'];
        $personalize = $_SESSION['personalize'];


        unset($_SESSION);
        unset($_SESSION['APP_SERVER_HOST_URL']);
        unset($_SESSION['dropbox_app_key']);
        unset($_SESSION['dropbox_app_secret']);
        unset($_SESSION['dropbox_access_token']);
        $session->destroy();


        if (isset($_SESSION['cmsuser_url'])) {
            $cmsuser_url = $_SESSION['cmsuser_url'];
            $session->delete('cmsuser_url');
            $this->Flash->loginSuccess('You are now logged out.');
            //return $this->redirect(['controller'=>'Cmsusers', 'action' => 'login']);
        } else {

            $this->Flash->loginSuccess($message);
            $this->Auth->logout();
            if (!empty($referer_domain) && $referer_domain != SITE_DOMAIN) {
                $_SESSION['client_logo_path'] = $client_logo_path;
                $_SESSION['personalize'] = $personalize;
                $_SESSION['referer_domain'] = $referer_domain;
                $_SESSION['logout'] = 1;
            }
            if (isset($_GET['member_id'])) {
                //return $this->redirect('/'.$_GET['member_id']);
            } else {
                if (!empty($personalize)) {
                    $redirect_url = $personalize->domain_type;
                    if ($personalize->is_www == 1) {
                        $redirect_url .= "www.";
                    }
                    $redirect_url .= $personalize->domain;
                    //return $this->redirect($redirect_url);
                } else {
                    //return $this->redirect(['action' => 'login']);
                }
            }
        }

        return $this->redirect(['controller' => 'Cmsusers', 'action' => 'login']);
//        if($_SESSION['userType']==1){
//            return $this->redirect($this->Auth->logout());
//        }else if($_SESSION['userType']==2){
//            $session->delete("access_controller");
//            $session->delete("userType");
//            return $this->redirect(['controller'=>'Cmsusers', 'action' => 'login']);
//
//        }
    }


    private function logoutForumUser()
    {

        $cookie = "Set-Cookie: mybbuser=; expires=" . date('Y-m-d') . "; path=" . MYBB_COOKIE_PATH;
        if (!empty(MYBB_COOKIE_DOMAIN)) {
            $cookie .= "; domain= " . MYBB_COOKIE_DOMAIN;
        }
        header($cookie, false);
    }


    public function checkArtistRegistered()
    {

        $this->viewBuilder()->layout(FALSE);
        //$user = $this->Cmsusers->find('all')->where(['fb_id' => $_POST['fb_id']])->first();
        $user = $this->Cmsusers->find('all')->where(['fb_id' => $_POST['fb_id']])->toArray();

        //print_r($user);

        if ($user[0]->id) {
            echo "ok";
        } else
            echo "no";

        die();
    }

    public function fbLogin($fb_id)
    {

        if ($fb_id) {
            $user = $this->Cmsusers->find('all')->where(['fb_id' => $fb_id, 'status' => 1])->toArray();

            $user_info['id'] = $user[0]->id;
            $user_info['language'] = $user[0]->language;
            $user_info['username'] = $user[0]->username;
            $user_info['email'] = $user[0]->email;
            $user_info['eset_password_token'] = $user[0]->eset_password_token;
            $user_info['status'] = $user[0]->status;
            $user_info['company_id'] = $user[0]->company_id;
            $user_info['created_on'] = $user[0]->created_on;
            $user_info['updated_on'] = $user[0]->updated_on;


            if ($user_info) {
                $this->Auth->setUser($user_info);
                return $this->redirect($this->Auth->redirectUrl());
            }
            $this->Flash->loginError('Your username or password is incorrect.');
            return $this->redirect('/');
        } else {
            $this->Flash->loginError('Your username or password is incorrect.');
            return $this->redirect('/');
        }

        $this->viewBuilder()->layout(FALSE);
        die();
    }

    public function fbLoginRegister($fb_id = NULL)
    {

        $companyTable = TableRegistry::get('Companies');

        $company = $companyTable->newEntity();

        $cmsUser = $this->Cmsusers->newEntity();

        $artistTable = TableRegistry::get('Artists');
        $artist = $artistTable->newEntity();
        $picture = false;

        if ($this->request->is('post')) {

            $company = $companyTable->patchEntity($company, $this->request->data('company'));
            $company = $this->fixCompanyForAdd($company);
            $company->logo = $this->request->data("uploaded_file");

            $timezone_offset = TableRegistry::get('timezones')->find('all')
                ->select(['utc_offset'])
                ->where(['id' => $_POST['company']['timezone']])->toArray();


            $company->timezone_value = $timezone_offset[0]->utc_offset;

            $cmsUser = $this->Cmsusers->patchEntity($cmsUser, $this->request->data('cmsuser'));
            $cmsUser = $this->fixUserForAdd($cmsUser);

            $companyErrors = $this->checkAndDisplayEntityErrors($company);
            $userErrors = $this->checkAndDisplayEntityErrors($cmsUser);

            $password = $this->request->data('cmsuser.password');

            if (!$companyErrors && !$userErrors) {

                $savedCompany = $companyTable->save($company);

                if ($savedCompany) {

                    //$this->Flash->success(__('The company has been saved.'));

                    $cmsUser['company_id'] = $savedCompany['id'];

                    if ($this->Cmsusers->save($cmsUser)) {

                        if ($this->insertSuperUserPermission($company, $cmsUser)) {

                            //$this->Flash->success(__('The super admin has been saved.'));
                            $this->Flash->success(__('Artist has been saved.'));

                            $artist = $artistTable->patchEntity($artist, $this->request->data('artist'));
//                            $picture = $this->request->data("uploaded_artist_file");
                            $artist->name_en = $savedCompany['name'];
                            $artist->picture = $savedCompany['logo'];

                            $artist = $this->createArtist($artist, $savedCompany['id']);

                            copy(WWW_ROOT . '/media/companies/' . $artist->picture, WWW_ROOT . '/media/artists/' . $artist->picture);
                            $this->createThumbnail($artist->picture, 'artists');

                            $artistErrors = $this->checkAndDisplayEntityErrors($artist);

                            $artist = $artistTable->save($artist);

                            if ($artist) {

                                $template_content = array(
                                    array(
                                        'name' => 'firstname',
                                        'content' => $cmsUser->username
                                    ),
                                    array(
                                        'name' => 'user_email',
                                        'content' => $cmsUser->email
                                    ),
                                    array(
                                        'name' => 'password',
                                        'content' => $password
                                    ),
                                    array(
                                        'name' => 'login_url',
                                        'content' => APP_SERVER_HOST_URL
                                    ));

                                $this->sendEmail(MANDRILL_TEMPLATE_USER_CREATION, $template_content, $cmsUser->email);

                                $this->Flash->success(__('An email has been sent to your specified email address.'));

                                //return $this->redirect(['action' => 'fbLoginRegister']);
                                return $this->redirect(['action' => 'login']);

                            } else {
                                $this->Flash->error(__('The Artist could not be saved. Please, try again'));
                            }
                            //return $this->redirect(['action' => 'fbLoginRegister']);
                        } else {
                            $this->Flash->error(__('The Artist could not be saved. Please, try again'));
                            $this->revertPermissions($company, $cmsUser);
                            $companyTable->delete($company);
                            $this->Cmsusers->delete($company);
                        }
                        return $this->redirect(['action' => 'fbLoginRegister']);
                    } else {
                        $companyTable->delete($company);
                        $this->Flash->error(__('The Artist could not be saved. Please, try again'));
                    }
                } else {
                    $this->Flash->error(__('The company could not be saved. Please, try again.'));
                }
            }
        }



        $this->set('countries', $this->getCountries());

        $timezones_array = TableRegistry::get('timezones')->find()->toArray();

        foreach ($timezones_array as $zone)
            $timezones[$zone->id] = $zone->time_zone . ' ' . $zone->utc_offset;

        $this->set('timezones', $timezones);

        $this->set('fb_id', $fb_id);

        $this->viewBuilder()->layout('fb_login_register');
    }

    private function insertSuperUserPermission($company, $cmsUser)
    {

        $rolesTable = TableRegistry::get('roles');
        $pagesTable = TableRegistry::get('pages');
        $userGroupsTable = TableRegistry::get('usergroups');
        $userGroupRolesTable = TableRegistry::get('usergroup_roles');
        $rolePagesTable = TableRegistry::get('role_pages');
        $userUserGroupsTable = TableRegistry::get('cmsuser_usergroups');
        /**
         * 1. create a role for that company into the table "roles"
         * 2. create a usergroup for that company into the table "usergroups"
         * 3. associate newly created usergroup and role into the table "usergroup_roles"
         * 4. Associate the pages to that role into the table "role_pages"
         * 5. Provide Artists and Groups Permission
         */
        $role = $rolesTable->newEntity();
        $role['title'] = $company['name'] . '-super-admin';
        $role['create_on'] = new DateTime();
        $role['modified_on'] = new DateTime();
        $role['status'] = 1;
        $role['company_id'] = $company['id'];

        $role = $rolesTable->save($role);
        if (!$role) {
            return false;
        }

        $userGroup = $userGroupsTable->newEntity();
        $userGroup['group_name'] = $company['name'] . '-super-admin-group';
        $userGroup['created_on'] = new DateTime();
        $userGroup['modified_on'] = new DateTime();
        $userGroup['status'] = 1;
        $userGroup['company_id'] = $company['id'];

        $userGroup = $userGroupsTable->save($userGroup);
        if (!$userGroup) {
            return false;
        }

        $userGroupRole = $userGroupRolesTable->newEntity();
        $userGroupRole['role_id'] = $role['id'];
        $userGroupRole['usergroup_id'] = $userGroup['id'];

        $userGroupRole = $userGroupRolesTable->save($userGroupRole);
        if (!$userGroupRole) {
            return false;
        }

        $userUserGroup = $userUserGroupsTable->newEntity();
        $userUserGroup['usergroup_id'] = $userGroup['id'];
        $userUserGroup['cms_user_id'] = $cmsUser['id'];

        $userUserGroup = $userUserGroupsTable->save($userUserGroup);
        if (!$userUserGroup) {
            return false;
        }

        $pagesWithPermission = $pagesTable->query('SELECT pages.id, pages.sub_module_id, pages.title')
            ->innerJoin('sub_modules', 'pages.sub_module_id = sub_modules.id')
            ->innerJoin('modules', 'sub_modules.module_id = modules.id')
            ->where('modules.id IN (' . ModuleConstants::ACCESS_CONTROL . ',' . ModuleConstants::CONTENT . ',' . ModuleConstants::ARTIST_AND_GROUPS . ')');

        foreach ($pagesWithPermission as $pageWithPermission) {
            $rolePage = $rolePagesTable->newEntity();

            $rolePage['role_id'] = $role['id'];
            $rolePage['page_id'] = $pageWithPermission['id'];
            if (!$rolePagesTable->save($rolePage)) {
                return false;
            }
        }

        $rolePage = $rolePagesTable->newEntity();
        $rolePage['role_id'] = $role['id'];
        $rolePage['page_id'] = PagesConstants::BASIC_SETTINGS;
        $rolePagesTable->save($rolePage);

//        $rolePage = $rolePagesTable->newEntity();
//        $rolePage['role_id'] = $role['id'];
//        $rolePage['page_id'] = PagesConstants::LIST_PAYMENT;
//        $rolePagesTable->save($rolePage);
//
//        $rolePage = $rolePagesTable->newEntity();
//        $rolePage['role_id'] = $role['id'];
//        $rolePage['page_id'] = PagesConstants::VIEW_PAYMENT_RECORD;
//        $rolePagesTable->save($rolePage);
//
//        $rolePage = $rolePagesTable->newEntity();
//        $rolePage['role_id'] = $role['id'];
//        $rolePage['page_id'] = PagesConstants::LIST_STAR_ACTIVITIES;
//        $rolePagesTable->save($rolePage);
//
//        $rolePage = $rolePagesTable->newEntity();
//        $rolePage['role_id'] = $role['id'];
//        $rolePage['page_id'] = PagesConstants::LIST_UNLOCK_ACTIVITIES;
//        $rolePagesTable->save($rolePage);
//
//        $rolePage = $rolePagesTable->newEntity();
//        $rolePage['role_id'] = $role['id'];
//        $rolePage['page_id'] = PagesConstants::VIEW_UNLOCK_ACTIVITY;
//        $rolePagesTable->save($rolePage);

        return true;
    }

    private function revertPermissions($company, $cmsUser)
    {
        $rolesTable = TableRegistry::get('roles');
        $role = $rolesTable->find('all')->where(['company_id' => $company['id']])->toArray()[0];

        $userGroupsTable = TableRegistry::get('usergroups');
        $userGroup = $userGroupsTable->find('all')->where(['company_id' => $company['id']])->toArray()[0];

        $rolePagesTable = TableRegistry::get('role_pages');
        $rolePagesTable->deleteAll(['role_id' => $role['id']]);

        $userUserGroupsTable = TableRegistry::get('cmsuser_usergroups');
        $userUserGroup = $userUserGroupsTable->find('all')->where(['cms_user_id' => $cmsUser['id']])->toArray();
        $this->log($userUserGroup);
        if (sizeof($userUserGroup) > 0) {
            $userUserGroupsTable->delete($userUserGroup[0]);
        }

        $userGroupRolesTable = TableRegistry::get('usergroup_roles');
        $userGroupRole = $userGroupRolesTable->find('all')->where(['usergroup_id' => $userGroup['id']])->toArray();
        if (sizeof($userGroupRole) > 0) {
            $this->log($userGroupRole);
            $userGroupRolesTable->delete($userGroupRole[0]);
        }

        $userGroupsTable->delete($userGroup);
        $rolesTable->delete($role);
        $cmsUsersTable = TableRegistry::get('cmsusers');
        $cmsUsersTable->deleteAll(['company_id' => $company['id']]);
    }

    public function uploadPicture($type = 'companies')
    {

//        if ($this->Auth->user()) {
//            $user_id = $this->Auth->user()['id'];

        if ($this->request->is('post')) {

            $data = $this->request->data;
            $resp = array();

            if (!empty($data['doc_file']['name'])) {
                $file = $data['doc_file']; //put the data into a var for easy use

                $ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
                $image_ext = array('jpg', 'jpeg', 'gif', 'bmp', 'png');
                $not_image = '';

                //only process if the extension is valid
                if (in_array($ext, $image_ext)) {

                    $curr_time = date('Ymdhis');
                    $new_file_name = $curr_time . '.' . $ext;
                    $mediaPath = '/media/' . $type . '/' . $new_file_name;

                    if (move_uploaded_file($file['tmp_name'], WWW_ROOT . $mediaPath)) {
                        $resp['file_name'] = $new_file_name;
                        echo json_encode($resp);
                    } else {
                        echo 'error';
                    }
                } else {
                    $not_image = 'yes';
                }


                if ($not_image == 'yes') {
                    echo 'not_allowed';
                }
            }
        }
        // }
        exit;
    }

    public function removeMedia()
    {

//        if ($this->Auth->user()) {
//            $this->glbl();
        $f_type = $this->request->data('f_type');
        $prev_name = $this->request->data('prev_name');
        $f_name = $this->request->data('f_name');
        $file_url = '';
        if ($f_type == '1') {
            $file_url = substr(WWW_ROOT, '0', '-1') . '/videos/' . $f_name;
            $prev_url = substr(WWW_ROOT, '0', '-1') . '/previews/' . $prev_name;
            unlink($prev_url);
        } else if ($f_type == '2') {
            $file_url = substr(WWW_ROOT, '0', '-1') . '/audios/' . $f_name;
        } else if ($f_type == '3') {
            $file_url = substr(WWW_ROOT, '0', '-1') . '/images/' . $f_name;
        } else if ($f_type == '4') {
            $file_url = substr(WWW_ROOT, '0', '-1') . '/media/companies/' . $f_name;
        }
        unlink($file_url);
        //}
        exit;
    }

    public function uploadArtistPicture($type = 'artists', $picture = NULL)
    {
//        if ($this->Auth->user()) {
//            $data = $this->glbl();
//            $user_id = $data['logged_user_info']['id'];

        if ($this->request->is('post')) {

            $data = $this->request->data;
            $resp = array();

            if (!empty($data['doc_artist_file']['name'])) {
                $file = $data['doc_artist_file']; //put the data into a var for easy use

                $ext = substr(strtolower(strrchr($file['name'], '.')), 1); //get the extension
                $image_ext = array('jpg', 'jpeg', 'png');
                $not_image = '';

                //only process if the extension is valid
                if (in_array($ext, $image_ext)) {
                    $curr_time = date('Ymdhis');
                    $new_file_name = $curr_time . '.' . $ext;
                    $mediaPath = '/media/' . $type . '/' . $new_file_name;

                    if (move_uploaded_file($file['tmp_name'], WWW_ROOT . $mediaPath)) {
                        $this->createThumbnail($new_file_name, $type);
                        $resp['file_name'] = $new_file_name;
                        echo json_encode($resp);
                    } else {
                        echo 'error';
                    }
                } else {
                    $not_image = 'yes';
                }


                if ($not_image == 'yes') {
                    echo 'not_allowed';
                }
            }
        }
        //}
        exit;
    }

    public function removeArtistMedia()
    {
//        if ($this->Auth->user()) {
//            $this->glbl();
        $f_type = $this->request->data('f_type');
        $prev_name = $this->request->data('prev_name');
        $f_name = $this->request->data('f_name');
        $file_url = '';
        if ($f_type == '1') {
            $file_url = substr(WWW_ROOT, '0', '-1') . '/videos/' . $f_name;
            $prev_url = substr(WWW_ROOT, '0', '-1') . '/previews/' . $prev_name;
            unlink($prev_url);
        } else if ($f_type == '2') {
            $file_url = substr(WWW_ROOT, '0', '-1') . '/audios/' . $f_name;
        } else if ($f_type == '3') {
            $file_url = substr(WWW_ROOT, '0', '-1') . '/images/' . $f_name;
        } else if ($f_type == '4') {
            $file_url = substr(WWW_ROOT, '0', '-1') . '/media/artists/' . $f_name;
            $file_url_thumb = substr(WWW_ROOT, '0', '-1') . '/media/artists/thumbnails/' . $f_name;
        }
        unlink($file_url);
        unlink($file_url_thumb);
        //}
        exit;
    }

    function createThumbnail($filename, $type)
    {

        //require 'config.php';

        copy(WWW_ROOT . '/media/' . $type . '/' . $filename, WWW_ROOT . '/media/' . $type . '/' . 'thumbnails/' . $filename);

        $path_to_image_directory = WWW_ROOT . '/media/' . $type . '/' . 'thumbnails/';

        if (preg_match('/[.](jpg)$/', $filename)) {
            $im = imagecreatefromjpeg($path_to_image_directory . $filename);
        } else if (preg_match('/[.](gif)$/', $filename)) {
            $im = imagecreatefromgif($path_to_image_directory . $filename);
        } else if (preg_match('/[.](png)$/', $filename)) {
            $im = imagecreatefrompng($path_to_image_directory . $filename);
        }

        $ox = imagesx($im);
        $oy = imagesy($im);

        $nx = WIDTH_OF_IMAGE;
        $ny = floor($oy * (WIDTH_OF_IMAGE / $ox));

        $nm = imagecreatetruecolor($nx, $ny);

        imagecopyresampled($nm, $im, 0, 0, 0, 0, $nx, $ny, $ox, $oy);

        imagejpeg($nm, $path_to_image_directory . $filename);


        return true;
    }

    public function termsService()
    {
        $this->viewBuilder()->layout('terms_service');
    }

    private function checkAndDisplayEntityErrors($entity)
    {
        $entityErrors = $entity->errors();
        foreach ($entityErrors as $key => $value) {
            foreach ($entityErrors[$key] as $errorKey => $errorValue) {
                $this->Flash->error($errorValue);
            }
        }
        return $entityErrors;
    }

    private function createArtist($artist, $com_id)
    {
        //       $artist['country'] = $this->getCountries()[$artist['country']];
        $artist['company_id'] = $com_id;
        $artist['status'] = 0;
        //$artist['date_of_birth'] = Time::parse($artist['date_of_birth']);
        return $artist;
    }

    private function fixCompanyForAdd($company)
    {
        $company['status'] = 0;
        $company['country'] = $this->getCountries()[$company['country']];
        $company['created_on'] = new DateTime();
        $company['modified_on'] = new DateTime();
        return $company;
    }

    private function fixUserForAdd($cmsUser)
    {
        $cmsUser['created_on'] = new DateTime();
        $cmsUser['updated_on'] = new DateTime();
        $cmsUser['status'] = 0;
        return $cmsUser;
    }

    /**
     * @param $cmsuser
     * @return \Cake\Datasource\EntityInterface
     */
    private function createUser($cmsuser)
    {
        $this->loadModel('App');
        $current_date_time = $this->App->getSystemCurrentTimeStamp();
        $cmsuser = $this->Cmsusers->patchEntity($cmsuser, $this->request->data);
        $cmsuser->reset_password_token = '';
        $cmsuser->created_on = $current_date_time;
        $cmsuser->updated_on = $current_date_time;
        $cmsuser->status = STATUS_ACTIVE;
        $cmsuser->last_active_date = $current_date_time;
        $cmsuser->company_id = $this->Auth->user('company_id');
        return $cmsuser;
    }

    public function emailSent()
    {
        $mandrill = new Mandrill('pfkbceAO9GboPTWRl4h_mw');

        $template_content = array(
            array(
                'name' => 'firstname',
                'content' => 'Abu'
            ),
            array(
                'name' => 'user_email',
                'content' => 'dipcse20@gmail.com'
            ),
            array(
                'name' => 'password',
                'content' => 'dip!12345'
            ),
            array(
                'name' => 'login_url',
                'content' => APP_SERVER_HOST_URL
            ));

        $to = array(array('email' => 'dipcse20@gmail.com'));

        $this->sendEmail(MANDRILL_TEMPLATE_USER_CREATION, $template_content, $to);
        die();
    }

    public function getCountries()
    {
        return ["Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica",
            "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain",
            "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegowina",
            "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory", "Brunei Darussalam", "Bulgaria", "Burkina Faso",
            "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde", "Cayman Islands", "Central African Republic", "Chad", "Chile",
            "China", "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Congo", "Congo, the Democratic Republic of the",
            "Cook Islands", "Costa Rica", "Cote d'Ivoire", "Croatia (Hrvatska)", "Cuba", "Cyprus", "Czech Republic", "Denmark", "Djibouti",
            "Dominica", "Dominican Republic", "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia",
            "Ethiopia", "Falkland Islands (Malvinas)", "Faroe Islands", "Fiji", "Finland", "France", "France Metropolitan", "French Guiana",
            "French Polynesia", "French Southern Territories", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece",
            "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Heard and Mc Donald Islands",
            "Holy See (Vatican City State)", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran (Islamic Republic of)",
            "Iraq", "Ireland", "Israel", "Italy", "Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea, Democratic People's Republic of",
            "Korea, Republic of", "Kuwait", "Kyrgyzstan", "Lao, People's Democratic Republic", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libyan Arab Jamahiriya",
            "Liechtenstein", "Lithuania", "Luxembourg", "Macau", "Macedonia, The Former Yugoslav Republic of", "Madagascar", "Malawi", "Malaysia", "Maldives",
            "Mali", "Malta", "Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia, Federated States of",
            "Moldova, Republic of", "Monaco", "Mongolia", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal",
            "Netherlands", "Netherlands Antilles", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island",
            "Northern Mariana Islands", "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines",
            "Pitcairn", "Poland", "Portugal", "Puerto Rico", "Qatar", "Reunion", "Romania", "Russian Federation", "Rwanda", "Saint Kitts and Nevis",
            "Saint Lucia", "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal",
            "Seychelles", "Sierra Leone", "Singapore", "Slovakia (Slovak Republic)", "Slovenia", "Solomon Islands", "Somalia", "South Africa",
            "South Georgia and the South Sandwich Islands", "Spain", "Sri Lanka", "St. Helena", "St. Pierre and Miquelon", "Sudan", "Suriname",
            "Svalbard and Jan Mayen Islands", "Swaziland", "Sweden", "Switzerland", "Syrian Arab Republic", "Taiwan, Province of China", "Tajikistan",
            "Tanzania, United Republic of", "Thailand", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan",
            "Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "United States Minor Outlying Islands",
            "Uruguay", "Uzbekistan", "Vanuatu", "Venezuela", "Vietnam", "Virgin Islands (British)", "Virgin Islands (U.S.)", "Wallis and Futuna Islands",
            "Western Sahara", "Yemen", "Yugoslavia", "Zambia", "Zimbabwe"];
    }


    public function changeLanguage()
    {


        $language_key = $this->request->data["global_selected_language"];

        $country_value_array = array(
            "US" => "en_US",
            "SP" => "sp_SP",
        );

        $language = $country_value_array[$language_key];
        $url = $this->request->data["global_current_url"];

        if (empty($url)) {
            $url = APP_SERVER_HOST_URL;
        }

        $language = trim($language);
        $allowedLanguage = array("en_US", "sp_SP");

        if (!in_array($language, $allowedLanguage)) {
            $language = "en_US";
        }

        // $this->request->session()->write("Config.language",$language);
        // $this->Cookie->write("Config.expcount.language",$language);
        //dd($this->referer());
        //$language = "en_US";
        //ini_set('intl.default_locale', $language);
        $this->request->session()->write("Config.language", $language);
        //$this->Cookie->write("Config.expcount.language",$language);

        return $this->redirect($url);
        exit;
    }


    private function isCrmUser($email, $password)
    {

        $result = false;
        $crmuserstable = TableRegistry::get('crmusers');
        $crmuser = $crmuserstable->find()
            ->where(['email' => $email, 'hashed_password' => $password])->toArray();
        //dd($crmuser[0]);
        if (!empty($crmuser[0]) && $crmuser[0]->is_portal_access == 0 && $crmuser[0]->type == 2) {
            return ['status' => true,'is_login_disable'=>1, 'type' => $crmuser[0]->type];
        }
        // if membership is revoked member id redirected to the login page
        $cmsuser_id_from_crmuser = $crmuser[0]->cmsuser_id;
        if ($cmsuser_id_from_crmuser > 0) {
            $this->isUserMembershipActive($cmsuser_id_from_crmuser);
        }

        if ($crmuser) {

            $this->loadModel('VideoSettings');
            $video_settings = $this->VideoSettings->getVideoSettingsList();
            $_SESSION['url_list_by_section'] = $video_settings['url_list_by_section'];

            $id = $crmuser[0]->id;
            $cmsUserTable = TableRegistry::get('cmsusers');
            $cmsUser = $cmsUserTable->find()->where(['id' => $crmuser[0]->cmsuser_id])->first();


            $this->loadModel('Personalizes');


            $this->loadModel('MemberPackages');
            $result = $this->MemberPackages->hasEpicOrVelocityuser($crmuser[0]->cmsuser_id);
            if (!empty($result)) {

                $_SESSION['crm_has_velocity'] = false;
                if ($result['hasVelocity']) {
                    $_SESSION['crm_has_velocity'] = $crmuser[0]->has_velocity;
                }

                $_SESSION['has_super_rtg_user'] = false;

                if ($result['has_super_rtg_user'] && $crmuser[0]->has_rtg_access == 1) {
                    $_SESSION['has_super_rtg_user'] = true;
                }

                if($result['has_epic_for_employee']){
                    $_SESSION['has_epic_for_employee'] = true;
                }

            }
            else {
                $crmuser[0]->has_velocity = 0;
            }

            $is_employee_affiliate = false;
            if ($crmuser[0]->employee_id > 0) {
                $is_employee_affiliate = true;
            }

            $personalize = $this->Personalizes->getPersonalizeByMemberId($crmuser[0]->cmsuser_id);
            $crmUserInfo = [
                'id' => $crmuser[0]->cmsuser_id,
                'user_id' => $id,
                'name' => trim($crmuser[0]->first_name) . " " . trim($crmuser[0]->last_name),
                'email' => $crmuser[0]->email,
                'id' => $crmuser[0]->cmsuser_id,
                'is_first_login' => $crmuser[0]->is_first_login,
                'type' => $crmuser[0]->type,
                'is_show_all_clients' => $crmuser[0]->is_show_all_clients,
                'member_logo' => $cmsUser->logo,
                'member_email' => $cmsUser->email,
                'member_header' => $personalize->header,
                'member_footer' => $personalize->footer,
                'is_employee_affiliate' => $is_employee_affiliate,
                'has_analysis_analyzer' => $crmuser[0]->has_analysis_analyzer,
                'is_watched_video' => $cmsUser->is_watched_video,
                'member_time_zone' => $cmsUser->time_zone,
                'is_default_checked_saved_letter' => $cmsUser->is_default_checked_saved_letter,
                'is_admin_access' => $crmuser[0]->is_admin_access,
                'auto_assign_affiliate' => $crmuser[0]->auto_assign_affiliate
            ];

            $_SESSION['userType'] = 2;


            $member_id = $crmUserInfo['id'];
            /*
            if ($crmUserInfo['type'] == 2) {
                $this->loadModel('Clients');
                $client_list = $this->Clients->getAffiliateNewClientList($id);
                if (!empty($client_list)) {
                    $_SESSION['total_num_of_clients'] = count($client_list);
                }

            }*/

            /*
            if ($crmUserInfo['type'] == 1) {
                $this->loadModel('Sertg');
                $this->loadModel('LetterExtras');
                if ($crmUserInfo['is_show_all_clients'] == 1) {
                    $no_of_yellow = $this->Sertg->isNextSelectionNearestDay($member_id);
                    $epic_no_of_yellow = $this->LetterExtras->isNextSelectionNearestDay($member_id);
                } else {
                    $no_of_yellow = $this->Sertg->isNextSelectionNearestDayForEmployee($id);
                    $epic_no_of_yellow = $this->LetterExtras->isNextSelectionNearestDayForEmployee($id);
                }

                if ($epic_no_of_yellow > 0) {
                    $no_of_yellow += $epic_no_of_yellow;
                }
                if ($no_of_yellow > 0) {
                    $_SESSION['no_of_yellow'] = $no_of_yellow;
                    $_SESSION['is_warning'] = 1;
                }
            }
            */
            $access_controllerArray = array();
            $this->loadModel('Crmuserhascontroller');
            $controllers = $this->Crmuserhascontroller->find()->contain(['Controllers'])->where(['Crmuserhascontroller.crmuser_id' => $id])->toArray();


            foreach ($controllers as $controller) {
                if($controller->controller->id == SAVE_DOWNLOAD_PRINT_LETTER_CONTROLLER_ID){
                    $crmUserInfo['is_allow_store_letters'] = 1;
                }


                if($controller->controller->id == EDIT_CLIENT_CREDIT_REPORT_CONTROLLER_ID){
                    $crmUserInfo['is_allow_client_credit_report_edit'] = 1;
                }

                $controllersArray = [
                    'id' => $controller->controller->id,
                    'user_type' => $controller->controller->user_type,
                    'module_name' => $controller->controller->module_name,
                    'controller_name' => $controller->controller->contrloller_name,
                    'controller_url' => $controller->controller->controller_url,
                    'controller_icon' => htmlspecialchars($controller->controller->icon)
                ];

                if ($crmUserInfo['type'] == 2) {
                    if($controller->controller->user_type == 2) {
                        $access_controllerArray[] = $controllersArray;
                    }

                    if($controller->controller->id == CREDIT_REPORT_STATUS_CONTROLLER_ID){
                        $access_controllerArray[] = $controllersArray;
                    }
                }else{
                    $access_controllerArray[] = $controllersArray;
                }
            }

            //dd($access_controllerArray);
            $_SESSION['access_controller'] = $access_controllerArray;
            Permission::setPermissionForEmployee(EPICVELOCITY_CONTROLLER_ID);
            $this->Auth->setUser($crmUserInfo);
            if(Permission::isEmployeeAsAdmin()) {
                $this->memberPermissionSet($cmsUser);
            }
            $result = true;
        }

        return ['status' => $result, 'type' => $crmuser[0]->type];
    }


//    private function isCmsUsers($email,$password){
//        $result = false;
//
//        $cmsUserTable = TableRegistry::get('cmsusers');
//        $cmsusers = $cmsUserTable->find()->where(['email'=>$email,'password'=>$password]);
//
//        pr($cmsusers->toArray());exit;
//
//    }


    public function contactedit()
    {

        $id = $this->Auth->user('user_id');
        $this->loadModel('Crmusers');
        $contactUserTable = TableRegistry::get('contacts');
        $contactUser = $contactUserTable->get($id);

        if ($this->request->is('post')) {
            //pr($this->request->data());exit;
            $email = $this->request->data['email'];
            $password = $this->request->data['password'];
            $cpassword = $this->request->data['retype_password'];
            $previous_pass = $this->request->data['hash_pass'];
//            $contactUser->email  =$email ;
//            $contactUser->password  = md5($password);


            if ($password == $cpassword) {
                $contactUser->email = $email;
                if ($previous_pass == $password) {
                    $contactUser->password = $previous_pass;
                } else {
                    $contactUser->password = md5($password);
                }
                $checkEmail = true;
                if ($checkEmail) {

                    if ($contactUserTable->save($contactUser)) {
                        $this->Flash->success(__('Successfully Updated'));
                        return $this->redirect($this->referer());
                    } else {
                        $this->Flash->error(__('Please try again'));
                        return $this->redirect($this->referer());
                    }
                } else {
                    $this->Flash->error(__('The email already exist.'));
                    return $this->redirect($this->referer());
                }
            } else {
                $this->Flash->error(__('Password does not match'));
                return $this->redirect($this->referer());
            }

        }

        //pr($crmuser);exit;
        $this->set('crmuser', $contactUser);
        $this->viewBuilder()->layout("new_contact_user_dashboard");
    }


    private function createRelationCmsuserUserGroup($cmsuser_id, $usergroup_id)
    {
        $cmsuser_usergroupTable = TableRegistry::get('cmsuser_usergroups');
        $cmsuser_usergroup = $cmsuser_usergroupTable->newEntity();
        $cmsuser_usergroup->cms_user_id = $cmsuser_id;
        $cmsuser_usergroup->usergroup_id = $usergroup_id;
        if ($cmsuser_usergroupTable->save($cmsuser_usergroup)) {
            return true;
        }

        return false;
    }


    private function setForumLogin($username, $password)
    {
        //$password = '123456';
        $forum_user_script = '<script>
                                var data = new FormData();
                                data.append("action", "do_login");
                                data.append("url", "' . APP_SERVER_HOST_URL . 'forum/index.php");
                                data.append("quick_login", "1");
                                data.append("quick_username", "' . $username . '");
                                data.append("quick_password", "' . $password . '");
                                data.append("quick_remember", "yes");
                                data.append("submit", "Login");

                                var xhr = new XMLHttpRequest();
                                xhr.withCredentials = true;

                                xhr.addEventListener("readystatechange", function () {
                                  if (this.readyState === 4) {
                                    console.log(this.responseText);
                                  }
                                });

                                xhr.open("POST", "' . APP_SERVER_HOST_URL . 'forum/member.php");
                                xhr.send(data);
                            </script>';

        return $forum_user_script;
    }


    public function limitedTimePkgCheck()
    {
        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'), date('Y-m-d H:i:s'));
                if ($days > $required_days) {
                    $this->logout("Your " . $required_days . " day limited access has been exceeded.");
                }
            }
        }
    }

    /* Zapier api start */


    public function zapierAuth()
    {
        $response['success'] = false;
        $response['statuscode'] = -100;
        $response['data'] = [];
        $response['message'] = "No Data Found";

        if ($this->request->is('post')) {
            $this->getJsonData();
            $email = $this->data['email'];
            $password = $this->data['password'];
            $this->loadModel('Cmsusers');
            if ($member = $this->Cmsusers->getMemberByEmailAndPassword($email, $password)) {
                if ($member->is_zapier == 0) {
                    $member->is_zapier = 1;
                    $this->Cmsusers->save($member);
                }
                $response['success'] = true;
                $response['statuscode'] = 100;
                $response['message'] = "Succesfully get data";
                $response = [
                    'name' => $member->email,
                    'email' => $member->email,
                    'job' => 'Member'
                ];
            }
        }

        $this->getApiResponse($response);

    }


    /* Zapier api end */


    /* Trial Account */

    public function trialaccount($key)
    {
        $this->loadModel('Settings');
        $settings = $this->Settings->getSettingsByTrialAccountKey($key);
        $isSuccess = false;
        if (!empty($settings)) {
            $this->viewBuilder()->setLayout("open_link_layout");
            if ($this->request->is('post')) {
                $request = $this->request->getData();
                $this->loadModel('Cmsusers');
                $this->loadModel('App');
                $this->loadModel('MemberPackages');
                $cmsuser = $this->Cmsusers->newEntity();

                $cmsuser->is_trial_user = 1;
                $cmsuser->is_detect_trial_user = 1;
                $current_date_time = $this->App->getSystemCurrentTimeStamp();
                $cmsuser->created_on = $current_date_time;
                $cmsuser->updated_on = $current_date_time;
                $cmsuser->status = STATUS_ACTIVE;
                $cmsuser->retype_password = md5($request['password']);
                $cmsuser = $this->createUser($cmsuser);
                $cmsuser->company_id = 8;

                $email = $request['email'];
                $isUnique = $this->checkUniqueEmail($email);
                try {

                    if ($isUnique) {

                        if ($result = $this->Cmsusers->save($cmsuser)) {
                            $cmsuserData['affiliate_unique_key'] = \App\Utility\Common::generateRandomString(10, $result->id); // length = 10
                            $cmsuserData['zapier_appkey'] = \App\Utility\Common::generateRandomString(10, $result->id);
                            $this->Cmsusers->updateAll($cmsuserData, ['id' => $result->id]);

                            $isMember = 1;

//                            $this->assignPackageForMember($isMember, $cmsuser->id, TRIAL_USER_PACKAGES);
                            $this->createRelationCmsuserUserGroup($result->id, 11);

                            $this->loadModel('CmsuserStatus');
                            $cmsuserStatusData['cmsuser_id'] = $result->id;
                            $this->CmsuserStatus->insertCmsuserStatus($cmsuserStatusData);

                            $this->Flash->success(__('Successfully added.'));
                            $isSuccess = true;
                            $inputData['id'] = $result->id;
                            $inputData['username'] = $result->username;
                            $inputData['email'] = $result->email;
                            $inputData['password'] = $request['password'];
                            $forumUtil = new forumUtils();
                            $forumUtil->addForumUser($inputData);
                            $template_content = array(
                                'firstname' => $inputData['username'],
                                'user_email' => $inputData['email'],
                                'password' => $inputData['password'],
                                'loginurl' => APP_SERVER_HOST_URL
                            );

                            $this->sendEmail(MANDRILL_TEMPLATE_USER_CREATION, $template_content, $inputData['email']);
                        }
                    } else {
                        $this->Flash->error(__('This email already exist'));
                    }

                } catch (\Exception $e) {
                    //dd($e->getMessage());
                }

            }

        } else {
            echo "Invalid request";
            exit;
        }

        $this->set(compact('isSuccess'));
    }

    /* Trial Account */

    /* Member Permission Set */

    private function memberPermissionSet($user){
        $email = $user['email'];
        $this->loadModel('VideoSettings');
        $this->loadModel('Cmsusers');

        $member_id = $this->Auth->user('id');

        $video_settings = $this->VideoSettings->getActualVideoSettingsList();
        $_SESSION['url_list_by_section'] = $video_settings['url_list_by_section'];


    }

    /* Member Permission Set */

}
