<?php
namespace App\Controller;

use App\Utility\Common;
use Cake\I18n\I18n;
use Cake\Cache\Cache;

/**
 * Settings Controller
 *
 * @property \App\Model\Table\SettingsTable $Settings
 */
class SettingsController extends AppsController
{

    public function initialize()
    {
        parent::initialize();
        I18n::locale('en_US');
    }

    /**
     * Index method
     *
     * @return void
     */
    public function index()
    {
//        $this->loadModel('Certificates');
//        $this->loadModel('Tshirts');
        $setting = $this->Settings->getCurrentSettings();

        if ($this->request->is(['patch', 'post', 'put'])) {
            if (!empty($this->request->data['logo_path']['name'])) {
                if (!empty($this->request->data['previous_logo_path'])) {
                    unlink(WWW_ROOT . '/' . $this->request->data['previous_logo_path']);
                }
                $logopath = 'images/logo/' . $this->request->data['logo_path']['name'];
                $file = $this->request->data['logo_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["logo_path"]["tmp_name"], WWW_ROOT . 'images/logo/' . basename($_FILES['logo_path']['name']));
                } else {
                    $this->Flash->error(__('Logo is not in right format.Please, try again.'));
                    return $this->redirect(['action' => 'index']);
                }
                $this->request->data['logo_path'] = $logopath;
            } else {
                $this->request->data['logo_path'] = $this->request->data['previous_logo_path'];
            }

            if (!empty($this->request->data['favicon_path']['name'])) {
                if (!empty($this->request->data['previous_favicon_path'])) {
                    unlink(WWW_ROOT . '/' . $this->request->data['previous_favicon_path']);
                }
                
                
                $file = $this->request->data['favicon_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', 'ico'); //set allowed extensions
                $this->request->data['favicon_path']['name'] = "favicon.".$ext;
                $faviconpath = 'images/favicon/' . $this->request->data['favicon_path']['name'];
                //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["favicon_path"]["tmp_name"], WWW_ROOT . $faviconpath);
                } else {
                    $this->Flash->error(__('Logo is not in right format.Please, try again.'));
                    return $this->redirect(['action' => 'index']);
                }
                $this->request->data['favicon_path'] = $faviconpath;
            } else {
                $this->request->data['favicon_path'] = $this->request->data['previous_favicon_path'];
            }

            // inquiry image
            $folder_path = "AdminAccountImage/";
            if (!is_dir('AdminAccountImage')) {
                mkdir('AdminAccountImage', 0777, true);
                $folder_path = "AdminAccountImage/";
            }

                if (!empty($this->request->data['enhance_img']['name'])) {
                    if (!empty($this->request->data['previous_enhance_img_path'])) {
                        unlink(WWW_ROOT . '/' . $folder_path . $this->request->data['previous_enhance_img_path']);
                    }

                    $file = $this->request->data['enhance_img']; //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
                    $logopath = $folder_path . ENHANCE_IMAGE.".".$ext;
                    //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["enhance_img"]["tmp_name"], WWW_ROOT . $folder_path . ENHANCE_IMAGE.".".$ext);
                    } else {
                        $this->Flash->error(__('Image is not in right format.Please, try again.'));
                        return $this->redirect(['action' => 'index']);
                    }
                    $this->request->data['enhance_img'] = $logopath;
                } else {
                    $this->request->data['enhance_img'] = $this->request->data['previous_enhance_img_path'];
                }

                // enhance image
                if (!empty($this->request->data['inquiry_img']['name'])) {
                    if (!empty($this->request->data['previous_inquiry_img_path'])) {
                        unlink(WWW_ROOT . '/' . $folder_path . $this->request->data['previous_inquiry_img_path']);
                    }

                    $file = $this->request->data['inquiry_img']; //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
                    $logopath = $folder_path . INQUIRY_IMAGE.".".$ext;
                    //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["inquiry_img"]["tmp_name"], WWW_ROOT."/".$folder_path .INQUIRY_IMAGE.".".$ext);
                    } else {
                        $this->Flash->error(__('Image is not in right format.Please, try again.'));
                        return $this->redirect(['action' => 'index']);
                    }
                    $this->request->data['inquiry_img'] = $logopath;
                } else {
                    $this->request->data['inquiry_img'] = $this->request->data['previous_inquiry_img_path'];

                }
                
                //$this->request->data['updated_on'] = date('Y-m-d H:i:s');
                $settingEntity = $this->Settings->patchEntity($setting, $this->request->data);               
                $settingEntity->trial_account_key = str_replace(TRIAL_ACCOUNT_URL,"",$settingEntity->trial_account_key);
                $settingEntity->time_zone = $this->request->data['time_zone'];
                if ($this->Settings->save($settingEntity)) {
                    //Cache::write('setting',$setting);
//                    $this->updateCertificateUrl();
//                    $this->updateTshirtUrl();
                    $this->Flash->success(__('The setting has been saved.'));
                } else {
                    $this->Flash->error(__('The setting could not be saved. Please, try again.'));
                }
            }
            
//            $certificates = $this->Certificates->getAllCertificates();
//            $tshirts = $this->Tshirts->getAllTshirts();
            $common = new Common;
            $this->set('time_zone_list', $common->tz_key_value_list());
//            $this->set(compact('setting','certificates','tshirts'));
            $this->set(compact('setting'));
            //$this->set('_serialize', ['setting']);
            $this->viewBuilder()->layout("custom_layout");
    }


    /*
    private function updateCertificateUrl(){
        $request_certificate = $this->request->getData('certificate');
        if(!empty($request_certificate)){
            foreach($request_certificate as $certificate_id => $certificate){
                $endpoint = trim(end(explode('/', $certificate)));
                $this->Certificates->updateUniqueString($certificate_id,$endpoint);
            }
        }  
    }

    private function updateTshirtUrl(){
        $request_tshirt = $this->request->getData('tshirt');
        if(!empty($request_tshirt)){
            foreach($request_tshirt as $tshirt_id => $tshirt){
                $endpoint = trim(end(explode('/', $tshirt)));
                $this->Tshirts->updateUniqueString($tshirt_id,$endpoint);
            }
        }  
    }

    */

    public function getModules()
    {
        return [
            'Settings' => '1004'
        ];
    }

    public function getSubModules()
    {
        return [
            'Site Settings' => '2070'
        ];
    }

    public function getPages()
    {
        return [
            'index' => '3081'
        ];
    }
}
