<?php
namespace App\Controller;

use App\Common\Permission;
use Cake\I18n\I18n;
use SubModuleConstants;
use Cake\Cache\Cache;
/**
 * Personalizes Controller
 *
 * @property \App\Model\Table\PersonalizesTable $Personalizes
 *
 * @method \App\Model\Entity\Personalize[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
 */
class PersonalizesController extends AppsController
{
    
    public function initialize() {
        parent::initialize();
        I18n::locale('en_US');

        $this->checkUser(); // is RTG User or not

        $this->setUserType(); // Set CRM/CMS/Contacts user

        if($this->Auth->user()){
            $this->Auth->allow(['deletePersonalize']);
            if(Permission::isEmployeeAsAdmin()){
                $this->Auth->allow('index');
            }
        }

    }

    /**
     * Index method
     *
     * @return \Cake\Http\Response|null
     */
    public function index()
    {

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

        $step_name = 'is_personalized_domain';

        if($this->request->is('post')){
            $inputData = $this->request->getData();
            $inputData['member_id'] = $member_id;
            $inputData['company_id'] = $company_id;
            $main_domain = "londonschooloflearninghub.org";
            $domain = strtolower($inputData['domain']);
            $domain = str_replace("www.", "", $domain);
            if($domain ==  $main_domain){
                $this->Flash->error(__('You cannot use '.$inputData['domain']." as domain."));
            }
            else{
                $inputData['domain'] = $domain;
                $inputData['is_www'] = 2;
                if(!empty($inputData['www'])){
                    $inputData['is_www'] = 1;
                }
                $result = $this->Personalizes->processPersonalize($inputData,true);

                if(!empty($result)){
                    $this->request->session()->write('Auth.User.member_footer', $inputData['footer']);
                    $_SESSION['personalize'] =  $inputData;
                    $this->uploadMemberLogo($inputData);

                    //add_log
                    $logData['action'] = "PERSONALIZES_ADD_EDIT";
                    $logData['status'] = "success";
                    $logData['input_data'] = $this->request->getData();
                    $logData['input_data']["id"]=$result->id;
                    unset($logData['input_data'][password]);
                    $this->appLog($logData);

                    $this->Flash->success(__('Information has been saved.'));
                    Cache::delete('personalizes');
                    return $this->redirect(['action' => 'index']);
                }

            }
        }

        $personalize = $this->Personalizes->find()->where(['company_id'=>$company_id])->first();
//        dd($personalize);
        $user_permissions = $this->request->session()->read('user_permissions');
        $this->set('user_permission', $user_permissions);
        $this->set('personalize',$personalize);
        $this->set('current_module', $this->getModules());
        $this->set('page_list', $this->getPages());
        $this->set('module_pages', $this->getPages());
        $nav_arr[0] = array('action' => 'index', 'page_id' => '3214', 'icon' => '<i class="fa fa-plus-circle"></i>', 'label' => 'Add');
        $this->set('nav_arr', $nav_arr);
        $this->viewBuilder()->layout("custom_layout");
    }

    public function deletePersonalize(){
        $member_id = $this->Auth->user('id');
        if($this->Personalizes->deletePersonalizeByMemberId($member_id)){
            return $this->redirect(['action' => 'index']);
        }
    }

    private function uploadMemberLogo($request){
         
                $this->loadModel('Cmsusers');
                if(!empty($request['img_path']['name'])){
                    $id = $this->request->session()->read('Auth.User.id');
                    if(!empty($request['previous_img_path'])){
                        unlink(WWW_ROOT.'/'.$request['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.'/'.$request['img_path']['name'];
                    $imagepath = 'media/companies/'.$id.'/'.$request['img_path']['name'];
                    //echo $imagepath;exit;
                    $file = $request['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']);
                    }
                    $request['img_path'] = $imagepath;
                    $this->request->session()->write('Auth.User.img_path', $imagepath);
                }  else{
                    $request['img_path'] = $request['previous_img_path'];
                }
                
                
                  if(!empty($request['logo']['name'])){
                    if(!is_dir('cmsuser_logo')){
                        mkdir('cmsuser_logo',0777,true);
                    }  
                    $insertedId = $this->Auth->user('id');
                    $logofile = $request['logo'];
                    $ext = substr(strtolower(strrchr($logofile['name'], '.')),1);
                    $logoname = explode('.',$logofile['name'])[0];
                    $newname = $logoname."_".$insertedId.".".$ext;
                    $request['logo'] = $newname;
                    @unlink(CMSUSER_LOGO.$request['previous_logo']);
                    $this->uploadlogo($newname, $ext);
                  }else{
                     $request['logo'] =  $request['previous_logo'];
                  }
                  
                  
                  $cmsuser = $this->Cmsusers->get($this->Auth->user('id'));
                  $cmsuser->logo = $request['logo'];
                  
                //$cmsuser = $this->Cmsusers->patchEntity($cmsuser, $request);
                
               // pr($cmsuser);exit;
                if ($this->Cmsusers->save($cmsuser)) {
                    $this->request->session()->write('Auth.User.logo', $request['logo']);  
                } else {
                    $this->Flash->error(__('The Profile could not be saved. Please, try again.'));
                }
        

    }
    
    private function uploadlogo($newname ,$ext){
        //get the extension
        $arr_ext = array('jpg', 'jpeg', 'png'); //set allowed extensions
        
        
        if (in_array($ext, $arr_ext)) {
				    //do the actual uploading of the file. First arg is the tmp name, second arg is 
				    //where we are putting it
             move_uploaded_file($_FILES["logo"]["tmp_name"],WWW_ROOT.'cmsuser_logo/'. $newname);
	} else{
            $this->Flash->error(__('Profile Picture is not in right format.Please, try again.'));
            return $this->redirect($this->referer());
	}
    }
   

    
}
