<?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 Google\Service\Sheets;
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
 */
class MemberController extends AppsController
{

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

        $this->loadModel('Cmsusers');

        $this->loadModel('Usergroups');

        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']);

    }




    /**
     * Index method
     *
     * @return void
     */
    public function index($id = null)
    {
        $Cmsusers = TableRegistry::get('Cmsusers');
        $page_limit = 10;
        if (isset($this->request->query['page_limit'])) {
            $page_limit = $this->request->query('page_limit');
        }

        $this->paginate = [
            'limit' => $page_limit,
            'order' => [
                'id' => 'desc'
            ]
        ];

        $search = '';
        $db_colum = ['id',
            'full_name',
            'roll_no',
            'email',
            'batch_no',
            'organization',
            'mobile_number',
            'alternative_mobile_number',
            'blood_group',
            'designation',
            'status',
            'username',
            'user_type'
        ];
        if (isset($this->request->query['search'])) {
            $search = $this->request->query('search');

            $condition = ' ( full_name LIKE ' . "'%" . $search . "%' OR full_name LIKE '%" . $search . "%' "
                . "OR username LIKE '%" . $search . "%' OR roll_no LIKE '%" . $search . "%' OR email LIKE '%" . $search . "%') ";
            if (!empty($employee_condition)) {
                $condition .= " AND " . $employee_condition;
            }
            $users = $Cmsusers->find('all')
                ->select($db_colum)
                ->where([ $condition, 'user_type' => 2]);
        } else {

            $users = $Cmsusers->find('all')
                ->select($db_colum)
                ->where(['user_type' => 2]);
        }
//        pr($this->paginate($users));exit;
        $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('users', $this->paginate($users));
        $this->set('searchText', $search);
        $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);
    }


    /**
     * View method
     *
     * @param string|null $id User id.
     * @return void
     * @throws \Cake\Network\Exception\NotFoundException When record not found.
     */
    public function view($id = null)
    {

        $crmuserTable = TableRegistry::get('Cmsusers');
        $user = $crmuserTable->get($id);

        $this->set('user', $user);
        $this->set('_serialize', ['user']);

        $user_permissions = $this->request->session()->read('user_permissions');
        $this->set('languages', $this->languages);
        $this->set('module_pages', $this->getPages());
        $this->set('user_permission', $user_permissions);

    }

    /**
     * Add method
     *
     * @return void Redirects on successful add, renders view otherwise.
     */
    public function add()
    {
        if ($this->request->is('post')) {

            $this->insertData($this->request->getData('user'));
        }
        $user_permissions = $this->request->session()->read('user_permissions');
        $this->set('languages', $this->languages); // var $languages member variable of App Controler
        $this->set('module_pages', $this->getPages());
        $this->set('user_permission', $user_permissions);

    }


    /**
     * 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)
    {

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

        if ($this->request->is(['patch', 'post', 'put'])) {
            //pr($this->request->data);exit;

            $email = trim($this->request->data['email']);

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

            $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'));
                }

            }
        }

        $languages = [LANGUAGE_CODE_ENGLISH => 'English', LANGUAGE_CODE_KOREAN => 'Korean'];
        $user_permissions = $this->request->session()->read('user_permissions');
        $this->set('user_permission', $user_permissions);
        $this->set('cmsuser', $cmsuser);
        $this->set('languages', $languages);
        $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 insertData($client){

        $this->set('crmuserdata', $this->request->getData('user'));

        $CmusersTable = TableRegistry::get('Cmsusers');
        $user = $CmusersTable->newEntity();

        $this->loadModel('Cmsusers');


        $user->user_type = 2;
        $user->employee_id = 1;
        $user->cmsuser_id = 51;
        $user->full_name = $client["full_name"];
        $user->roll_no = $client["roll_no"];
        $user->email = $client["email"];
        $user->batch_no = $client["batch_no"];
        $user->organization = $client["organization"];
        $user->mobile_number = $client["mobile_number"];
        $user->alternative_mobile_number = $client["alt_mobile_number"];
        $user->blood_group = $client["blood_group"];
        $user->designation = $client["designation"];
        $user->username = $client["user_name"];
        $user->status = 1;
        $user->permission_version = 79;

        $user->created_on = date("Y-m-d h:i:s");
        $user->created_by = 51;

        $user->password = $client['password'];
        $checkEmail = $this->checkEmail($user->email);

        if ($checkEmail) {
            $crmUserData = $CmusersTable->save($user);
            if (!empty($crmUserData)) {
                $crmUserId = $crmUserData->id;
                $CrmusersHasControllerTable = TableRegistry::get('cmsuser_usergroups');

                $entities = $CrmusersHasControllerTable->newEntity();
                $entities->cms_user_id = $crmUserId;
                $entities->usergroup_id = 12;
                $CrmusersHasControllerTable->save($entities);


                $commonlogic = new commonLogic();
                $personalizeInfo = $commonlogic->personalizeInfo();
                $personalize = $personalizeInfo['personalize'];
                $loginurl = $personalizeInfo['login_url'];
                //pr($personalizeInfo);exit;
                $templateContent = [
                    'firstname' => $client["full_name"],
                    'loginurl' => $loginurl,
                    'user_email' => $client["email"],
                    'password' => $client['password']
                ];

                $this->sendEmail(AFFILIATE_TEMPLATE_USER_CREATION, $templateContent, $client["email"], 'New Registration', "", null);

                //add_log

                $logData['action'] = "MEMBER_ADD";
                $logData['status'] = "success";
                $logData['input_data'] = $this->request->getData();
                $logData['input_data']["id"] = $crmUserData->id;
                $this->appLog($logData);
                $this->Flash->success(__('The user has been saved.'));
                return $this->redirect(['action' => 'index']);
            }

        }else{
            $this->Flash->error(__('The email already exist.'));
        }

    }
    private function checkEmail($email)
    {
        $result = false;

        $CmusersTable = TableRegistry::get('Cmsusers');

        $this->loadModel('Cmsusers');

        $cmsuser = $CmusersTable->find("All")->where(['email' => $email])->first();

        if(empty($cmsuser)) {

            $result = true;
        }

        return $result;
    }

}
