<?php

namespace App\Controller;

use App\Controller\AppsController;
use Cake\I18n\I18n;
use SubModuleConstants;
use Cake\ORM\TableRegistry;
use DateTime;
use Cake\ORM\Query;
use Cake\Routing\Router;
use Cake\Datasource\ConnectionManager;
use App\Controller\Registrations;
use Aura\Intl\Exception;
use Cake\View\View;
use App\Helper\commonLogic;
use App\Utility\Common;

/**
 * Dashboard Controller
 *
 * @property \App\Model\Table\DashboardTable $Dashboard
 */
class DashboardController extends AppsController {

    public function isAuthorized($user) {
        parent::isAuthorized($user);
        
        
        
        return true;
    }

    private function getSecretKey($id) {
        $length = 32;
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }

        return $randomString . $id;
    }

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

        I18n::locale('en_US');
        $this->Auth->allow(['upgrade']);

        $user = $this->Auth->user();
       
        $this->Auth->allow(['clientContact']);
        $this->Auth->allow(['getContact']);
        $this->Auth->allow(['getClientInfoById']);
        $this->Auth->allow(['ajaxrequest']);
        $this->Auth->allow(['getClientListByType']);
        $this->Auth->allow(['sendToMemberEmail']);
        
        if(empty($user['id'])){
          $this->forceLoggedOutUser('You are now logged out.');
        }
        
        $this->checkUser(); // is RTG User or not

        $this->setUserType();
        
        
    }


    /**
     * Index method
     *
     * @return void
     */
    public function index() {

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

        $user = $this->Auth->user();

        $isRTGuser = $this->isUser($user);

        if (empty($user)) {
            $this->redirect($this->Auth->redirectUrl());
        }
        else {
            if ($this->isStaffUser($user)) {
                $this->redirect(['controller' => 'staff-contents', 'action' => 'show']);
            }
            if (!$isRTGuser) {
                $_SESSION["adminType"] = 1;
                $this->redirect(['controller' => $user_permissions[0]['controller'], 'action' => 'index']);
//                $this->redirect(['controller' => 'settings', 'action' => 'index']);
            } else if ($this->hasUserVelocityAccess($user)) {
                $this->redirect(["controller" => 'Statistics', "action" => "index"]);
            } else if ($isRTGuser) {
                $this->redirect(["controller" => 'Statistics', "action" => "index"]);
            }
        }


        /* 	echo "<pre>";
          print_r($user_permissions);exit; */
        $this->set('user_permission', $user_permissions);
//        if (empty($user_permissions) && $this->isRTGUser($this->Auth->user())) {
//            $this->Flash->error(__('You do not have access to any modules currently'));
//            $this->redirect(['controller' => 'Registrations', 'action' => 'terms']);
//        }
        $this->set('company_id', $this->Auth->user()['company_id']);
        $base_url = Router::url('/');
        $this->set('base_url', $base_url);
    }
    
    private function forceLoggedOutUser($message) {
        $session = $this->request->session();
        $session->delete("user_permissions");
        $session->delete('permission_version');
        $session->delete('modules');
        $this->request->session()->destroy();
        $this->Flash->loginSuccess($message);
        return $this->redirect($this->Auth->logout());
        exit;
    }

    private function generateLetterTypeHtml($isRTGLetter = false) {
        $html = "";

        if (!empty(LETTER_TYPES_NAME)) {
            $html = '<ul style="display: block;">';
            foreach (json_decode(LETTER_TYPES_NAME) as $id => $name) {
                if($isRTGLetter){
                    $html .= '<li><input onclick="seteSelectedDropDownView(this);" name="lettertypes[]" type="checkbox" class="beforeSaveInput" value="' . $id . '" data-view="' . $name . '"> ' . $name . '</li>';
                }else{
                    if(!in_array($id, [14,15])){
                        $html .= '<li><input onclick="seteSelectedDropDownView(this);" name="lettertypes[]" type="checkbox" class="beforeSaveInput" value="' . $id . '" data-view="' . $name . '"> ' . $name . '</li>';
                    }
                }
                
            }
            
            $html .= "</ul>";
        }
        return $html;
    }

    private function letterDropdown($isNotVelocity = true) {
        $common  = new Common();
        $padding_left_0 = "";
        $padding_left_0_1 = "padding_left_0";
        $date_picker = "date-time-picker";
        if($isNotVelocity){
            $padding_left_0_1 = "";
            $padding_left_0 = "padding_left_0";
            $date_picker = "date-time-picker";
        }
        $select = '<select name="letter_send_date_tmezone" id="" class="form-control">
        <option value="0">Please select timezone</option>';
        $letter_set_string = "";
        foreach (LETTER_SET_LIST as $key => $letter_set) {
            $letter_set_string .= "<option value='$key'>$letter_set</option>";
        }
        foreach ($common->tz_list() as $t) {
            $selected = '';
            if ($t['label'] == "GMT -7:00 (Mountain Standard Time)") {
                $selected = 'selected';
            }
            $select .= '<option value="' . $t['key'] . '" ' . $selected . '>' .
                    $t['label'] .
                    '</option>';
        }
        $select .= '</select>';

        $html = '<div class="row">
                    <div class="col-md-12 '.$padding_left_0_1.' text-left">
                        <label for="">Send Email Notification Of Letters Being Sent Out Check Below</label>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-4 '.$padding_left_0_1.'">
                        <select name="letter_type" id="" class="form-control">
                             <option value="0">Please Select</option>'
                             .$letter_set_string.
                         '</select>                           
                    </div>
                    <div class="col-md-4">'.$this->set_STT_PI_LETTER_SET_Dropdown().'</div>
                    <div class="col-md-3 '.$padding_left_0.'">
                        <div class="checkbox">
                            <label>
                                <input type="checkbox"  name="set_schedule"  value="1" > Set Schedule
                            </label>
                        </div>
                    </div>
                    
                </div>
                <br/>
                <div class="row schedule-area" style="display:none; padding-bottom: 10px;">
                        <div class="col-md-6 padding_left_0">
                        <div class="input-group date '.$date_picker.'" id="date-time-picker">
                    <input type="text" placeholder="Please select schedule date/time" name="next_sending_email_date" class="form-control" readonly/>
                    <span class="input-group-addon">
                        <span class="glyphicon glyphicon-calendar"></span>
                    </span>
                </div>
                        
                    </div>
                    <div class="col-md-6 padding_left_0">' .
                $select
                . '</div>
                    </div>';


        return $html;
    }

    private function setAutomationHTML() {
        $option = "";
        
        if (!empty(AUTOMATION_SCHEDULE_TYPES)) {
            $AUTOMATION_SCHEDULE_TYPES = AUTOMATION_SCHEDULE_TYPES;
            unset($AUTOMATION_SCHEDULE_TYPES[3]);
            $option = '<select name="automation_type" class="form-control">';
            foreach ($AUTOMATION_SCHEDULE_TYPES as $key => $ast) {
                $selected = "";
//                if($type == $key){
//                    $selected = "selected";
//                }
                $option .= '<option value="' . $key . '">' . $ast . '</option>';
            }
            $option .= "</select>";
        }

        $html = '<div class="row">
                        <div class="col-md-3 padding_left_0">
                            <label for="">Setup Automation</label>
                        </div>
                        <div class="col-md-2 padding_left_0">
                            <div class="checkbox rtg-automation-checkbox" style="padding-top:0" >
                                <label>
                                    <input type="checkbox" value="1"  name="set_automation" > Automation
                                </label>
                            </div>
                        </div>
                        
                    </div>
                    <div class="row setup-automation" style="display:none;">
                        <div class="col-md-4 padding_left_0">
                            <div class="input-group">
                                <input type="number" pattern="[0-9]" placeholder="Days" name="day_value" class="form-control">
                            </div>
                        </div>
                        <div class="col-md-4">
                            ' . $option . '   
                        </div>
                    </div>';

        return $html;
    }

    private function tz_list() {
        $zones_array = array();
        $zones_array[] = ['key' => 'America/Belize', 'label' => "GMT -6:00 (Mountain Daylight Time)"];
        $zones_array[] = ['key' => 'Pacific/Honolulu', 'label' => "GMT -10:00 (Hawaii Standard Time)"];
        $zones_array[] = ['key' => 'America/Anchorage', 'label' => "GMT -8:00 (Alaska Daylight Time)"];
        $zones_array[] = ['key' => 'America/Los_Angeles', 'label' => "GMT -7:00 (Pacific Daylight Time)"];
        $zones_array[] = ['key' => 'America/Los_Angeles', 'label' => "GMT -7:00 (Mountain Standard Time)"];
        $zones_array[] = ['key' => 'America/Chicago', 'label' => "GMT -5:00 (Central Daylight Time)"];
        $zones_array[] = ['key' => 'America/New_York', 'label' => "GMT -4:00 (Eastern Daylight Time)"];
        return $zones_array;
    }

    public function ajaxrequest() {
        if ($this->request->is('post')) {
            $request = $this->request->getData();
            $member_id = $this->Auth->user('id');
            $response = false;
            if ($request['type'] == 'yellow') {
                $_SESSION['is_warning'] = 0;
                $response = $_SESSION['is_warning'];
            } else if ($request['type'] == 'client') {
                $response = $_SESSION['is_warning'];
                unset($_SESSION['total_num_of_clients']);
            } else if ($request['type'] == 'remove_client_notifications') {
                $this->loadModel('Clients');
                $this->Clients->clearClientNotificationsByMemberId($member_id);
                unset($_SESSION['total_num_of_clients']);
            } else if ($request['type'] == "remove_agreement_notifications") {
                $this->loadModel('AgreementAssignments');
                $result = $this->AgreementAssignments->makeReadBymemberId($member_id);
                if ($result) {
                    unset($_SESSION['total_agreenment']);
                    $response = "clear";
                }
            }else if($request['type'] == "SEE_MORE_REMINDER"){
                $member_id = $this->Auth->user('id');
                $user_type = 1;
                $response['status'] = false;
                $this->loadModel("MemberReminders");
                if($_SESSION['userType'] == CMS_USER_INDICATOR){
                    $member_remainder = $this->MemberReminders->getReminderNotifications($member_id, $user_type,0,0);
                }else if($_SESSION['userType'] == CRM_USER_INDICATOR && $_SESSION['Auth']['User']['type'] == 1){
                    $member_remainder = $this->MemberReminders->getRemindersForEmployees($this->Auth->user('user_id'),3);
                }
                
                $remainders = $member_remainder["due"];
                $total_unread_remainders = $member_remainder["total_unread"];
                $total_remainders = $member_remainder["total_remainder"];
                $today_reminders = $member_remainder["today"]+$member_remainder["over"];
                
                $view = new View($this->request, $this->response);
                $response['html'] = $view->element('reminder/reminder_notification_list',compact('remainders','total_unread_remainders','total_remainders','today_reminders'));
                if(!empty($response['html'])){
                    $response['status'] = true;
                }
            }else if($request['type'] == "SEE_MORE_NOTE"){
                $member_id = $this->Auth->user('id');
                $user_type = 1;
                $response['status'] = false;
                $this->loadModel("MemberNotes");
                if($_SESSION['userType'] == CMS_USER_INDICATOR){
                    $member_note = $this->MemberNotes->getNoteNotifications($member_id, $user_type,0,0);
                }else if($_SESSION['userType'] == CRM_USER_INDICATOR && $_SESSION['Auth']['User']['type'] == 1){
                    $member_note = $this->MemberNotes->getNotesForEmployees($this->Auth->user('user_id'),3);
                }
                
                $notes = $member_note["due"];
                $total_unread_notes = $member_note["total_unread"];
                $total_notes = $member_note["total_remainder"];
                $today_notes = $member_note["today"]+$member_note["over"];
                
                $view = new View($this->request, $this->response);
                $response['html'] = $view->element('note/note_notification_list',compact('notes','total_unread_notes','total_notes','today_notes'));
                if(!empty($response['html'])){
                    $response['status'] = true;
                }
            }else if($request['type'] == "AFFILIATE_NOTIFICATION_UPDATE"){
                $this->loadModel('Crmusers');
                $response['status'] = false;
                if($this->Crmusers->updateNewAffiliateRegistrationByMemberId($this->Auth->user('id'))){
                    $_SESSION['new_affiliate_count'] = 0;
                    $response['status'] = true;
                }
            }

            echo json_encode($response);
            exit;
        }
    }



    public function clientContact() {
        if ($this->request->is('ajax')) {
            
            $cmsuser_id = $this->Auth->user('id');
            $employee_condition = "";
            $isNotAllclientAccess = $this->isAccessAllClients();
            if ($isNotAllclientAccess) {
                $this->loadModel('ClientAssignments');
                $auth_employee_id = $this->Auth->user('user_id');
                //echo $auth_employee_id;exit;
                $client_id_list = $this->ClientAssignments->getClientsByUserTypeIdAndCondition($auth_employee_id,"refference_type = 3");
                $employee_condition = "Clients.id in(" . implode(",",$client_id_list).")";
                
            }
            
            $dashboard_client_id = 0;
            if(isset($_SESSION['client_id_from_dashboard']) && $_SESSION['client_id_from_dashboard'] > 0){
                $dashboard_client_id = $_SESSION['client_id_from_dashboard'];
                unset($_SESSION['client_id_from_dashboard']);
                
            }
            
            $contacts = TableRegistry::get('Clients')
                    ->find('all')
                    ->select(['crmuser_id' => 'Clients.crmuser_id',
                        'id' => 'C.id',
                        'first_name' => 'C.first_name',
                        'last_name' => 'C.last_name',
                        'name' => 'Clients.name',
                        'email' => 'C.email',
                        'contact_id' => 'C.id',
                        'client_id' => 'Clients.id'])
                    ->join([
                        'table' => 'contacts',
                        'alias' => 'C',
                        'type' => 'INNER',
                        'conditions' => [
                            'C.client_id = Clients.id',
                            'C.is_primary_contact = 1',
                            'Clients.status = 1',
                            $client_dashboard_condition
                        ]
                    ])
                    ->where(['Clients.cmsuser_id' => $cmsuser_id, $employee_condition])
                    ->order('C.first_name asc');
            $response['contacts'] = $contacts;
            $response['dashboard_client_id'] = $dashboard_client_id;
            
            echo json_encode($response);
            die();
        }
    }

    private function hasUserVelocityAccess() {

        $result = false;
        if ($this->request->session()->read("user_has_velocity_access")) {
            $this->request->session()->delete("user_has_velocity_access");
            $result = true;
        }
        return $result;
    }

    public function getContact() {
        $request = $this->request->data();
        $request_url = $this->referer();
        $form_id = basename($request_url);
        $this->loadModel('App');
        $current_date_time = $this->App->getSystemCurrentTimeStamp('m/d/Y');

        $report_type = 1;
        if (isset($request['report_type']) && $request['report_type'] > 0) {
            $report_type = $request['report_type'];
        }
        
        $id = $request['contactId'];
        $client_type = $request['client_type'];
        $HAS_RTG_ACCESS_PKG = $request['HAS_RTG_ACCESS_PKG'];
        $requestArray = array();
        $clientDetails = "";
        $affiliate_condition = "";
        if ($this->request->is('ajax')) {
            $contact = TableRegistry::get('contacts')
                    ->find('all')
                    ->where(['id' => $id, 'cmsuser_id' => $this->Auth->user('id'), 'is_primary_contact' => 1])
                    ->first();

            $client_id = $contact->client_id;
            $client_email = $contact->email;

            if (!empty($client_id)) {


                $clientDetails = TableRegistry::get('creditreportsetups')
                        ->find('all')
                        ->where(['client_id' => $client_id, $affiliate_condition])
                        ->first();

                $clientMedias = TableRegistry::get('uploadmedias')
                        ->find('all')
                        ->where(['client_id' => $client_id])
                        ->toArray();
                $temp_clientmedias = [];
                if (!empty($clientMedias)) {
                    foreach ($clientMedias as $current_media_id => $media) {
                        $media_file_path = WWW_ROOT . "contact_photo/" . $media->image_path;
                        if (file_exists($media_file_path)) {
                            $temp_clientmedias[$current_media_id] = $media;
                        }
                    }
                }

                $clientMedias = $temp_clientmedias;

                $publicKeyIdAssoc = [];
                $inq_data = [];
                $bankAssocchunkList = [];
                $bankAssoc = [];
                $bankList = [];
                $latepayList = [];
                $paublicrecords = [];
                $inquries = [];
                $databasikKeyItem = [];
                $inquriesAssoc = [];
                $inquriesChunkList = [];
                $publicrecordAddressList = [];
                $this->loadModel('DataDocuments');
                $dataDocumentinfo = $this->DataDocuments->getDDocumentById($this->Auth->user('id'), $client_id);
                $report_type_id = null;
                $report_html = "";
                if(!empty($dataDocumentinfo) && $dataDocumentinfo->dst_id > 0){
                    $report_type_id = $dataDocumentinfo->dst_id;
                    $report_html = file_get_contents(WWW_ROOT."html_content/".$dataDocumentinfo->cmsuser_id."/".$dataDocumentinfo->client_id."/".$dataDocumentinfo->id.".html");
                }
                
                
                if ($HAS_RTG_ACCESS_PKG) {
                    
                    $dd_id = 0;
                    
                    $this->loadModel('DataItemKeyValues');
                    $this->loadModel('DataPublicRecords');
                    $this->loadModel('DataInquiries');
                    $this->loadModel('DataBasicKeyValues');
                    $this->loadModel('DataInquiriesAddress');
                    $this->loadModel('DataPublicrecordAddress');
                    

                    $bankAssoc = $this->DataItemKeyValues->getBankAssoc($client_id);

                    if (!empty($dataDocumentinfo)) {
                        $dd_id = $dataDocumentinfo->id;
                    }

                    $with_late_pays = true;
                    $publicrecordAddressList = $this->DataPublicrecordAddress->getPublicrecordAddressListByDdId($dd_id);
                    $this->DataItemKeyValues->is_delete = 0;
                    $negativeAndLatePayList = $this->DataItemKeyValues->getDataBasicBankListDDId($dd_id, $with_late_pays);
                    $bankList = $negativeAndLatePayList['negative'];
                    $negativecategory = $negativeAndLatePayList['negativecategory'];
                    $latepayList = $negativeAndLatePayList['latepays'];
                    $latepayscategory = $negativeAndLatePayList['latepayscategory'];

                    $this->DataPublicRecords->is_delete = 0;
                    $db_pb_result = $this->DataPublicRecords->getAllPublicRecordsByDdId($dd_id, "(status1 = 1 OR status2 = 1 OR status3 = 1)", true);
                    $paublicrecords = $db_pb_result['default_list'];
                    $main_public_records = $paublicrecords;
                    $publicCategoryWiseResult = $db_pb_result['category_wise_list'];

                    $this->DataInquiries->is_delete = 0;
                    $db_inq_info = $this->DataInquiries->getInquiriesKeyListByDDId($dd_id, "DataInquiries.type = 1", true);
                    $inquries = $db_inq_info['default_list'];

                    $this->DataBasicKeyValues->is_delete = 0;
                    $databasikKeyItem = $this->DataBasicKeyValues->getDataBasicKeysByDDId($dd_id);
                    $personal_info_assoc = $this->makePersonalInfoString($databasikKeyItem);
                    $inq_address_assoc = $this->DataInquiriesAddress->getInquiriesAddressByDDId($dd_id);
                    $paublicrecords = $this->publicrecorduniqueList($paublicrecords);
                    $bank_chunk_list = [];
//                    if($this->Auth->user('id') == 702){
//                        pr($databasikKeyItem);exit;
//                    }

                    if (!empty($bankList)) {
                        $chunk_value = 15;
                        $temp_bank_list = $bankList;
                        if (!empty($paublicrecords)) {
                            $temp_bank_list[] = "__PUBLIC_RECORD__";
                        }
                        $last_key = array_search("__PUBLIC_RECORD__", $temp_bank_list);
                        $array_pos = $chunk_value - 1;
                        $temp_bank_list = array_slice($temp_bank_list, 0, $array_pos, true) + array($last_key => "__PUBLIC_RECORD__") + array_slice($temp_bank_list, $array_pos, count($temp_bank_list) - 1, true);
                        $bank_chunk_list = array_chunk($temp_bank_list, $chunk_value, true);
                    }

                    list($bankAssocchunkList, $negetiv_item_list_by_chunk) = $this->bankAssocChunkList($paublicrecords, $bank_chunk_list, $bankAssoc);

                    $getinquries = $this->setInquiriesAssoc($inquries);
                    $inquries = $getinquries['inquries'];
                    $inquriesAssoc = $getinquries['inquriesAssoc'];
                    $inq_with_company = [];
                    if (isset($db_inq_info['with_company_list']['Exp']) && !empty($db_inq_info['with_company_list']['Exp'])) {
                        $exp_inq = $this->setInquiriesAssoc($db_inq_info['with_company_list']['Exp']);
                        $inq_with_company['Exp'] = $exp_inq['inquries'];
                    }
                    if (isset($db_inq_info['with_company_list']['Trans']) && !empty($db_inq_info['with_company_list']['Trans'])) {
                        $trabs_inq = $this->setInquiriesAssoc($db_inq_info['with_company_list']['Trans']);
                        $inq_with_company['Trans'] = $trabs_inq['inquries'];
                    }
                    if (isset($db_inq_info['with_company_list']['Equif']) && !empty($db_inq_info['with_company_list']['Equif'])) {
                        $equif_inq = $this->setInquiriesAssoc($db_inq_info['with_company_list']['Equif']);
                        $inq_with_company['Equif'] = $equif_inq['inquries'];
                    }

                    if (!empty($paublicrecords)) {
                        foreach ($paublicrecords as $key_id => $paublicrecord) {
                            $publicKeyIdAssoc[$key_id] = $paublicrecord['key'];
                        }
                    }

                    $inquriesChunkList = $this->processInqChunk($inquriesAssoc);

                    $total_bank_assoc_chunk = count($bankAssocchunkList);
                    $total_inquries_assoc_chunk = count($inquriesChunkList);

                    $final_assoc_list = [];
                    $count = 0;
                    if ($total_inquries_assoc_chunk > $total_bank_assoc_chunk) {
                        foreach ($inquriesChunkList as $current_inq_chunk) {
                            if (!isset($bankAssocchunkList[$count])) {
                                $count = 0;
                            }
                            $ngrative_item = $bankAssocchunkList[$count];
                            $array_val = $negetiv_item_list_by_chunk[$count];
                            $final_assoc_list[] = ['negative_item_ids' => $array_val, 'negative_item' => $ngrative_item, 'inqury' => $current_inq_chunk['inqury']  ?? "", 'inqury_ids' => $current_inq_chunk['inqury_ids']];
                            $count++;
                        }
                    } else {
                        foreach ($bankAssocchunkList as $bank_chunk_key => $current_bank_chunk) {
                            if (!isset($inquriesChunkList[$count])) {
                                $count = 0;
                            }
                            $inqury_item = $inquriesChunkList[$count];
                            $array_val = $negetiv_item_list_by_chunk[$bank_chunk_key];
                            $final_assoc_list[] = ['negative_item_ids' => $array_val, 'negative_item' => $current_bank_chunk, 'inqury' => $inqury_item['inqury'] ?? "", 'inqury_ids' => $inqury_item['inqury_ids']];
                            $count++;
                        }
                    }
                }
                //pr($final_assoc_list);exit;
                $client_info = [];
                if (empty($clientDetails)) {

                    if (!empty($contact)) {
                        if (!empty($contact->first_name)) {
                            $client_info['first_name'] = $contact->first_name;
                        }

                        if (!empty($contact->last_name)) {
                            $client_info['last_name'] = $contact->last_name;
                        }
                    }
                }
                
                $banklist_index_less = [];
                $banklist_index_less_assoc = [];
                if(!empty($bankList)){
                    foreach($bankList as $b){
                        $bnk = preg_replace('/-[0-9]*$/', '', $b);
                        if(!empty($bnk)){
                            $banklist_index_less[] = $bnk;
                            $banklist_index_less_assoc[$b] = $bnk;
                        }
                    }
                }
                
                $requestArray = [
                    'client_info' => $client_info,
                    'clientDetails' => $clientDetails,
                    'clientMedias' => $clientMedias,
                    'banklist_index_less'=>$banklist_index_less,
                    'banklist_index_less_assoc'=>$banklist_index_less_assoc,
                    'bankList' => $bankList,
                    'latepayList' => $latepayList,
                    'client_id' => $client_id,
                    'dd_id' => $dd_id,
                    'bankAssoc' => $bankAssoc,
                    'paublicrecords' => $paublicrecords,
                    'publicKeyIdAssoc' => $publicKeyIdAssoc,
                    'inquries' => $inquries,
                    'bank_chunk_list' => $bank_chunk_list,
                    'databasikKeyItem' => $databasikKeyItem,
                    'bankAssocchunkList' => $final_assoc_list,
                    'form_id' => $form_id,
                    'inq_with_company' => $inq_with_company,
                    'latepayscategory' => $latepayscategory,
                    'negativecategory' => $negativecategory,
                    'main_public_records' => $main_public_records,
                    'publicCategoryWiseResult' => $publicCategoryWiseResult,
                    'personal_info_assoc' => $personal_info_assoc,
                    'inq_address_assoc' => $inq_address_assoc,
                    'report_type_id' => $report_type_id,
                    'client_email'=>$client_email,
                    'publicrecordAddressList'=>$publicrecordAddressList,
                    'report_html'=>$report_html,
                    'today_date'=>$current_date_time,
                ];
            }

            // die();
        }

        echo json_encode($requestArray);
        die();
    }

    private function makePersonalInfoString($databasikKeyItem) {
        $finalString = "";
        $category_wise = [];
        $category_wise['equif'] = [];
        $category_wise['exp'] = [];
        $category_wise['trans'] = [];
        $keyList = [];
        $keyList['exp'] = [];
        $keyList['equif'] = [];
        $keyList['trans'] = [];
        if (!empty($databasikKeyItem)) {
            foreach ($databasikKeyItem as $key => $item) {
                $string = "";
                $data_key = trim($item['data_key']);
                $value1 = trim($item['value1']);
                $value2 = trim($item['value2']);
                $value3 = trim($item['value3']);

                if (!empty($value1)) {
                    if($item['status1'] == 1){
                    $keyList['exp'][$key] = $data_key;
                    
                        $category_wise['exp'][$key] = [
                            'data_key' => $data_key,
                            'value' => $value1
                        ];
                    }
                }

                if (!empty($value2)) {
                    if($item['status2'] == 1){
                    $keyList['equif'][$key] = $data_key;
                     
                    $category_wise['equif'][$key] = [
                        'data_key' => $data_key,
                        'value' => $value2
                    ];
                     }
                }

                if (!empty($value3)) {
                    if($item['status3'] == 1){
                    $keyList['trans'][$key] = $data_key;
                     
                    $category_wise['trans'][$key] = [
                        'data_key' => $data_key,
                        'value' => $value3
                    ];
                     }
                }
            }
        }


        return [
            'all_category_list' => $category_wise['exp'] + $category_wise['equif'] + $category_wise['trans'],
            'category_wise_assoc' => $category_wise,
            'key_name_list' => $keyList,
            'all_key_name_list' => $keyList['exp'] + $keyList['equif'] + $keyList['trans']
        ];
    }

    private function setInquiriesAssoc($inquries) {
        if (!empty($inquries)) {
            foreach ($inquries as $key_inq => $inqury_id) {
                $key_date_name = explode('_', $key_inq);
                $inq_data['key_name'][$inqury_id] = $key_date_name[0];
                $inq_data['key_date'][$inqury_id] = $key_date_name[1];
                $inqString = "";
                if (!empty($inq_data['key_name'][$inqury_id])) {
                    $inqString = $inq_data['key_name'][$inqury_id];
                }

                if (!empty($inq_data['key_date'][$inqury_id])) {
                    if (!empty($inqString)) {
                        $inqString .= "\n" . $inq_data['key_date'][$inqury_id];
                    } else {
                        $inqString = $inq_data['key_date'][$inqury_id];
                    }
                }
                $inquriesAssoc[$inqury_id] = $inqString;
            }
            $inquries = $inq_data;
        }

        return ['inquries' => $inquries, 'inquriesAssoc' => $inquriesAssoc];
    }

    private function processInqChunk($inquriesAssoc) {
        $result = [];
        if (!empty($inquriesAssoc)) {
            $inquriesChunkList = array_chunk($inquriesAssoc, 15, true);
        }

        if (!empty($inquriesChunkList)) {
            foreach ($inquriesChunkList as $current_inq_chunk) {
                $address_string = "";
                $inqury_id_list = [];
                foreach ($current_inq_chunk as $inqury_id => $chunk) {
                    if (!empty($chunk)) {
                        $inqury_id_list[] = $inqury_id;
                        if (!empty($address_string)) {
                            $address_string .= "\n\n" . $chunk;
                        } else {
                            $address_string = $chunk;
                        }
                    }
                }
                if (!empty($address_string)) {
                    $result[] = ['inqury' => $address_string, 'inqury_ids' => $inqury_id_list ?? ""];
                }
            }
        }

        return $result;
    }

    private function publicrecorduniqueList($paublicrecords) {
        $uniqueList = [];
        if (!empty($paublicrecords)) {
            foreach ($paublicrecords as $pb_id => $current_pb) {
                $uniqueList[$pb_id] = array_unique($current_pb);
            }
        }
        return $uniqueList;
    }

    private function bankAssocChunkList($paublicrecords, $bank_chunk_list, $bankAssoc) {
        $bankAssocchunkList = [];
        $final_public_record_string = "";
        //pr($paublicrecords);exit;
        if (!empty($paublicrecords)) {
            foreach ($paublicrecords as $pb_id => $current_pb) {
                $pb_key = "";
                if (!empty($current_pb['key'])) {
                    $explode = explode('-', $current_pb['key']);
                    if (!empty($explode[1]) && ($explode[1] >= 1 && $explode[1] <= 100)) {
                        $pb_key = $explode[0];
                    }
                }

                $public_record_string = "";
                if (!empty($current_pb['value1'])) {
                    if (!empty($public_record_string)) {
                        $public_record_string .= "\n" . $current_pb['value1'];
                    } else {
                        $public_record_string = $current_pb['value1'];
                    }
                }

                if (!empty($current_pb['value2'])) {
                    if (!empty($public_record_string)) {
                        $public_record_string .= "\n" . $current_pb['value2'];
                    } else {
                        $public_record_string = $current_pb['value2'];
                    }
                }

                if (!empty($current_pb['value3'])) {
                    if (!empty($public_record_string)) {
                        $public_record_string .= "\n" . $current_pb['value3'];
                    } else {
                        $public_record_string = $current_pb['value3'];
                    }
                }

                if (!empty($public_record_string)) {
                    $final_public_record_string .= "\n" . $pb_key . ": " . $public_record_string;
                }
            }
        }



        $negetiv_item_list_by_chunk = [];
        if (!empty($bank_chunk_list)) {
            foreach ($bank_chunk_list as $occurance => $current_chunk) {
                if (!empty($current_chunk)) {
                    $every_chunk_string = "";
                    foreach ($current_chunk as $every_chunk_key => $every_bank_name) {
                        if (isset($bankAssoc[$every_chunk_key]) && $every_bank_name != "__PUBLIC_RECORD__") {
                            $negetiv_item_list_by_chunk[$occurance][$every_chunk_key] = $every_bank_name;
                            $info = $bankAssoc[$every_chunk_key];
                            //$info = array_unique($info);
                            
                            
                            if (!empty($every_bank_name)) {
                                $explode = explode('-', $every_bank_name);
                                if (!empty($explode[1]) && ($explode[1] >= 1 && $explode[1] <= 100)) {
                                    $every_bank_name = $explode[0];
                                }
                            }

                            $accTypeString = "Account type: ";
                            $finalString = "";
                            $common_acctype_string = "";
                            $account_no_array = [];

                            $trans_string = "";
                            $exp_string = "";
                            $equif_string = "";


                            if ($info['isJson'] == 1) {

                                if (!empty($info['value6']['accType'])) {
                                    $common_acctype_string = $info['value6']['accType'];
                                }

                                if (!empty($info['value5']['accType'])) {
                                    $common_acctype_string = $info['value5']['accType'];
                                }

                                if (!empty($info['value1']['accType'])) {
                                    $common_acctype_string = $info['value1']['accType'];
                                }

                                // Transunion
                               
                                if (!empty($info['value1']['account'])) {
                                    if (!empty($finalString)) {
                                        $finalString .= "\n" . $every_bank_name;
                                    } else {
                                        $finalString = $every_bank_name;
                                    }
                                    if(!in_array($info['value1']['account'],$account_no_array)){
                                        $account_no_array[] = $info['value1']['account'];
                                        $trans_string = $info['value1']['account'];
                                        if (!empty($finalString)) {
                                            $finalString .= "\n" . $info['value1']['account'];
                                        } else {
                                            $finalString = $info['value1']['account'];
                                        }
                                    }
                                }
                                
                                if (!empty($trans_string) && !empty($info['value2'])) {
                                   // $trans_string = $info['value2'];
                                    if (!empty($finalString)) {
                                        $finalString .= "\n" . $info['value2'];
                                    } else {
                                        $finalString = $info['value2'];
                                    }
                                }
                                
                                if(!empty($trans_string) && !empty($info['value3'])){
                                    //$trans_string = $info['value3'];
                                    if (!empty($finalString)) {
                                        $finalString .= "\n" . $info['value3'];
                                    } else {
                                        $finalString = $info['value3'];
                                    }
                                }

                                if(!empty($trans_string) && !empty($common_acctype_string)){
                                    if (!empty($finalString)) {
                                        $finalString .= "\n" . $accTypeString . $common_acctype_string;
                                    } else {
                                        $finalString = $accTypeString . $common_acctype_string;
                                    }
                                }

                                // Experian
                                if (!empty($info['value5']['account'])) {
                                    
                                    if(!in_array($info['value5']['account'],$account_no_array)){
                                        $account_no_array[] = $info['value5']['account'];
                                        $exp_string = $info['value5']['account'];
                                        if (!empty($finalString)) {
                                            $finalString .= "\n\n" . $every_bank_name;
                                        } else {
                                            $finalString = $every_bank_name;
                                        }
                                        
                                        if (!empty($finalString)) {
                                            $finalString .= "\n" . $info['value5']['account'];
                                        } else {
                                            $finalString = $info['value5']['account'];
                                        }
                                    }

                                }

                                if (!empty($exp_string) && !empty($info['value2'])) {
                                    //$exp_string = $info['value2'];
                                    if (!empty($finalString)) {
                                        $finalString .= "\n" . $info['value2'];
                                    } else {
                                        $finalString = $info['value2'];
                                    }

                                }
                                
                                if(!empty($exp_string) && !empty($info['value3'])){
                                    //$exp_string = $info['value3'];
                                    if (!empty($finalString)) {
                                        $finalString .= "\n" . $info['value3'];
                                    } else {
                                        $finalString = $info['value3'];
                                    }

                                }

                                if(!empty($exp_string) && !empty($common_acctype_string)){
                                    if (!empty($finalString)) {
                                        $finalString .= "\n" . $accTypeString . $common_acctype_string;
                                    } else {
                                        $finalString = $accTypeString . $common_acctype_string;
                                    }
                                }


                                // Equifax
                                if (!empty($info['value6']['account'])) {

                                    if(!in_array($info['value6']['account'],$account_no_array)){
                                        $account_no_array[] = $info['value6']['account'];
                                        $equif_string = $info['value6']['account'];
                                        if (!empty($finalString)) {
                                            $finalString .= "\n\n" . $every_bank_name;
                                        } else {
                                            $finalString = $every_bank_name;
                                        }
                                        
                                        if (!empty($finalString)) {
                                            $finalString .= "\n" . $info['value6']['account'];
                                        } else {
                                            $finalString = $info['value6']['account'];
                                        }
                                    }
                                }


                                if (!empty($equif_string) && !empty($info['value2'])) {
                                    //$equif_string = $info['value2'];
                                    if (!empty($finalString)) {
                                        $finalString .= "\n" . $info['value2'];
                                    } else {
                                        $finalString = $info['value2'];
                                    }

                                }
                                
                                if(!empty($equif_string) && !empty($info['value3'])){
                                    //$equif_string = $info['value3'];
                                    if (!empty($finalString)) {
                                        $finalString .= "\n" . $info['value3'];
                                    } else {
                                        $finalString = $info['value3'];
                                    }

                                }

                                if(!empty($equif_string) && !empty($common_acctype_string)){
                                    if (!empty($finalString)) {
                                        $finalString .= "\n" . $accTypeString . $common_acctype_string;
                                    } else {
                                        $finalString = $accTypeString . $common_acctype_string;
                                    }
                                }

                            } else {
                                if (!empty($info['value1'])) {
                                    if (!empty($finalString)) {
                                        $finalString .= "\n" . $info['value1'];
                                    } else {
                                        $finalString = $info['value1'];
                                    }
                                }

                                if (!empty($info['value5'])) {
                                    if (!empty($finalString)) {
                                        $finalString .= "\n" . $info['value5'];
                                    } else {
                                        $finalString = $info['value5'];
                                    }
                                }

                                if (!empty($info['value6'])) {
                                    if (!empty($finalString)) {
                                        $finalString .= "\n" . $info['value6'];
                                    } else {
                                        $finalString = $info['value6'];
                                    }
                                }
                            }
                            // if($every_bank_name == "DPT ED/NAVI"){
                            //     //pr($finalString);exit;
                            // }
                            
                            if (!empty($finalString)) {
                                $every_chunk_string .= $finalString . "\n\n";
                            }
                        } else {
                            $every_chunk_string .= $final_public_record_string;
                        }
                    }
                    
                    $bankAssocchunkList[$occurance] = $every_chunk_string;
                }
            }
        }

        return [$bankAssocchunkList, $negetiv_item_list_by_chunk];
    }

    private function generateExportDropDownByMemberId() {
        $member_id = $this->Auth->user('id');
        $this->loadModel('Automationsetup');
        $exports = $this->Automationsetup->getMemberExportsByMemberId($member_id);
        $exportsArray = []; //download_category
        $html = '<select name="download_category" id="" class="form-control" disabled>';
        $view = new View($this->request, $this->response);
        $view->viewPath = 'Dashboard';
        $view->layout = false;
        $view->set('exports', $exports);
        $html_all = $view->render('download_dropdown');

        $ls_fax_exprts = [];
        $html_ls_fax = "";
        
        if (!empty($exports)) {
            foreach ($exports as $exp) {
                
                if (in_array($exp->export_id, [EMAIL_EXPORT_TYPE,DROPBOX_EXPORT_TYPE,GOOGLE_DRIVE_EXPORT_TYPE,ZAPIER_EXPORT_TYPE,RINGCENTRAL_EXPORT_TYPE,LETTER_STREAM_TYPE])) {
                    $ls_fax_exprts[] = $exp;
                }
                
//                if (in_array($exp->export_id, [LETTER_STREAM_TYPE])) {
//                    $ls_fax_exprts[] = $exp;
//                }
            }

            
        }
        
        $view1 = new View($this->request, $this->response);
        $view1->viewPath = 'Dashboard';
        $view1->layout = false;
        $view1->set('exports', $ls_fax_exprts);
        $html_ls_fax = $view1->render('download_dropdown');



        return [
            'ALL_EXPORT_TYPES' => $html_all,
            'LS_AND_FAX_TYPES' => $html_ls_fax
        ];
    }

    public function getClientInfoById() {
        $responseArray = array();
        if ($this->request->is('ajax')) {
            $request = $this->request->data();
            $client_id = $request['client_id'];
            if ($client_id > 0) {
                $dd_id = 0;
                $this->loadModel('DataDocuments');
                $this->loadModel('DataItemKeyValues');

                $dataDocumentinfo = $this->DataDocuments->getDDocumentById($this->Auth->user('id'), $client_id);
                if (!empty($dataDocumentinfo)) {
                    $dd_id = $dataDocumentinfo->id;
                }

                $with_late_pays = true;
                $this->DataItemKeyValues->is_delete = 1; // ignore deleted items
                $negativeAndLatePayList = $this->DataItemKeyValues->getDataBasicBankListDDId($dd_id, $with_late_pays);
                $bankList = $negativeAndLatePayList['negative'];
                $latepayList = $negativeAndLatePayList['latepays'];
                $banklist_index_less = [];
                $banklist_index_less_assoc = [];
                if(!empty($bankList)){
                    foreach($bankList as $b){
                        $bnk = preg_replace('/-[^-]*$/', '', $b);
                        if(!empty($bnk)){
                            $banklist_index_less[] = $bnk;
                            $banklist_index_less_assoc[$b] = $bnk;
                        }
                    }
                }
                
                $responseArray = [
                    'latepayList' => $latepayList,
                    'bankList' => $bankList,
                    'banklist_index_less'=>$banklist_index_less,
                    'banklist_index_less_assoc'=>$banklist_index_less_assoc,
                    'client_id' => $client_id,
                    'dd_id' => $dd_id
                ];
            }
        }

        echo json_encode($responseArray);
        die();
    }

    private function sourceDropDownHTML($sertg_id) {
        $selected_key = 0;
        if ($sertg_id > 0) {
            $member_id = $this->Auth->user('id');
            $this->loadModel('Sertg');
            $sertg = $this->Sertg->getSertgById($sertg_id, $member_id);
            if (!empty($sertg)) {
                $selected_key = $sertg->report_type;
            }
        }

        $html = '<div class="form-group">
                    <label class="col-sm-5 control-label">Source</label>
                    <div class="col-sm-7">
                        <select onchange="reportchange(this)" name="report_type" class="form-control">';
        if (!empty(REPORT_SOURCE_TYPES)) {
            foreach (REPORT_SOURCE_TYPES as $key => $value) {
                $selected = '';
                if ($key == $selected_key) {
                    $selected = 'selected';
                }
                $html .= '<option  value="' . $key . '" ' . $selected . '>' . $value . '</option>';
            }
        }
        $html .= '</select>
                    </div>
                </div>';
        $result['html'] = $html;
        $result['export_type'] = $selected_key;
        return $result;
    }

    public function form($form_id, $sertg_id = 0) {
        $user_type_name = $this->getCurrentUserType();
       
        if($_SESSION["userType"] == CRM_USER_INDICATOR){
          // echo $_SESSION['crm_has_velocity'];exit;
            if($form_id == SERTG_VELOCITY_FORM_ID && $_SESSION['crm_has_velocity'] != 1){
                return $this->redirect(['controller'=>'Statistics','action'=>'index']);
            }else if($form_id != SERTG_VELOCITY_FORM_ID && !isset($_SESSION['has_super_rtg_user'])){
               
                return $this->redirect(['controller'=>'Statistics','action'=>'index']);
            }
       }

       
        $member_id = $this->Auth->user('id');
        $step_status = $this->setSteps('is_send_first_letter', $member_id);
        $employee_id = 0;
        $member_email = $this->Auth->user('email');
        $form_name_list = $this->request->session()->read('form_name_list');
        $letter_dropdown = '';
        $letter_email_signature_text = '';
        $isNotAllclientAccess = $this->isAccessAllClients();
        $this->loadModel('MemberPackages');
        $this->loadModel('RtgLetters');

        $rtg_letter = "";
        $hasRTGAccessPkg = false;
        $hasRtgLsFaxPkg = false;
        $is_show_address_dropdown = true;
        $member_pkg_list = $this->MemberPackages->hasSuperRTGAccessPkgByMemberId($member_id);
        if (in_array(SUPER_RTG_ACCESS_PKG_ID, $member_pkg_list)) {
            $hasRTGAccessPkg = true;
        }
        
         if($user_type_name == "MEMBER"){
             if (in_array(SUPER_RTG_LS_FAX_PKG_ID, $member_pkg_list)) {
                $hasRtgLsFaxPkg = true;
            }
         }else if($user_type_name == "EMPLOYEE"){
            if (in_array(RTG_FOR_EMPLOYEES_PKG_ID, $member_pkg_list)) {
                $hasRtgLsFaxPkg = true;
            }
        }
        
        
        if($_SESSION['hasEpicVelocity'] || $_SESSION['hasVelocity'] || $hasRTGAccessPkg){
            $is_show_address_dropdown = false;
        }

        if ($hasRtgLsFaxPkg) {

            if($form_id != SERTG_VELOCITY_FORM_ID && $sertg_id > 0){
                $rtg_letter = $this->RtgLetters->getRtgLetterByIdWithMemberIdAndFormId($sertg_id,$member_id,$form_id);
                if(!empty($rtg_letter) && !empty($rtg_letter->data)){
                    $rtg_json_data_decoded = json_decode($rtg_letter->data,true);
                    $rtg_json_data_decoded['image1'] = $this->fileNotExistReturnEmpty($rtg_json_data_decoded['image1']);
                    $rtg_json_data_decoded['image2'] = $this->fileNotExistReturnEmpty($rtg_json_data_decoded['image2']);
                    $rtg_json_data_decoded['image3'] = $this->fileNotExistReturnEmpty($rtg_json_data_decoded['image3']);
                    $rtg_json_data_decoded['image4'] = $this->fileNotExistReturnEmpty($rtg_json_data_decoded['image4']);
                    $rtg_json_data_decoded['image5'] = $this->fileNotExistReturnEmpty($rtg_json_data_decoded['image5']);
                    $rtg_letter->data = json_encode($rtg_json_data_decoded);
                }
                //pr($rtg_letter->data);exit;
                
            }
        }
        //SUPER_RTG_ACCESS_PKG_ID
        if ($isNotAllclientAccess) {
            $employee_id = $this->Auth->user('user_id');
        }
        $formsTable = TableRegistry::get('Forms');
        $thisForm = $formsTable->find('all')
                // ->select(['short_name','long_name'])
                ->where([
                    'Forms.status' => 1,
                    'Forms.id' => $form_id
                ])
                ->contain(['Categories'])
                ->first();

        if (isset($_SESSION['crm_has_velocity']) && $_SESSION['crm_has_velocity'] == 1) {
            $form_name_list[SERTG_VELOCITY_FORM_ID] = 'SERTG';
        }

        
        $this->loadModel('Cmsusers');
        $cmsuser = $this->Cmsusers->find()->select(['Cmsusers.is_show_option_to_send_letter', 'Cmsusers.letter_email_signature'])->where(['id' => $this->Auth->user('id')])->first();
        if ($thisForm->type == 1 || in_array($form_id, array_flip($form_name_list))) {
            $base_url = APP_SERVER_HOST_URL;


            if (!empty($thisForm->short_name)) {
                $result['form_title'] = $thisForm->short_name;
            } else {
                $result['form_title'] = '';
            }
            if (!empty($thisForm->text_before_video)) {
                $result['text_before_video'] = $thisForm->text_before_video;
            } else {
                $result['text_before_video'] = '';
            }
            if (!empty($thisForm->text_after_video)) {
                $result['text_after_video'] = $thisForm->text_after_video;
            } else {
                $result['text_after_video'] = '';
            }
            if (!empty($thisForm->video_url)) {
                $result['video_url'] = $thisForm->video_url;
            } else {
                $result['video_url'] = '';
            }

            if ($form_id == WAVE_1_PKG_HOW_TO_START_FORM_ID) {
                $result['img_after_video'] = APP_SERVER_HOST_URL . WAVE_1_PKG_HOW_TO_START_IMAGE_URL;
            } else if ($form_id == WAVE_2_PKG_HOW_TO_START_FORM_ID) {
                $result['img_after_video'] = APP_SERVER_HOST_URL . WAVE_2_PKG_HOW_TO_START_IMAGE_URL;
            }

            $category_id = $thisForm->category_id;
            $folderName = '';
            if ($thisForm->category)
                $folderName = $thisForm->category->name . '/';

            if (!empty($thisForm->long_name)) {
                $long_name = str_replace(' ', '-', $thisForm->long_name);

                $file_dir = $folderName . $long_name . '.html';
                if (ENVIROMENT == 3) {
                    //echo $file_dir;
                }

                $fileContent = file_get_contents($file_dir);
                $fileContent = str_replace("__SERVER_URL__", APP_SERVER_HOST_URL, $fileContent);
                $this->loadModel('MemberPackages');
                $isVelocityUser = $this->MemberPackages->isVelocityuser($member_id);

                if ($_SESSION['userType'] == CMS_USER_INDICATOR || $_SESSION['crm_has_velocity'] == 1) {
                    $settingsTable = TableRegistry::get('settings');
                    $settings = $settingsTable->find()->toArray()[0];
                    $fileContent = str_replace("__USER_TYPE__", $_SESSION['userType'], $fileContent);
                    if (!$isVelocityUser) {
                        $fileContent = str_replace("__IS_VELOCITY_USER__", "velocity-user-hide", $fileContent);
                    }
                    $fileContent = str_replace("__MEMBER_ID__", $member_id, $fileContent);
                    $fileContent = str_replace("_DISPLAY_NONE__", 'style="display:block"', $fileContent);
                    $static_image_path = APP_SERVER_HOST_URL;
                    if (ENVIROMENT == 1) {
                        $static_image_path = "/../";
                    }
                    $fileContent = str_replace("__ADMIN_ACC_ENHANCE_IMAGE__", $static_image_path . $settings->enhance_img, $fileContent);
                    $fileContent = str_replace("__ADMIN_ACC_INQUIRY_IMAGE__", $static_image_path . $settings->inquiry_img, $fileContent);

                    $fileContent = str_replace(".rebuttal-class3", '.rebuttal-class', $fileContent);
                    $fileContent = str_replace(".rebuttal-class4", '.rebuttal-class1', $fileContent);
                    if($form_id != SERTG_VELOCITY_FORM_ID){
                        $html = $this->generateLetterTypeHtml(true);
                    }else{
                        $html = $this->generateLetterTypeHtml();
                    }
                    
                    $fileContent = str_replace("__LETTER_TYPES__", $html, $fileContent);
                    $dropdown_html = $this->generateExportDropDownByMemberId();
                    $dropdown = $dropdown_html['ALL_EXPORT_TYPES'];
                    $dropdown_ls_fax = $dropdown_html['LS_AND_FAX_TYPES'];

                    if ($cmsuser->is_show_option_to_send_letter == 1) {
                        $letter_dropdown = $this->letterDropdown(false);
                        $letter_email_signature_text = $cmsuser->letter_email_signature;
                    }
                    $automationHTML = $this->setAutomationHTML();
                    if (!empty($letter_dropdown)) {
                        $letter_dropdown .= $automationHTML;
                    } else {
                        $letter_dropdown = $automationHTML;
                    }
                    $sertgInfo = $this->sourceDropDownHTML($sertg_id);
                    if ($sertgInfo['export_type'] == 0) {
                        $sertgInfo['export_type'] = "";
                    }
                    //pr($sertgInfo['export_type']);exit;
                    
                    $fileContent = str_replace("__TEMEP_REPORT_TYPE__", $sertgInfo['export_type'], $fileContent);
                    $fileContent = str_replace("__REPORT_SOURCE_TYPES__", $sertgInfo['html'], $fileContent);
                    $fileContent = str_replace("__LETTER_EMAIL_SIGNATURE__", htmlentities($letter_email_signature_text), $fileContent);
                    $fileContent = str_replace("__LETTER_DROPDOWN__", $letter_dropdown, $fileContent);
                    $fileContent = str_replace("__DAY_SELECTION_DROPDOWN__", $this->setNextDayIntervalDropdown(), $fileContent);
                    $fileContent = str_replace("__EXPORT_TYPE_DROPDOWN__", $dropdown, $fileContent);
                    $fileContent = str_replace("__MEMBER_EMAIL__", $member_email, $fileContent);
                    $fileContent = str_replace("__ONLOAD_ID__", $sertg_id, $fileContent);
                    $fileContent = str_replace("__EMPLOYEE_ID__", $employee_id, $fileContent);
                    $employee_radio_checkbox_html = $this->employeecheckboxHTML();
                    if ($_SESSION['userType'] == CMS_USER_INDICATOR) {
                        $fileContent = str_replace('__EMPLOYEE_CHECKBOX__', $employee_radio_checkbox_html['checkbox'], $fileContent);
                        $fileContent = str_replace('__EMPLOYEE_RADIO_BUTTON__', $employee_radio_checkbox_html['radio'], $fileContent);
                        $fileContent = str_replace('__IS_EMPLOYEE__', '<input type="hidden" name="isEmplyee" value="0">', $fileContent);
                        if ($step_status == 0) {
                            $fileContent = str_replace('__STEP_STATUS__', '<input type="hidden" name="step_status" value="0">', $fileContent);
                        }
                    } else {
                        $fileContent = str_replace('__EMPLOYEE_CHECKBOX__', '', $fileContent);
                        $fileContent = str_replace('__EMPLOYEE_RADIO_BUTTON__', '', $fileContent);
                        $fileContent = str_replace('__IS_EMPLOYEE__', '<input type="hidden" name="isEmplyee" value="1">', $fileContent);
                    }
                    $fileContent = str_replace("__STEP_STATUS__", '<input type="hidden" name="step_status" value="1">', $fileContent);
                    $fileContent = str_replace("__SAVE_LETTER__", $this->saveLetterHTML(), $fileContent);

                }

                if ($form_id != SERTG_VELOCITY_FORM_ID && $hasRtgLsFaxPkg) { 
                    $letter_dropdown = $this->letterDropdown().$automationHTML;
                    $fileContent .= $this->rtgSubmitModal($dropdown_ls_fax, $html, $letter_dropdown);
                    $fileContent .= $this->letterStreamModalForRTGLetters();
                }

            } else {
                $fileContent = '';
            }

            
            $result['form_body'] = $fileContent;
            $this->set('rtg_letter',$rtg_letter);
            $this->set(compact('result', 'form_id', 'hasRTGAccessPkg', 'hasRtgLsFaxPkg','is_show_address_dropdown'));
        } else {
            
            $this->Flash->error(__('You do not have permission to access this form'));
            $this->redirect(['controller' => 'Dashboard', 'action' => 'index']);
        }


        //$this->viewBuilder()->layout("new_dashboard");
        // // dashboard functionality start here
        // $user = $this->Auth->user();
        // $allForms = $this->_getAllFormsByUser($user);
        // $this->set('allForms', $allForms[0]);
        // $settingData = $this->_getSettingData();
        // $this->set(compact('settingData'));
        // $resultJson = json_encode($result);
        // $this->response->type('json');
        // $this->response->body($resultJson);
        // return $this->response;
    }

    private function fileNotExistReturnEmpty($image){
        $result = $image;
        if(!is_file($image)){
            $result = "";       
        }
        
        return $result;
    }

    private function setNextDayIntervalDropdown(){
        $day_selection_dropdown = '<select onchange="autoSelectNextDate(this)" name="next_day" id="next_day" class="form-control">';
        $day_selection_dropdown .= '<option value="">Please Select</option>';
        foreach(NEXT_DATE_INTERVAL_DAYS as $key => $day){
            $day_selection_dropdown .= '<option value="'.$key.'">'.$day.'</option>';
        }
        $day_selection_dropdown .="</select>";
        
        return $day_selection_dropdown;
    }
    
    private function set_STT_PI_LETTER_SET_Dropdown(){
        
//        $day_selection_dropdown = '<span class="multiselect-native-select">
//    
//                    <div class="btn-group" style="width: 100%;">
//                            <button type="button" class="multiselect dropdown-toggle btn btn-default" data-toggle="dropdown" title="Assign To" style="width: 100%; overflow: hidden; text-overflow: ellipsis;" aria-expanded="false">
//                                <span class="multiselect-selected-text">No selected</span> 
//                                <b class="caret"></b>
//                            </button> 
//                        <ul class="multiselect-container dropdown-menu" style="width:100%;">';
//                            foreach(STT_PI_LETTER_SET as $key => $day){
//                                if(!isset($_SESSION['hasVelocity']) && $key == 13){
//                                    continue;
//                                }
//                                $day_selection_dropdown .= '<li class="">
//                                                            <a tabindex="0">
//                                                                <label class="checkbox" style="font-weight:400;">
//                                                                    <input name="stt_pi_letter_set[]" class="stt_pi_letter_set" type="checkbox"  value="'.$key.'" onclick="$(`.stt_pi_letter_set:checked`).length > 0 ? $(`.multiselect-selected-text`).html($(`.stt_pi_letter_set:checked`).length+` selected`) : $(`.multiselect-selected-text`).html(`No selected`)" /> 
//                                                                    '.$day.'
//                                                                    </label>
//                                                                </a>
//                                                            </li>';
//                            }
//                                                                
//                                       
//                        $day_selection_dropdown .='</ul>
//                                                    </div>
//                                                </span><span class="pull-right" style="position: absolute;top: 32px;right: 14px;">
//                                                <a href="#" onclick="event.preventDefault();$(`.stt_pi_letter_set`).prop(`checked`,false);$(`.multiselect-selected-text`).html(`No selected`);">
//                                                <i class="fa fa-eraser" aria-hidden="true"></i>
//                                                Clear
//                                                </a> 
//                                                </span>';

        
        //$day_selection_dropdown .="</select>";
        $day_selection_dropdown = "";
        $view = new View($this->request,$this->response);
        $view->layout = false;
        $day_selection_dropdown = $view->render('Element/letter_set_dropdown');
        return $day_selection_dropdown;
    }

    private function saveLetterHTML(){
        $html = "";
        if($this->Auth->user('is_allow_store_letters')) {
            $checked = $this->Auth->user('is_default_checked_saved_letter') == 1 ? 'checked':'';

            $html = <<<END
                    <div class="col-md-3">
                        <div class="form-group">
                            <div class="radio dload">
                                <label>
                                    <input type="radio" value="3" name="download_type" class=""  $checked/>
                                    Save Letter
                                </label>
                            </div>
                        </div>
                </div>
            END;
        }
        return $html;
    }

    private function rtgSubmitModal($dropdown, $html, $letter_dropdown) {

        $checked = $this->Auth->user('is_default_checked_saved_letter') == 0 ? 'checked':'';
        $html = '<div id="rtg-before-saving-modal" class="modal fade" data-backdrop="static" data-keyboard="false" role="dialog">
    <div class="modal-dialog modal-md">

        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" style="top:30%;color: white;"><i class="fa fa-close"></i></button>
                <h4 class="modal-title" id="formModalLabel">
                    What Type Of Letter Would You Like To Save This As: Check Below 1 Or Multiple
                </h4>
            </div>
            <div class="modal-body">
            <div class="row">
                                        <div class="col-md-12">
                                            <dl class="dropdown-x">
                                                <dt>
                                                    <div>
                                                        <a onclick="chooseDropDown(this);" href="javascript:;">
                                                            <span class="choose-dest">Choose Item</span>
                                                            <p class="multiSel"></p>
                                                        </a>
                                                    </div>
                                                </dt>
                                                <dd>
                                                    <div class="mutliSelect" id="maindestination">
                                                        ' . $html . '
                                                    </div>
                                                </dd>

                                            </dl>
                                        </div>
                                    </div>
                                    <br/>
                <div class="download-area __IS_VELOCITY_USER__" style="margin-left: 15px;">
                    <div class="row">
                        <div class="col-md-3">
                            <div class="form-group">
                                <div class="radio dload">
                                    <label>
                                        <input type="radio" value="1" name="download_type" class="" '.$checked.' disable="false">
                                        Download
                                    </label>
                                </div>
                            </div>
                        </div>
                        '.$this->saveLetterHTML().'
                    </div>
                    <div class="row">
                        <div class="col-md-3">
                            <div class="form-group">
                                <div class="radio dload">
                                    <label>
                                        <input type="radio" value="2" name="download_type" class="" disable="false">
                                        Download as
                                    </label>
                                </div>

                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group" style="margin-right: 0;">
                               ' . $dropdown . '
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="checkbox">
                                <label>
                                    <input type="checkbox" onclick="checkAllExport(this)" name="checkallExport" disabled=""> Check all
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
                <div id="date-action" style="margin-left: 15px;">
                                        <div class="row">
                                            <div class="col-md-3" style="padding-left: 0;">
                                                <label class="control-label">Date Of Next Action</label>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="form-group" style="margin-right: 0;">
                                                    <div class="input-group date date-only">
                                                        <input type="text" placeholder="Please select date" name="next_section_date" class="form-control" readonly />
                                                        <div class="input-group-addon">
                                                            <span class="glyphicon glyphicon-th"></span>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                            '.$this->setNextDayIntervalDropdown().'
                                            </div>
                                        </div>
                                        '.$letter_dropdown.'
                                    </div>
            </div>
            <div class="modal-footer">

                <span>
                    <img style="display:none" id="saveloading" class="rtg-loading-img" src="' . APP_SERVER_HOST_URL . 'images/ajax-loader.gif">
                </span> &nbsp;
                <button type="button" data-type="0" id="rtg-before-save" class="btn btn-default btn-orange-color">Save</button>
                <button type="button" id="before-cancel" class="btn btn-default btn-orange-color" data-dismiss="modal">Cancel</button>
            </div>
        </div>

    </div>
</div>';

        return $html;
    }

    private function employeecheckboxHTML() {
        $employee_checkbox_html = '<div class="col-sm-3 client-status">
                                        <div class="checkbox">
                                            <label>
                                                <input type="checkbox" value="2" onclick="employeeShow(this)" name="employee_client_type"> 
                                                Show employee clients
                                                <img id="employee-loader" src="' . APP_SERVER_HOST_URL . 'images/ajax-loader.gif" style="display: none;width: 15px;">
                                            </label>
                                        </div>
                                    </div>';
        $employee_radio_button_html = '<div class="col-sm-3 client-status">
                                            <div class="radio">
                                                <label>
                                                    <input type="radio" value="1" onclick="affiliateFormShow(this)" name="client_type"> 
                                                    Show employee clients
                                                    <img id="employee-loader-form" src="' . APP_SERVER_HOST_URL . '/images/ajax-loader.gif" style="display: none;width: 15px;">
                                                </label>
                                            </div>
                                        </div>';
        $html['checkbox'] = $employee_checkbox_html;
        $html['radio'] = $employee_radio_button_html;
        return $html;
    }

    // all forms comes according to sub_category
    function _getAllFormsByUser_bk($user) {
        $connection = ConnectionManager::get('default');
        $packages = $connection->execute("SELECT mp.member_id,mp.package_id, pf.form_id, frm.category_id,
            frm.sub_category_id,frm.short_name form_short_name,
            frm.long_name form_long_name,frm.description form_description,
            frm.video_url form_video_url, sc.name sub_category_name
        FROM member_packages mp
        INNER JOIN package_forms pf ON pf.package_id = mp.package_id
        INNER JOIN forms frm ON frm.id = pf.form_id
        INNER JOIN sub_categories sc ON sc.id = frm.sub_category_id
        WHERE mp.status = 1 AND mp.member_id = " . $user['id'])->fetchAll('assoc');

        $allForms = [];
        $allFormNames = [];
        if (!empty($packages)) {
            foreach ($packages as $key => $value) {
                $allForms[$value['sub_category_id']]['name'] = $value['sub_category_name'];
                $allForms[$value['sub_category_id']]['forms'][$value['form_id']] = $value;
                $allFormNames[$value['form_id']] = $value['form_long_name'];
            }
        }
        // pr($allForms);
        return array($allForms, $allFormNames);
    }

    // all forms comes according to package
    function _getAllStaticForms() {
        $connection = ConnectionManager::get('default');
        $packages_query = "SELECT 
            pf.package_id, 
            pf.form_id, 
            frm.category_id,
            frm.sub_category_id,
            frm.short_name form_short_name,
            frm.long_name form_long_name,
            frm.description form_description,
            frm.video_url form_video_url, 
            sc.name sub_category_name,
            pkg.name package_name
        FROM packages pkg 
        INNER JOIN package_forms pf ON pf.package_id = pkg.id
        INNER JOIN forms frm ON frm.id = pf.form_id
        INNER JOIN sub_categories sc ON sc.id = frm.sub_category_id
        WHERE pkg.type = 1 
        ORDER BY pkg.id ASC, frm.weight asc";
        $packages = $connection->execute($packages_query)->fetchAll('assoc');
        //pr($packages); die;

        $allForms = [];
        $allFormNames = [];
        if (!empty($packages)) {
            foreach ($packages as $key => $value) {
                $allForms[$value['package_id']]['name'] = $value['package_name'];
                $allForms[$value['package_id']]['forms'][$value['form_id']] = $value;
                $allFormNames[$value['form_id']] = $value['form_long_name'];
            }
        }
        // pr($allForms);
        return array($allForms, $allFormNames);
    }

    // all forms comes according to package
    function _getAllFormsByUser($user, $package_type = null) {
     
        if (!empty($user)) {
            
            $connection = ConnectionManager::get('default');
            $packages_query = "SELECT mp.member_id,mp.package_id, pf.form_id, 
            frm.category_id,
            frm.sub_category_id,
            frm.short_name form_short_name,
            frm.long_name form_long_name,
            frm.description form_description,
            frm.video_url form_video_url, 
            sc.name sub_category_name,
            pkg.name package_name
        FROM member_packages mp
        INNER JOIN packages pkg ON pkg.id = mp.package_id
        INNER JOIN package_forms pf ON pf.package_id = mp.package_id
        INNER JOIN forms frm ON frm.id = pf.form_id
        INNER JOIN sub_categories sc ON sc.id = frm.sub_category_id
        WHERE pkg.type = " . $package_type . " AND mp.status = 1 AND mp.member_id = " . $user['id'] . "
        ORDER BY pkg.id ASC, frm.weight asc";
            $packages = $connection->execute($packages_query)->fetchAll('assoc');
        }
        //pr($packages); die;

        $allForms = [];
        $allFormNames = [];

        $hasValocityAccess = false;

        if (!empty($packages)) {
            foreach ($packages as $key => $value) {

                if ($value['form_id'] == SERTG_VELOCITY_FORM_ID && !$hasValocityAccess) {
                    $hasValocityAccess = true;
                    $this->request->session()->write("user_has_velocity_access", 1);
                }

                $allForms[$value['package_id']]['name'] = $value['package_name'];
                $allForms[$value['package_id']]['package_id'] = $value['package_id'];
                $allForms[$value['package_id']]['forms'][$value['form_id']] = $value;
                $allFormNames[$value['form_id']] = $value['form_long_name'];
            }
        }

        return array($allForms, $allFormNames);
    }

    // all forms comes according to package
    function _getPackageWiseAllForms($package_id = null) {
        $connection = ConnectionManager::get('default');
        $packages_query = "SELECT 
            pf.package_id, 
            pf.form_id, 
            frm.category_id, frm.sub_category_id, 
            frm.short_name form_short_name, 
            frm.long_name form_long_name, 
            frm.description form_description, 
            frm.video_url form_video_url, 
            sc.name sub_category_name, 
            pkg.name package_name 

            FROM package_forms pf 
            INNER JOIN packages pkg ON pkg.id = pf.package_id 
            INNER JOIN forms frm ON frm.id = pf.form_id 
            INNER JOIN sub_categories sc ON sc.id = frm.sub_category_id

            WHERE pkg.id = $package_id 
            ORDER BY pkg.id ASC, frm.weight ASC";

        $packages = $connection->execute($packages_query)->fetchAll('assoc');
        // pr($packages); die;

        $allForms = [];
        if (!empty($packages)) {
            foreach ($packages as $key => $value) {
                $allForms[$value['package_id']]['name'] = $value['package_name'];
                $allForms[$value['package_id']]['forms'][$value['form_id']] = $value;
            }
        }
        return $allForms;
    }

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

    public function editProfile() {
        if ($this->Auth->user()) {
            $current_user_type = $this->getCurrentUserType();
            $common  = new Common();
            $step_name = 'is_account_profile_set';
            if ($current_user_type == 'EMPLOYEE' || $current_user_type == 'AFFILIATE') {
                return $this->employeeditprofile();
                
            } else {
                if($current_user_type != 'MEMBER'){
                    $this->redirect($this->referer());
                }
                // dashboard functionality start here
                $user = $this->Auth->user();

                // $allForms = $this->_getAllFormsByUser($user);
                // $this->set('allForms', $allForms[0]);
                // $settingData = $this->_getSettingData();
                // $this->set(compact('settingData'));

                $id = $this->Auth->user('id');
                $this->loadModel('Personalizes');
                $personalize = $this->Personalizes->getPersonalizeByMemberId($id);
                $this->set(compact('personalize'));
                $is_client_credit_login_details = "";
                $is_receive_notification_selcted = '';
                $is_show_option_to_send_letter_selected = '';
                $letter_email_signature = '';
                if ($_SESSION['userType'] == 4) {
                    $id = $this->Auth->user('user_id');
                }

                $_SESSION['zapier_appkey'] = $this->Auth->user('zapier_appkey');
                $this->loadModel('Cmsusers');
                //$zapier_appkey = $_SESSION['zappier_appkey'];

                $cmsuser = $this->Cmsusers->get($id, [
                    'contain' => []
                ]);
                //pr($cmsuser);exit;
                if (empty($_SESSION['zapier_appkey'])) {
                    $cmsuser->zapier_appkey = $this->getSecretKey($id);
                    $this->Cmsusers->save($cmsuser);
                    $_SESSION['zapier_appkey'] = $cmsuser->zapier_appkey;
                } else {
                    $cmsuser->zapier_appkey = $_SESSION['zapier_appkey'];
                }
                if ($cmsuser->is_show_option_to_send_letter == 1) {
                    $is_show_option_to_send_letter_selected = 'checked';
                }

                if ($cmsuser->is_client_credit_login_details == 1) {
                    $is_client_credit_login_details = 'checked';
                }

                if ($cmsuser->is_receive_notification == 1) {
                    $is_receive_notification_selcted = 'checked';
                }

                if (isset($cmsuser->letter_email_signature) && !empty($cmsuser->letter_email_signature)) {
                    $isletter_email_signature = $cmsuser->letter_email_signature;
                }
                
                $is_default_checked_letterstrem_return_address_checkbox = "";
                if ($cmsuser->is_default_checked_letterstrem_return_address_checkbox == 1) {
                    $is_default_checked_letterstrem_return_address_checkbox = "checked";
                }
                
                $is_default_checked_send_email_checkbox = "";
                if ($cmsuser->is_default_checked_send_email_checkbox == 1) {
                    $is_default_checked_send_email_checkbox = "checked";
                }
                $is_auto_login_enable = "";
                if ($cmsuser->is_client_auto_login == 1) {
                    $is_auto_login_enable = "checked";
                }

                $is_allow_store_letters = "";
                if ($cmsuser->is_allow_store_letters == 1) {
                    $is_allow_store_letters = "checked";
                }

                $is_default_checked_saved_letter = "";
                if ($cmsuser->is_default_checked_saved_letter == 1) {
                    $is_default_checked_saved_letter = "checked";
                }
                //pr($cmsuser);exit;
                $isValidImage = true;
                if ($this->request->is(['patch', 'post', 'put'])) {
                    $step_status = $this->request->data['step_status'];
                    $contact_name = $this->request->data['contact_name'];
                    if (!empty($this->request->data['img_path']['name'])) {

                        $image_dimension = getimagesize($this->request->data['img_path']['tmp_name']);
                        $image_height = $image_dimension[1];
                        $image_width = $image_dimension[0];

                        if ($image_height > PROFILE_IMAGE_SIZE['height'] || $image_width > PROFILE_IMAGE_SIZE['width']) {
                            $this->Flash->error(__('Profile Picture should be less than ' . PROFILE_IMAGE_SIZE['height'] . ' px in height and ' . PROFILE_IMAGE_SIZE['width'] . ' px in width.Please try again!'));
                            $isValidImage = false;
                            //return $this->redirect(['action' => 'editProfile']);
                        } else {

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


                    if (!empty($this->request->data['logo']['name'])) {

                        $image_dimension = getimagesize($this->request->data['logo']['tmp_name']);
                        $image_height = $image_dimension[1];
                        $image_width = $image_dimension[0];

                        if ($image_height > LOGO_SIZE['height'] || $image_width > LOGO_SIZE['width']) {
                            $this->Flash->error(__('Logo should be less than ' . LOGO_SIZE['height'] . ' px in height and ' . LOGO_SIZE['width'] . ' px in width.Please try again!'));
                            $isValidImage = false;
                            // return $this->redirect(['action' => 'editProfile']);
                        } else {

                            if (!is_dir('cmsuser_logo')) {
                                mkdir('cmsuser_logo', 0777, true);
                            }
                            $insertedId = $this->Auth->user('id');
                            $logofile = $this->request->data['logo'];
                            $ext = substr(strtolower(strrchr($logofile['name'], '.')), 1);
                            $logoname = explode('.', $logofile['name'])[0];
                            $arr_ext = array('jpg', 'jpeg');
                            if (!in_array($ext, $arr_ext)) {
                                $ext = 'jpg';
                            }

                            $newname = $logoname . "_" . $insertedId . "." . $ext;
                            $this->request->data['logo'] = $newname;
                            @unlink(CMSUSER_LOGO . $this->request->data['previous_logo']);
                            $this->uploadlogo($newname, $ext);
                        }
                    } else {
                        $this->request->data['logo'] = $this->request->data['previous_logo'];
                    }
                    if ($isValidImage) {
                        $cmsuser->is_client_credit_login_details = isset($this->request->data['is_client_credit_login_details']) ? 1 : 0;
                        $cmsuser->identity_iq_link = $this->request->data['identity_iq_link'];
                        $cmsuser->smart_credit_link = $this->request->data['smart_credit_link'];
                        $cmsuser->website = $this->request->data['website'];
                        $cmsuser->contact_email = $this->request->data['contact_email'];
                        $cmsuser->company_name = $this->request->data['company_name'];
                        $cmsuser->contact_name = $this->request->data['contact_name'];
                        $cmsuser->address_one = $this->request->data['address_one'];
                        $cmsuser->address_two = $this->request->data['address_two'];
                        $cmsuser->city = $this->request->data['city'];
                        $cmsuser->state = $this->request->data['state'];
                        $cmsuser->address_zip = $this->request->data['address_zip'];
                        $cmsuser->time_zone = $this->request->data['time_zone'];
                        $cmsuser->is_receive_notification = isset($this->request->data['is_receive_notification']) ? 1 : 0;
                        $cmsuser->is_default_checked_send_email_checkbox = isset($this->request->data['is_default_checked_send_email_checkbox']) ? 1 : 2;
                        $cmsuser->is_default_checked_letterstrem_return_address_checkbox = isset($this->request->data['is_default_checked_letterstrem_return_address_checkbox']) ? 1 : 2;
                        $cmsuser->is_show_option_to_send_letter = isset($this->request->data['is_show_option_to_send_letter']) ? 1 : 0;
                        $cmsuser->letter_email_signature = isset($this->request->data['letter_email_signature']) ? nl2br($this->request->data['letter_email_signature']) : '';
                        $cmsuser->letter_email_signature = htmlentities($cmsuser->letter_email_signature);
                        $cmsuser->is_client_auto_login = isset($this->request->data['is_auto_login_enable']) ? 1 : 0;
                        $cmsuser->is_allow_store_letters = isset($this->request->data['is_allow_store_letters']) ? 1 : 0;
                        $cmsuser->is_default_checked_saved_letter = isset($this->request->data['is_default_checked_saved_letter']) ? 1 : 0;
                        //pr($cmsuser->letter_email_signature);exit;



                        //$this->request->session()->write('Auth.User.username', $this->request->data['username']);
                        $cmsuser = $this->Cmsusers->patchEntity($cmsuser, $this->request->data);
                        unset($cmsuser->username); // disabled username
                        //pr($cmsuser);exit;
                        if ($saved_user = $this->Cmsusers->save($cmsuser)) {
                            $this->request->session()->delete('Auth.User.identity_iq_link');
                            $this->request->session()->delete('Auth.User.smart_credit_link');
                            $this->request->session()->delete('Auth.User.is_allow_store_letters');
                            if(!empty($cmsuser->identity_iq_link)){
                                $this->request->session()->write('Auth.User.identity_iq_link', $cmsuser->identity_iq_link);
                            }
                            if(!empty($cmsuser->smart_credit_link)){
                                $this->request->session()->write('Auth.User.smart_credit_link', $cmsuser->smart_credit_link);
                            }

                            $this->request->session()->write('Auth.User.is_allow_store_letters', $cmsuser->is_allow_store_letters);
                            $this->request->session()->write('Auth.User.is_default_checked_saved_letter', $cmsuser->is_default_checked_saved_letter);

                            $this->request->session()->write('Auth.User.contact_name', $this->request->data['contact_name']);
                            $this->request->session()->write('Auth.User.company_name', $this->request->data['company_name']);
                            $this->request->session()->write('Auth.User.time_zone', $this->request->data['time_zone']);
                            $this->request->session()->write('Auth.User.is_default_checked_letterstrem_return_address_checkbox', $this->request->data['is_default_checked_letterstrem_return_address_checkbox']);
                            $this->request->session()->write('Auth.User.is_default_checked_send_email_checkbox', $this->request->data['is_default_checked_send_email_checkbox']);
                            if ($step_status == 0) {
                                $this->loadModel('CmsuserStatus');
                                $this->CmsuserStatus->upgradeCmsuserStatus($id, $step_name);
                                $this->redirect(["controller" => 'Statistics', "action" => "index"]);
                            }
                            $this->request->session()->write('Auth.User.logo', $saved_user->logo);    
                            //$contact_name
                            $this->request->session()->write('Auth.User.contact_name', $contact_name);
                            $this->Flash->success(__('Profile has been updated.'));
                            //$this->redirect('/dashboard');
                            return $this->redirect($this->referer());
                        } else {
                            $this->Flash->error(__('The Profile could not be saved. Please, try again.'));
                        }
                    }
                } else {
                    $this->setSteps($step_name, $id);
                }

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

                $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('is_default_checked_saved_letter', $is_default_checked_saved_letter);
                $this->set('is_allow_store_letters', $is_allow_store_letters);
                $this->set('isletter_email_signature', $isletter_email_signature);
                $this->set('is_auto_login_enable', $is_auto_login_enable);
                $this->set('is_receive_notification_selcted', $is_receive_notification_selcted);
                $this->set('is_show_option_to_send_letter_selected', $is_show_option_to_send_letter_selected);
                $this->set('is_client_credit_login_details', $is_client_credit_login_details);
                $this->set('time_zone_list', $common->tz_key_value_list());
                $this->set('is_default_checked_letterstrem_return_address_checkbox', $is_default_checked_letterstrem_return_address_checkbox);
                $this->set('is_default_checked_send_email_checkbox', $is_default_checked_send_email_checkbox);
                $this->viewBuilder()->layout("new_dashboard");
            }
        } else {
            return $this->redirect($this->Auth->redirectUrl());
        }
    }

    private function uploadlogo($newname, $ext) {
        //get the extension
        $arr_ext = array('jpg', 'jpeg', 'png'); //set allowed extensions
        $inner_path = 'cmsuser_logo/' . $newname;
        $_SESSION['client_logo_path'] = $newname;
        $target_file = WWW_ROOT . $inner_path;
        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"]["tmp_name"],WWW_ROOT.'cmsuser_logo/'. $newname);
            //move_uploaded_file($_POST["logo_jpg"],WWW_ROOT.'cmsuser_logo/'. $newname);
            $data = str_replace('data:image/jpeg;base64,', '', $_POST["logo_jpg"]);
            $data = base64_decode($data);

            file_put_contents($target_file, $data);
            $image_size = filesize($target_file);
        } else {
            $this->Flash->error(__('Profile Picture is not in right format.Please, try again.'));
            return $this->redirect($this->referer());
        }
    }

    private function userIPreset($id) {
        $this->loadModel('Cmsusers');
        $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;
    }

    private function hasPackageForUser($user_id, $package_id) {
        $table_member_packages = TableRegistry::get("MemberPackages");
        $memberPackage = $table_member_packages->find('all')
                ->where([
                    'MemberPackages.member_id' => $user_id,
                    'MemberPackages.package_id' => $package_id,
                    'MemberPackages.status' => 1
                ])
                //->contain(['Packages'])
                //->order('MemberPackages.id desc')
                // ->contain(['Cmsusers', 'Packages'])
                ->toArray();
        // return $memberPackage;
        if (!empty($memberPackage)) {
            return true;
        }
        return false;
    }

    public function contact() {
        $this->loadModel('Notifications');
        $notification = $this->Notifications->newEntity();
        if ($this->request->is('post')) {
            $notification = $this->Notifications->patchEntity($notification, $this->request->data);
            $notification->user_id = $this->user_id;
            $notification->from_datetime = date('Y-m-d h:i:s');
            $notification->is_replied = 0;
            $notification->ip = $this->get_client_ip();
            if ($this->Notifications->save($notification)) {
                $this->Flash->success(__('The Message has been send.'));

                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->error(__('The Message could not be send. Please, try again.'));
            }
        }
        $this->set(compact('notification'));
        $this->set('_serialize', ['notification']);


        // if ($this->Auth->user())
        // {
        //     // dashboard functionality start here
        //     $user = $this->Auth->user();
        //     $allForms = $this->_getAllFormsByUser($user);
        //     $this->set('allForms', $allForms[0]);
        //     $settingData = $this->_getSettingData();
        //     $this->set(compact('settingData'));
        //     $this->viewBuilder()->layout("dashboard");
        // } else {
        //     return $this->redirect($this->Auth->redirectUrl());
        // }
    }

    public function upgrade($selectd_package = -1) {
        if ($this->request->is('post')) {

            $registration_obj = new RegistrationsController();
            $user = $this->Auth->user();

            $user_creation_time = $user['created_on'];
            $current_time = date('Y-m-d h:i:s');
            $user_days = $this->getDateDifference($user_creation_time, $current_time);

            if ($user_days >= PACKAGE_WAVE_UPGRADE_MINIMUM_DAYS) {

                if (is_numeric($this->request->data['package_id'])) {
                    $package_id = $this->request->data['package_id'];
                    $packagesPrice = $this->_getPackagePrice($package_id);
                    $stripe_customer_id = $user['stripe_customer_id'];
                    // die;
                    $chargeObj = $registration_obj->stripeCreateCharge($packagesPrice, $stripe_customer_id, $package_id);
                    if (!empty($chargeObj)) {
                        // add this package to this user
                        if ($registration_obj->addUserToPackages($user_id = $user['id'], $package_id)) {
                            $this->Flash->success(__('Your package is successfully upgraded.'));
                            return $this->redirect(['action' => 'index']);
                        } else {
                            $this->Flash->error(__('Your package could not be upgraded. Please, try again.'));
                        }
                    }
                } else {
                    $this->Flash->error(__('You cannot upgrade your package now. ID mismatch'));
                }
            } else {
                $this->Flash->error(__('You cannot upgrade your package now. You have to wait for ' . PACKAGE_WAVE_UPGRADE_MINIMUM_DAYS . ' days from your registration.'));
            }
        }

        $this->set('selected_package', $selectd_package);
        $this->viewBuilder()->layout("new_dashboard");
    }

    private function _getPackagePrice($package_id = null) {
        $package = [];
        $table_package = TableRegistry::get("Packages");
        $package = $table_package->find('all')
                ->select(['name', 'price'])
                ->where(['Packages.id' => $package_id])
                ->first();
        return $package->price;
    }

    private function isStaffUser($user, $CmsuserUsergroupsData = null) {

        $returnValue = false;

        if (empty($CmsuserUsergroupsData)) {
            $table = TableRegistry::get("CmsuserUsergroups");
            $CmsuserUsergroupsData = $table->find('all')
                    ->select(['usergroup_id'])
                    ->where(['CmsuserUsergroups.cms_user_id' => $user['id']])
                    ->first();
        }

        // pr($users); die;
        if (isset($CmsuserUsergroupsData) && $CmsuserUsergroupsData->usergroup_id == STAFF_GROUP_ID) {
            $returnValue = true;
        }
        return $returnValue;
    }

    public function getFormData() {
        if ($this->request->is('ajax')) {
            $sertgForm = TableRegistry::get('sertg')
                    ->find('all')
                    ->toArray();

            echo json_encode($sertgForm);
            die();
        }
    }

    public function getForm() {
        if ($this->request->is('ajax')) {
            $id = $this->request->data('id');
            $sertgForm = TableRegistry::get('sertg')
                    ->find('all')
                    ->where(['id' => $id])
                    ->toArray();

            echo json_encode($sertgForm);
            die();
        }
    }

    public function getDestination() {
        if ($this->request->is('ajax')) {
            $id = $this->request->data('id');
            $sertgDestination = TableRegistry::get('sertg_destination')
                    ->find('all')
                    ->where(['sertg_id' => $id])
                    ->toArray();
            $destinationArray = array();
            $destinationOtherArray = array();
            foreach ($sertgDestination as $destination) {
                $destinationArray[$destination->destination_id] = explode(",", $destination->addresses);
                $destinationOtherArray[$destination->destination_id] = $destination->other_address;
            }
            $destination = ['address' => $destinationArray, 'other' => $destinationOtherArray];

            echo json_encode($destination);
            die();
        }
    }

    public function getAccountDetail() {
        if ($this->request->is('ajax')) {
            $id = $this->request->data('id');
            if (!empty($id)) {
                $sertgAccount = TableRegistry::get('sertg_account')
                        ->find('all')
                        ->where(['sertg_id' => $id])
                        ->toArray();

                $count = 1;
                $accountArray = array();
                $accountDestination = array();
                foreach ($sertgAccount as $account) {

                    $account_number = explode(",", $account->acc_number);
                    $aspect_number = explode(",", $account->acc_aspect);
                    $account_derogatory = explode(",", $account->acc_derogatory);
                    $item_ownership = $account->ownership_item_issue;
                    $item_discontinaunce = $account->item_discontinuance;
                    $disable_indicator = $account->acc_disable_indicator;
                    $item_attack_num = $account->item_attack_num;
                    $sertgDestination = TableRegistry::get('sertg_destination_acc')
                            ->find()
                            ->select('sertg_dest_id')
                            ->where(['sertg_acc_id' => $account->id])
                            ->toArray();

                    $dest = array();
                    foreach ($sertgDestination as $destination) {
                        array_push($dest, $destination->sertg_dest_id);
                    }
                    //$accountDestination[$count] = $dest;
                    $accountArray[$count] = ['acc_number' => $account_number, 'acc_aspect' => $aspect_number, 'acc_derogatory' => $account_derogatory,
                        'acc_other' => $account->acc_other, 'acc_image' => $account->acc_image, 'acc_image_desc' => $account->acc_image_desc,
                        'acc_num_other' => $account->acc_num_other, 'acc_derogatory_other' => $account->acc_derogatory_other, 'destination' => $dest,
                        'item_ownership' => $item_ownership, 'item_discontinaunce' => $item_discontinaunce, 'disable_indicator' => $disable_indicator,
                        'item_attack_num' => $item_attack_num
                    ];


                    $count++;
                }

                echo json_encode($accountArray);
                die();
            }
        }
    }

    public function getAttachmentDetail() {
        if ($this->request->is('ajax')) {
            $id = $this->request->data('id');
            if (!empty($id)) {

                $sertgAttachment = TableRegistry::get('sertg_attachment')
                        ->find('all')
                        ->where(['sertg_id' => $id])
                        ->toArray();

                $count = 1;
                $attachmentArray = array();
                $attachmentDestination = array();
                foreach ($sertgAttachment as $attachment) {

                    $sertgDestination = TableRegistry::get('sertg_destination_attachment')
                            ->find()
                            ->select('sertg_dest_id')
                            ->where(['sertg_attachment_id' => $attachment->id])
                            ->toArray();

                    $dest = array();
                    foreach ($sertgDestination as $destination) {
                        array_push($dest, $destination->sertg_dest_id);
                    }

                    $attachmentArray[$count] = ['attachment' => $attachment->attachment, 'destination' => $dest];
                    $count++;
                }

                echo json_encode($attachmentArray);
                die();
            }
        }
    }

    public function deleteFormData() {
        if ($this->request->is('ajax')) {
            $id = $this->request->data('id');
            if (!empty($id)) {
                $sertgTable = TableRegistry::get('sertg');
                $sertg = $sertgTable->get($id);
                $sertgTable->delete($sertg);

                $sertgDestinationTable = TableRegistry::get('sertg_destination');
                $destinations = $sertgDestinationTable->find()->where(['sertg_id' => $id])->toArray();

                if (!empty($destinations[0])) {
                    foreach ($destinations as $destination) {
                        $sertgDestinationTable->delete($destination);
                    }
                }

                $sertgAccountTable = TableRegistry::get('sertg_account');
                $accounts = $sertgAccountTable->find()->where(['sertg_id' => $id])->toArray();
                if (!empty($accounts[0])) {
                    foreach ($accounts as $account) {
                        $sertgDestinationAccTable = TableRegistry::get('sertg_destination_acc');
                        $destinationAccs = $sertgDestinationAccTable->find()->where(['sertg_acc_id' => $account->id])->toArray();

                        if (!empty($destinationAccs[0])) {
                            foreach ($destinationAccs as $destinationAcc) {
                                $sertgDestinationAccTable->delete($destinationAcc);
                            }
                        }
                        @unlink('Staff/sertg/accounts/' . $account->acc_image);
                        $sertgAccountTable->delete($account);
                    }
                }

                $sertgAttachmentTable = TableRegistry::get('sertg_attachment');
                $attachments = $sertgAttachmentTable->find()->where(['sertg_id' => $id])->toArray();
                if (!empty($attachments[0])) {
                    foreach ($attachments as $attachment) {

                        $sertgDestinationAttTable = TableRegistry::get('sertg_destination_attachment');
                        $destinationAtts = $sertgDestinationAttTable->find()->where(['sertg_attachment_id' => $attachment->id])->toArray();

                        if (!empty($destinationAtts[0])) {
                            foreach ($destinationAtts as $destinationAtt) {
                                $sertgDestinationAttTable->delete($destinationAtt);
                            }
                        }
                        @unlink('Staff/sertg/attachment/' . $attachment->attachment);
                        $sertgAttachmentTable->delete($attachment);
                    }
                }

                echo json_encode('Deleted successfully.');
                die();
            }
        }
    }

    public function getClientListByType() {
        if ($this->request->is('ajax')) {
            $this->loadModel('Clients');
            $this->loadModel('Crmusers');
            $ajaxData = $this->request->getData();
            $cmsuser_id = $this->Auth->user('id');
            
            
            
            if ($ajaxData['action'] == "AFFILIATE_CLIENT_LIST") {
                
                if ($ajaxData['crmuser_id'] > 0) {
                    $result = $this->Clients->getClientListByAffiliateIds($cmsuser_id, [$ajaxData['crmuser_id']]);
                } else {
                    $condition = "";
                    //$result = $this->Clients->getClientList($cmsuser_id, "Clients.crmuser_id > 0", true);
                    if ($_SESSION['userType'] == CRM_USER_INDICATOR && $_SESSION['Auth']['User']['type'] == 1) {
                        $condition = "Crmusers.employee_id = " . $ajaxData['crmuser_id'];
                        $employee_id = $this->Auth->user('user_id');
                        if($this->Auth->user('is_show_all_clients') == 1){
                            $condition = "";
                            $affiliateList = $this->Crmusers->generateAffiliateList($cmsuser_id, $condition);
                            $result = $this->Clients->getClientListByAffiliateIds($cmsuser_id, array_keys($affiliateList));
                            //$result['is_employee'] = false;
                            //$result = $this->Clients->getClientList($cmsuser_id, "Clients.crmuser_id > 0", true);
                            //pr($result);exit;
                        }else{
                            $result = $this->Clients->getClientListByEmployeeIds($cmsuser_id, [$employee_id],4);
                        }
                        
                    }else{
                        $affiliateList = $this->Crmusers->generateAffiliateList($cmsuser_id, "Crmusers.type = 2");
                        $result = $this->Clients->getClientListByAffiliateIds($cmsuser_id, array_keys($affiliateList));
                    }
                    //$affiliateList = $this->Crmusers->generateAffiliateList($cmsuser_id, $condition);
                    
                }

                
            } else if ($ajaxData['action'] == "AFFILIATE_LIST") {
                $affiliate_client_list = [];
                $condition = "";
                $client_condition = "Clients.crmuser_id > 0";
                if ($_SESSION['userType'] == CRM_USER_INDICATOR && $_SESSION['Auth']['User']['type'] == 1) {
                    $employee_id = $this->Auth->user('user_id');
                    $condition = "Crmusers.employee_id = " . $employee_id;
                    $client_condition .= " AND Clients.employee_id = " . $employee_id;
                    if($this->Auth->user('is_show_all_clients') == 1){
                        $affiliateList = $this->Crmusers->generateAffiliateList($cmsuser_id, $condition);

                        if (!isset($ajaxData['employee_id'])) {
                            //$affiliate_client_list = $this->Clients->getClientList($cmsuser_id, $client_condition, true);
                            $affiliate_client_list = $this->Clients->getClientListByAffiliateIds($cmsuser_id, array_keys($affiliateList));
                        }
                    }else{
                        $affiliate_client_list = $this->Clients->getClientListByEmployeeIds($cmsuser_id, [$employee_id],4);
                    }
                    
                }else{
                    
                    $affiliateList = $this->Crmusers->generateAffiliateList($cmsuser_id, $condition);
                    
                    if (!isset($ajaxData['employee_id'])) {
                        //$affiliate_client_list = $this->Clients->getClientList($cmsuser_id, $client_condition, true);
                        $affiliate_client_list = $this->Clients->getClientListByAffiliateIds($cmsuser_id, array_keys($affiliateList));
                    }
                }
                //pr($affiliateList);exit;
                $result = ['affiliateList' => $affiliateList, 'affiliate_client_list' => $affiliate_client_list];
                
            } else if ($ajaxData['action'] == "EMPLOYEE_LIST") {
                
                $employee_list = $this->Crmusers->getEmployeeListByMemberId($cmsuser_id);
                //pr(array_keys($employee_list));exit;
                //$employee_client_list = $this->Clients->getClientList($cmsuser_id, "Clients.employee_id > 0", true);
                $employee_client_list = $this->Clients->getClientListByEmployeeIds($cmsuser_id, array_keys($employee_list));
                
                $result = ['affiliateList' => $employee_list, 'affiliate_client_list' => $employee_client_list];
                
            } elseif ($ajaxData['action'] == "EMPLOYEE_CLIENT_LIST") {
                $employee_id = $ajaxData['employee_id'];
                $result = $this->Clients->getEmployeeClientList($cmsuser_id, $employee_id);

                //pr($result);exit;
            }
            
            echo json_encode($result);
            exit;
        }
    }

    private function employeeditprofile() {
        $new_client_link_for_affiliate = "";
        $id = $this->Auth->user('user_id');
        $user_type_name = $this->getCurrentUserType();
        $this->loadModel('Crmusers');
        $crmUserTable = TableRegistry::get('crmusers');
        $crmuser = $crmUserTable->get($id);

        if ($this->request->is('post')) {
           // pr($this->request->getData());exit;
            if (!empty($this->request->data['img_path']['name'])) {

                $image_dimension = getimagesize($this->request->data['img_path']['tmp_name']);
                $image_height = $image_dimension[1];
                $image_width = $image_dimension[0];
                
                if ($image_height > PROFILE_IMAGE_SIZE['height'] || $image_width > PROFILE_IMAGE_SIZE['width']) {
                    $this->Flash->error(__('Profile Picture should be less than 600 px in height and 500 px in width.Please try again!'));
                    return $this->redirect($this->referer());
                }
                
                //$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/employees/' . $id)) {
                    mkdir('media/employees/' . $id, 0777, true);
                }
                $imagedes = $this->request->webroot . 'webroot/media/employees/' . $id;
                //$imagepath = 'webroot/media/companies/'.$last_insert_id.'/'.$this->request->data['img_path']['name'];
                $imagepath = 'media/employees/' . $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
                    $dir =  WWW_ROOT . 'media/employees/' . $id . '/';

                    if(!is_dir($dir)){
                        mkdir($dir,0777,true);
                    }
                    move_uploaded_file($_FILES["img_path"]["tmp_name"], $dir. 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'];
            }

            $profile_img_path = $this->request->data['img_path'];
            $email = $this->request->data['email'];
            $password = $this->request->data['password'];
            $cpassword = $this->request->data['retype_password'];
            $previous_pass = $this->request->data['hash_pass'];

            if ($password == $cpassword) {
                $crmuser->email = $email;
                if ($previous_pass == $password) {
                    $crmuser->hashed_password = $previous_pass;
                } else {
                    $crmuser->hashed_password = md5($password);
                }
                $checkEmail = true;
                if ($checkEmail) {
                    $crmuser->user_photo = $profile_img_path;
                    if ($crmUserTable->save($crmuser)) {
                        $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());
            }
        }
        if($user_type_name == "AFFILIATE"){
            $new_client_link_for_affiliate = APP_SERVER_HOST_URL."client/addaffiliateclient/".$crmuser->client_registration_unique_key;
        }
        //new_client_link_for_affiliate

        //pr($crmuser);exit;
        $this->set(compact('crmuser','new_client_link_for_affiliate'));
        $this->render('edit_employee_profile');
    }
    
    
    
    
    private function letterStreamModalForRTGLetters(){
        $html = '<div id="rtg-letter-stream-modal" class="modal fade" data-backdrop="static" data-keyboard="false" role="dialog" style="display: none;">
                        <div class="modal-dialog modal-md">

                            <!-- Modal content-->
                            <div class="modal-content">
                                <div class="modal-header" style="height: 44px;background:#3c8dbc;">
                                    <button type="button" class="close" data-dismiss="modal" style="top:30%;color: white;"><i class="fa fa-close"></i></button>
                                    <h4 class="modal-title" style="line-height: 0.8; color: white;">Destination and Address Mapping</h4>
                                </div>
                                <div class="modal-body">
                                    <div class="row">
                                        <div class="col-md-6 col-xs-12">
                                            <p class="pull-left">Please confirm the addresses below to send the letter(s) to letterstream.com</p>
                                        </div>
                                        <div class="col-md-2 col-xs-12">
                                            <div class="row">
                                                <div class="col-md-12 col-xs-12">
                                                    <div class="radio" style="padding-top:0;">
                                                        <label>
                                                            <input checked type="radio" name="mailType"  value="firstclass"/>
                                                            First Class
                                                        </label>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-2 col-xs-12">
                                            <div class="row">
                                                <div class="col-md-12 col-xs-12">
                                                    <div class="radio" style="padding-top:0;">
                                                        <label>
                                                            <input type="radio" name="mailType"  value="certified"/>
                                                            Certified
                                                        </label>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-md-2 col-xs-12">
                                            <div class="row">
                                                <div class="col-md-12 col-xs-12">
                                                    <div class="checkbox" style="padding-top:0">
                                                        <label>
                                                            <input type="checkbox" name="is_letterstream_duplex" value="Y">
                                                            Double Sided Print
                                                        </label>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="letter-stream-content table-responsive"><table class="table table-bordered"><tbody><tr><th style="width:2%">
                                            <div class="checkbox">
                                               <label style="font-weight:bold;padding-left: 0">Destinations</label>
                                            </div>
                                        </th><th style="width:5%">
                                            <div class="checkbox">
                                                <label style="font-weight:bold;">
                                                    <input id="all-check-address" type="checkbox" onclick="letterAddressAllCheck(this)"> Addresses</label>
                                            </div>
                                        </th><th style="width:8%">
                                            <div class="checkbox">
                                                <label style="font-weight:bold;padding-left: 0">
                                                    Return Addresses</label>
                                            </div>
                                        </th></tr><tr><td style="font-weight: bold;">EXPERIAN DESTINATIONS</td><td><div class="checkbox"><label><input onclick="currentAddress()" class="letter-address-popup" checked="true" type="checkbox" value="1" name="letter_stream_address_1[]"> EXPERIAN  PO BOX 9701, ALLEN, TX 75013</label></div><div class="checkbox"><label><input onclick="currentAddress()" class="letter-address-popup"  type="checkbox" value="2" name="letter_stream_address_1[]"> EXPERIAN  PO BOX 4500, ALLEN, TX 75013</label></div><div class="checkbox"><label><input onclick="currentAddress()" class="letter-address-popup"  type="checkbox" value="3" name="letter_stream_address_1[]"> EXPERIAN  PO BOX 2002, ALLEN, TX 75013</label></div></td><td><div class="row">
                                            
<div class="col-md-6"><div class="checkbox"><label><input onclick="setEnableDisableReturnAddress(this)" value="1" type="checkbox" name="checkbox_return_address_1">Set return address</label></div></div><div class="col-md-12">
                                                <select style="display:none;" class="form-control" name="return_address_1"><option value="2">EXPERIAN  PO BOX 4500, ALLEN, TX 75013</option><option value="3">EXPERIAN  PO BOX 2002, ALLEN, TX 75013</option></select></div></div></td></tr><tr><td style="font-weight: bold;">EQUIFAX DESTINATIONS</td><td><div class="checkbox"><label><input onclick="currentAddress()" class="letter-address-popup"  type="checkbox" value="1" name="letter_stream_address_2[]" checked="true"> EQUIFAX  PO Box740256, ATLANTA,GA 30374-0256</label></div><div class="checkbox"><label><input onclick="currentAddress()" class="letter-address-popup"  type="checkbox" value="2" name="letter_stream_address_2[]"> EQUIFAX  PO Box740241, ATLANTA,GA 30374-0241</label></div></td><td><div class="row">
                                            
<div class="col-md-6"><div class="checkbox"><label><input onclick="setEnableDisableReturnAddress(this)" value="2" type="checkbox" name="checkbox_return_address_2">Set return address</label></div></div><div class="col-md-12">
                                                <select style="display:none;" class="form-control" name="return_address_2"><option value="2">EQUIFAX  PO Box740241, ATLANTA,GA 30374-0241</option></select></div></div></td></tr><tr><td style="font-weight: bold;">TRANS UNION DESTINATIONS</td><td><div class="checkbox"><label><input onclick="currentAddress()" class="letter-address-popup"  type="checkbox" value="1" name="letter_stream_address_3[]" checked="true"> Trans Union PO Box 2000, CHESTER, PA 19016-2000</label></div><div class="checkbox"><label><input onclick="currentAddress()" class="letter-address-popup"  type="checkbox" value="2" name="letter_stream_address_3[]"> Trans Union  PO Box 1000, CHESTER, PA 19022-1000</label></div><div class="checkbox"><label><input onclick="currentAddress()" class="letter-address-popup"  type="checkbox" value="3" name="letter_stream_address_3[]"> Trans Union  PO Box 2000, CHESTER, PA 19022-2000</label></div></td><td><div class="row">
                                            
<div class="col-md-6"><div class="checkbox"><label><input onclick="setEnableDisableReturnAddress(this)" value="3" type="checkbox" name="checkbox_return_address_3">Set return address</label></div></div><div class="col-md-12">
                                                <select style="display:none;" class="form-control" name="return_address_3"><option value="2">Trans Union  PO Box 1000, CHESTER, PA 19022-1000</option><option value="3">Trans Union  PO Box 2000, CHESTER, PA 19022-2000</option></select></div></div></td></tr></tbody></table></div>

                                </div>
                                <div class="modal-footer">
                                    <div class="row">
                                        <div class="col-md-12">
                                            <span>
                                                <img style="height:25px;display:none" id="saveloading-letter" class="rtg-loading-img" src="https://test.readytogoletters.com/webroot/loading/loading.gif">
                                            </span> &nbsp;
                                            <button type="button" id="letter-stream-btn" onclick="letterStreamSubmit()" class="btn btn-default btn-orange-color">Confirm</button>
                                            <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                                        </div>
                                    </div>
                                </div>
                            </div>

                        </div>
                    </div>';
        
        return $html;
    }

}
