<?php

namespace Dashboard\Controller;

use Application\Controller\RestAPIClientController;
use Dashboard\Form\{
    SiteConfigurationForm,
    HeaderFooterForm,
    JavaScriptCodeForm,
    WatermarkBaseForm,
    ThirdPartyForm,
    CacheForm,
    ContactUsForm,
    AccountDetailsForm,
    SetupGlobalSettingUserRoleForm,
    SetupGlobalsettingPageManagementForm,
    SetupManageCompanyForm
};
use Zend\View\Model\{
    ViewModel,
    JsonModel
};
use Zend\Json\Json;
use Dashboard\Model\CommonModel;
use Zend\Session\Container;
use Zend\Debug\Debug;

class GlobalSettingsController extends RestAPIClientController {
    
    public function __construct() {
        $this->CommonModel = new CommonModel();
    }
    
    /**
     * @CreatedBy : Mohit Jain
     * @createdDate : 21-May-2022
     * @description : ACTION FOR SITE SETTING BASIC DETAILS
     * @returns $responsedata
     */

    public function indexAction() {

        $viewModel = new ViewModel();
        $sessionContainer = new Container('userlogin');
        //echo '<pre>';print_r($sessionContainer);die();
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $company_id = $this->config()->getConfig()->company->companyId;
        $id = $this->params()->fromQuery('id');
        if(!empty($id)){
          $company_id= $id;  
        }
        SiteConfigurationForm::$country = $this->getCountryList();
        SiteConfigurationForm::$supp_lang = $this->getLanguageList();
        SiteConfigurationForm::$def_curr = $this->getCurrencyList();
        SiteConfigurationForm::$def_format = $this->getPriceFormatList();
        $dateFormat = $this->getDateTimeFormatList();
        SiteConfigurationForm:: $date_format_short = $dateFormat['date_short_format'];
        SiteConfigurationForm:: $date_format_long = $dateFormat['date_long_format'];
        SiteConfigurationForm:: $time_format_short = $dateFormat['time_short_format'];
        SiteConfigurationForm:: $time_format_long = $dateFormat['time_long_format'];
        SiteConfigurationForm:: $site_owner = $this->getSiteOwnerList();
        $form = new SiteConfigurationForm();
        $request = $this->getRequest();
        $compData = $this->getCompanySetupDetails($company_id);
        $form->setData($compData);
       

        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
             //echo '<pre>';print_r($post);die();
            $form->setData($request->getPost());
            if ($form->isValid()) {
                $data = [];
                $data = [
                    'site_name' => $post['site_name'],
                    'site_title' => $post['site_title'],
                    'site_url' => $post['site_url'],
                    'country_id' => $post['country_id'],
                    //'site_url' => $post['language'],
                    'currency_id' => $post['currency_id'],
                    'price_format' => $post['price_format'],
                    'seo_mode' => $post['seo_mode'],
                    'lang_direction' => $post['lang_direction'],
                    'maintenance_mode' => $post['maintenance_mode'],
                    'maintainence_mode_message' => $post['maintenance_mode_message'],
                    'date_format_short' => $post['date_format_short'],
                    'date_format_long' => $post['date_format_long'],
                    'time_format_short' => $post['time_format_short'],
                    'time_format_long' => $post['time_format_long'],
                    'billing_payment_mode' => $post['billing_payment_mode'],
                    'shopping_cart_mode' => $post['shopping_cart_mode'],
                    'payment_flow' => $post['payment_flow'],
                    'logo_url' => $post['logo_url'],
                    'pay_to_text' => $post['pay_to_text'],
                    'meta_key' => $post['meta_key'],
                    'meta_desc' => $post['meta_desc'],
                    'facebook' => $post['facebook'],
                    'twitter' => $post['twitter'],
                    'instagram' => $post['instagram'],
                    'linkedin' => $post['linkedin'],
                    'youtube' => $post['youtube'],
                    'client_app_url' => $post['client_app_url'],
                    'driver_app_url' => $post['driver_app_url'],
                    'ios_client_app_url' => $post['ios_client_app_url'],
                    'ios_driver_app_url' => $post['ios_driver_app_url'],
                    'modified_by' => $user_id,
                    'ip' => $_SERVER['REMOTE_ADDR'],
                    'id' => $company_id,
                ];
                $compJsonData = $this->insertCompanySetUpDetails($company_id, $data);
                if (!empty($compJsonData)) {
                    
                    /// CODE TO UPDATE THE LANGUAGE KEY IN GLOBAL FILE STARTS HERE //////
                        $file = BASE_PATH.'/config/autoload/global.php';
                        $a = file_get_contents($file);
                        $content = preg_replace("~'language'\s*=>\s*'\K[^']+~", $post['language'], $a, 1);
                        file_put_contents($file,$content);
                     /// CODE TO UPDATE THE LANGUAGE KEY IN GLOBAL FILE ENDS HERE ///////
                     
                     /// CODE TO UPDATE THE CURRENCY KEY IN GLOBAL FILE STARTS HERE //////
                        $file = BASE_PATH.'/config/autoload/global.php';
                        $a = file_get_contents($file);
                        $content = preg_replace("~'currency'\s*=>\s*'\K[^']+~", $post['currency_id'], $a, 1);
                        file_put_contents($file,$content);
                     /// CODE TO UPDATE THE CURRENCY KEY IN GLOBAL FILE ENDS HERE ///////
                        
                        /// CODE TO UPDATE THE PRICE FORMAT KEY IN GLOBAL FILE STARTS HERE //////
                        $file = BASE_PATH.'/config/autoload/global.php';
                        $a = file_get_contents($file);
                        $content = preg_replace("~'priceFormat'\s*=>\s*'\K[^']+~", $post['price_format'], $a, 1);
                        file_put_contents($file,$content);
                     /// CODE TO UPDATE THE PRICE FORMAT KEY IN GLOBAL FILE ENDS HERE ///////
                        
                        /// CODE TO UPDATE THE DATE SHORT FORMAT KEY IN GLOBAL FILE STARTS HERE //////
                        $file = BASE_PATH.'/config/autoload/global.php';
                        $a = file_get_contents($file);
                        $content = preg_replace("~'dateFormatShort'\s*=>\s*'\K[^']+~", $post['date_format_short'], $a, 1);  
                        file_put_contents($file,$content);
                        /// CODE TO UPDATE THE DATE SHORT FORMAT KEY IN GLOBAL FILE ENDS HERE //////
                        
                        /// CODE TO UPDATE THE DATE LONG FORMAT KEY IN GLOBAL FILE STARTS HERE //////
                        $file = BASE_PATH.'/config/autoload/global.php';
                        $a = file_get_contents($file);
                        $content = preg_replace("~'dateFormatLong'\s*=>\s*'\K[^']+~", $post['date_format_long'], $a, 1);  
                        file_put_contents($file,$content);
                        /// CODE TO UPDATE THE DATE LONG FORMAT KEY IN GLOBAL FILE ENDS HERE //////
                        
                        /// CODE TO UPDATE THE TIME SHORT FORMAT KEY IN GLOBAL FILE STARTS HERE //////
                        $file = BASE_PATH.'/config/autoload/global.php';
                        $a = file_get_contents($file);
                        $content = preg_replace("~'timeFormatShort'\s*=>\s*'\K[^']+~", $post['time_format_short'], $a, 1);  
                        file_put_contents($file,$content);
                        /// CODE TO UPDATE THE TIME SHORT FORMAT KEY IN GLOBAL FILE ENDS HERE //////
                        
                         /// CODE TO UPDATE THE TIME LONG FORMAT KEY IN GLOBAL FILE STARTS HERE //////
                        $file = BASE_PATH.'/config/autoload/global.php';
                        $a = file_get_contents($file);
                        $content = preg_replace("~'timeFormatLong'\s*=>\s*'\K[^']+~", $post['time_format_long'], $a, 1);  
                        file_put_contents($file,$content);
                        /// CODE TO UPDATE THE TIME LONG FORMAT KEY IN GLOBAL FILE ENDS HERE //////
                            
                    $this->flashMessenger()->addMessage(array('success' => 'Site Configuration updated successfully..'));
                    $result = ['result' => true, 'currentUrlRedirect' => 'Y'];


                }
            } else {
                $result = ['result' => false, 'message' => $form->getMessages()];
            }
            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
             $viewModel->setVariables(['data' => $result]);
             return $viewModel;
        }
        $companyData = [];
        $dataListing = $this->CommonModel->getCompanyDetailsList($companyData);

        $viewModel->setVariables(['form' => $form, 'compData' => $compData, 'dataListing' =>$dataListing, 'compId'=>$company_id]);
        return $viewModel;

    }
    
    /**
     * @CreatedBy : Mohit Jain
     * @createdDate : 21-May-2022
     * @description : ACTION FOR SITE CONFIGURATION DETAILS
     * @returns $responsedata
     */

    public function siteConfigurationAction() {
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $company_id = $this->config()->getConfig()->company->companyId;
        $id = $this->params()->fromQuery('id');
        if(!empty($id)){
          $company_id= $id;  
        }
        SiteConfigurationForm::$country = $this->getCountryList();
        SiteConfigurationForm::$supp_lang = $this->getLanguageList();
        SiteConfigurationForm::$def_curr = $this->getCurrencyList();
        SiteConfigurationForm::$def_format = $this->getPriceFormatList();
        $dateFormat = $this->getDateTimeFormatList();
        SiteConfigurationForm:: $date_format_short = $dateFormat['date_short_format'];
        SiteConfigurationForm:: $date_format_long = $dateFormat['date_long_format'];
        SiteConfigurationForm:: $time_format_short = $dateFormat['time_short_format'];
        SiteConfigurationForm:: $time_format_long = $dateFormat['time_long_format'];
        SiteConfigurationForm:: $site_owner = $this->getSiteOwnerList();
        $form = new SiteConfigurationForm();
        $request = $this->getRequest();
        $compData = $this->getCompanySetupDetails($company_id);
        $form->setData($compData);
        $viewModel = new ViewModel(['form' => $form, 'compData' => $compData, 'compId'=>$company_id]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }
    
    /**
     * @CreatedBy : Mohit Jain
     * @createdDate : 21-May-2022
     * @description : ACTION FOR HEADER AND FOOTER SETTING DETAILS
     * @returns $responsedata
     */

    public function headerFooterAction() {
        $viewModel = new ViewModel();
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $company_id = $this->config()->getConfig()->company->companyId;
        $id = $this->params()->fromQuery('id');
        if(!empty($id)){
          $company_id= $id;  
        }
        $form = new HeaderFooterForm();
        $request = $this->getRequest();
        $compData = $this->getCompanySetupDetails($company_id);
        $form->setData($compData);
        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            $form->setData($request->getPost());
            if (!empty($post)) {
                if ($form->isValid()) {
                    $data = [];
                    $data = [
                        'frontend_header_logo' => $post['frontend_header_logo'],
                        'admin_header_logo' => $post['admin_header_logo'],
                        //'admin_footer' => $post['admin_dashboard_logo'],
                        'frontend_favicon' => $post['frontend_favicon'],
                        'admin_favicon' => $post['admin_favicon'],
                        'admin_footer' => $post['admin_footer'],
                        'admin_footer_url' => $post['admin_footer_url'],
                        'frontend_footer' => $post['frontend_footer'],
                        'frontend_footer_url' => $post['frontend_footer_url'],
                        'modified_by' => $user_id,
                        'ip' => $_SERVER['REMOTE_ADDR'],
                        'id' => $company_id,
                    ];
                    $compJsonData = $this->insertCompanySetUpDetails($company_id, $data);
                    if (!empty($compJsonData)) {
                        $this->flashMessenger()->addMessage(array('success' => 'Header & Footer Details updated successfully..'));
                        $result = ['result' => true, 'currentUrlRedirect' => 'Y'];
                    }
                } else {
                    $result = ['result' => false, 'message' => $form->getMessages()];
                }
                if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                    $viewModel = new JsonModel();
                }
                $viewModel->setVariables(['form' => $form, 'compData' => $compData, 'data' => $result]);
                return $viewModel;
            }
        }
        $viewModel = new ViewModel(['form' => $form, 'compData' => $compData,  'compId'=>$company_id]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }
    
    /**
     * @CreatedBy : Mohit Jain
     * @createdDate : 21-May-2022
     * @description : ACTION FOR JAVASCRIPT CODE SETTING DETAILS
     * @returns $responsedata
     */

    public function javascriptCodeSettingsAction() {
        $viewModel = new ViewModel();
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $company_id = $this->config()->getConfig()->company->companyId;
        $id = $this->params()->fromQuery('id');
        if(!empty($id)){
          $company_id= $id;  
        }
        $form = new JavaScriptCodeForm();
        $request = $this->getRequest();
        $compData = $this->getCompanySetupDetails($company_id);
        $form->setData($compData);
        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            $form->setData($request->getPost());
            if (!empty($post)) {
                if ($form->isValid()) {
                    $data = [];
                    $data = [
                        'analytics_code' => $post['analytics_code'],
                        'additional_javascript' => $post['additional_javascript'],
                        'modified_by' => $user_id,
                        'ip' => $_SERVER['REMOTE_ADDR'],
                        'id' => $company_id,
                    ];
                    $compJsonData = $this->insertCompanySetUpDetails($company_id, $data);
                    if (!empty($compJsonData)) {
                        $this->flashMessenger()->addMessage(array('success' => 'Javascript Code Setting updated successfully..'));
                        $result = ['result' => true, 'currentUrlRedirect' => 'Y'];
                    }
                } else {
                    $result = ['result' => false, 'message' => $form->getMessages()];
                }
                if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                    $viewModel = new JsonModel();
                }
                $viewModel->setVariables(['form' => $form, 'compData' => $compData, 'data' => $result]);
                return $viewModel;
            }
        }
        $viewModel = new ViewModel(['form' => $form, 'compId'=>$company_id]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }
    
    /**
     * @CreatedBy : Mohit Jain
     * @createdDate : 21-May-2022
     * @description : ACTION FOR WATER MARK BASIC SETTING DETAILS
     * @returns $responsedata
     */

    public function waterMarkBaseSettingsAction() {
        $viewModel = new ViewModel();
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $company_id = $this->config()->getConfig()->company->companyId;
        $id = $this->params()->fromQuery('id');
        if(!empty($id)){
          $company_id= $id;  
        }
        WatermarkBaseForm:: $backround_transparency = $this->getNumbersList();
        WatermarkBaseForm:: $pos_water_mark = $this->getPositionList();
        WatermarkBaseForm:: $icon_alignment = $this->getPositionList();
        WatermarkBaseForm:: $vertical_alignment = $this->getPositionList();
        WatermarkBaseForm:: $text_alignment = $this->getPositionList();
        WatermarkBaseForm:: $jpeg_quality = $this->getNumbersList();
        $form = new WatermarkBaseForm();
        $request = $this->getRequest();
        $compData = $this->getCompanyWaterMarkDetails($company_id);
        if(!empty($compData[0])){
        $form->setData($compData[0]);
        }
        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            $form->setData($request->getPost());
            if (!empty($post)) {
                if ($form->isValid()) {
                    $data = [];
                    $data = [
                        'watermark_status' => $post['watermark_status'],
                        'watermark_inside_outside' => $post['watermark_inside_outside'],
                        'background_color' => $post['background_color'],
                        'background_transparency' => $post['background_transparency'],
                        'watermark_height' => $post['watermark_height'],
                        'watermark_position' => $post['watermark_position'],
                        'icon_image' => $post['icon_image'],
                        'icon_file' => $post['icon_file'],
                        'max_height_per' => $post['max_height_per'],
                        'icon_alignment' => $post['icon_alignment'],
                        'icon_vertical_alignment' => $post['icon_vertical_alignment'],
                        'icon_offset_X' => $post['icon_offset_X'],
                        'icon_offset_Y' => $post['icon_offset_Y'],
                        'icon_space' => $post['icon_space'],
                        'jpeg_quality' => $post['jpeg_quality'],
                        'show_text_status' => $post['show_text_status'],
                        'watermark_text' => $post['watermark_text'],
                        'text_alignment' => $post['text_alignment'],
                        'text_offset_X' => $post['text_offset_X'],
                        'text_offset_Y' => $post['text_offset_Y'],
                        'text_spacing' => $post['text_spacing'],
                        'font_direction' => $post['font_direction'],
                        'font_setting' => $post['font_setting'],
                        'font_size' => $post['font_size'],
                        'font_color' => $post['font_color'],
                        'modified_by' => $user_id,
                        'ip' => $_SERVER['REMOTE_ADDR'],
                        'company_id' => $company_id,
                    ];
                    //echo '<pre>';print_r($data);die();
                    $compJsonData = $this->insertWaterMarkSetUpDetails($company_id, $data);
                    if (!empty($compJsonData)) {
                        $this->flashMessenger()->addMessage(array('success' => 'Water Mark Base Settings updated successfully..'));
                        $result = ['result' => true, 'currentUrlRedirect' => 'Y'];
                    }
                } else {
                    $result = ['result' => false, 'message' => $form->getMessages()];
                }
                if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                    $viewModel = new JsonModel();
                }
                $viewModel->setVariables(['form' => $form, 'compData' => $compData[0], 'data' => $result]);
                return $viewModel;
            }
        }
        $viewModel = new ViewModel(['form' => $form, 'compData' => $compData, 'compId'=>$company_id]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }
    
    /**
     * @CreatedBy : Mohit Jain
     * @createdDate : 21-May-2022
     * @description : ACTION FOR THIRD PARTY SETTING DETAILS
     * @returns $responsedata
     */

    public function thirdPartySettingsAction() {
        $viewModel = new ViewModel();
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $company_id = $this->config()->getConfig()->company->companyId;
        $id = $this->params()->fromQuery('id');
        if(!empty($id)){
          $company_id= $id;  
        }
        ThirdPartyForm::$map_style = $this->getMapStyleList();
        ThirdPartyForm::$captcha_type = $this->getCaptchaTypeList();
        $form = new ThirdPartyForm();
        $request = $this->getRequest();
        $compData = $this->getThirdPartyDetails($company_id);
        $compData1 = $this->getCompanySetupDetails($company_id);
        $form->setData($compData1);
        if(!empty($compData)) {
            $form->setData($compData[0]);
        }
        if(!empty($compData1)) {
            $form->setData($compData1);
        }
        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            $form->setData($request->getPost());
            if (!empty($post)) {
                if ($form->isValid()) {
                    $data = [];
                    $data1 = [];
                    $data = [
                        'map_api_key' => $post['map_api_key'],
                        'map_style' => $post['map_style'],
                        'no_mark_place' => $post['no_mark_place'],
                        'multipoint_zoom_level' => $post['multipoint_zoom_level'],
                        'singlepoint_zoom_level' => $post['singlepoint_zoom_level'],
                        'default_latitude' => $post['default_latitude'],
                        'default_longitude' => $post['default_longitude'],
                        'captcha_type' => $post['captcha_type'],
                        'captcha_key' => $post['captcha_key'],
                        'google_font' => $post['google_font'],
                        'facebook_login_status' => $post['facebook_login_status'],
                        'facebook_api_key' => $post['facebook_api_key'],
                        'goole_login_status' => $post['goole_login_status'],
                        'google_client_id' => $post['google_client_id'],
                        'google_secret_id' => $post['google_secret_id'],
                        'google_redirect_url' => $post['google_redirect_url'],
                        'linkedin_login_status' => $post['linkedin_login_status'],
                        'linkedin_client_id' => $post['linkedin_client_id'],
                        'linkedin_secret_id' => $post['linkedin_secret_id'],
                        'linkedin_redirect_url' => $post['linkedin_redirect_url'],
                        'tawkchat_status' => $post['tawkchat_status'],
                        'tawkchat_script' => $post['tawkchat_script'],
                        'modified_by' => $user_id,
                        'ip' => $_SERVER['REMOTE_ADDR'],
                        'company_id' => $company_id
                    ];
                    
                     $data1 = [
                        'smtp_host' => $post['smtp_host'],
                        'smtp_username' => $post['smtp_username'],
                        'smtp_password' => $post['smtp_password'],
                        'smtp_port' => $post['smtp_port'],
                        'modified_by' => $user_id,
                        'ip' => $_SERVER['REMOTE_ADDR'],
                        'company_id' => $company_id
                    ];
                    $compJsonData = $this->insertThirdPartyDetails($company_id, $data);
                    $compJsonData1 = $this->insertCompanySetUpDetails($company_id, $data1);
                    if (!empty($compJsonData) && !empty($compJsonData1)) {
                        
                            /// CODE TO UPDATE THE API KEY IN GLOBAL FILE STARTS HERE //////
                            $file = BASE_PATH.'/config/autoload/global.php';
                            $a = file_get_contents($file);
                            $content = preg_replace("~'key'\s*=>\s*'\K[^']+~", $post['map_api_key'], $a, 1);
                            file_put_contents($file,$content);
                            /// CODE TO UPDATE THE API KEY IN GLOBAL FILE ENDS HERE ///////
                            
                        $this->flashMessenger()->addMessage(array('success' => '3rd Party Settings updated successfully..'));
                        $result = ['result' => true, 'currentUrlRedirect' => 'Y'];
                    }
                } else {
                    $result = ['result' => false, 'message' => $form->getMessages()];
                }
                if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                    $viewModel = new JsonModel();
                }
                $viewModel->setVariables(['form' => $form, 'compData' => $compData[0], 'data' => $result]);
                return $viewModel;
            }
        }


        $viewModel = new ViewModel(['form' => $form, 'compData' => isset($compData[0])?$compData[0]:'', 'compId'=>$company_id]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }
    
    /**
     * @CreatedBy : Mohit Jain
     * @createdDate : 21-May-2022
     * @description : ACTION FOR CACHE CODE SETTING DETAILS
     * @returns $responsedata
     */

    public function cacheAction() {
        $viewModel = new ViewModel();
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $company_id = $this->config()->getConfig()->company->companyId;
        $id = $this->params()->fromQuery('id');
        if(!empty($id)){
          $company_id= $id;  
        }
        $cache_adapter = [
            '' => 'Select an option',
            '1' => 'select new meta',
            '2' => 'Prepare with global congig3',
        ];
        CacheForm:: $cache_adapter = $cache_adapter;
        $form = new CacheForm();
        $request = $this->getRequest();
        $compData = $this->getCompanySetupDetails($company_id);
        $form->setData($compData);
        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            $form->setData($request->getPost());
            if (!empty($post)) {
                if ($form->isValid()) {
                    $data = [];
                    $data = [
                        'global_cache_mode' => $post['global_cache_mode'],
                        'cache_adapter' => $post['cache_adapter'],
                        'cache_directory' => $post['cache_directory'],
                        'modified_by' => $user_id,
                        'ip' => $_SERVER['REMOTE_ADDR'],
                        'id' => $company_id,
                    ];
                    $compJsonData = $this->insertCompanySetUpDetails($company_id, $data);
                    if (!empty($compJsonData)) {
                        $this->flashMessenger()->addMessage(array('success' => 'Cache Details updated successfully..'));
                        $result = ['result' => true, 'currentUrlRedirect' => 'Y'];
                    }
                } else {
                    $result = ['result' => false, 'message' => $form->getMessages()];
                }
                if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                    $viewModel = new JsonModel();
                }
                $viewModel->setVariables(['form' => $form, 'data' => $result]);
                return $viewModel;
            }
        }
        $viewModel = new ViewModel(['form' => $form, 'compData' => $compData, 'compId'=>$company_id]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }
    
    /**
     * @CreatedBy : Mohit Jain
     * @createdDate : 21-May-2022
     * @description : ACTION FOR CONTACT US SETTING DETAILS
     * @returns $responsedata
     */

    public function contactUsAction() {
        $viewModel = new ViewModel();
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $company_id = $this->config()->getConfig()->company->companyId;
        $id = $this->params()->fromQuery('id');
        if(!empty($id)){
          $company_id= $id;  
        }
        $form = new ContactUsForm();
        $request = $this->getRequest();
        $compData = $this->getCompanySetupDetails($company_id);
        $form->setData($compData);
        if ($request->isPost()) {
            $post = $request->getPost()->toArray();            
            $form->setData($request->getPost());
            if (!empty($post)) {
                if ($form->isValid()) {
                    $data = [];
                    $data = [
                        'com_name' => $post['com_name'],
                        'trading_name' => $post['trading_name'],
                        'comp_address' => $post['comp_address'],
                        'domain_address' => $post['domain_address'],                        
                        'pan_no' => $post['pan_no'],
                        'gst_no' => $post['gst_no'],
                        'office_address' => $post['office_address'],
                        'phone' => $post['phone'],
                        'fax_no' => $post['fax_no'],
                        'email' => $post['email'],
                        'global_email' => $post['global_email'],
                        'working_hour' => $post['working_hour'],
                        'modified_by' => $user_id,
                        'ip' => $_SERVER['REMOTE_ADDR'],
                        'id' => $company_id,
                    ];
                    $compJsonData = $this->insertCompanySetUpDetails($company_id, $data);
                    if (!empty($compJsonData)) {
                        $this->flashMessenger()->addMessage(array('success' => 'Contact Us updated successfully..'));
                        $result = ['result' => true, 'currentUrlRedirect' => 'Y'];
                    }
                } else {
                    $result = ['result' => false, 'message' => $form->getMessages()];
                }
                if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                    $viewModel = new JsonModel();
                }
                $viewModel->setVariables(['form' => $form, 'compData' => $compData, 'data' => $result]);
                return $viewModel;
            }
        }
        $viewModel = new ViewModel(['form' => $form, 'compId'=>$company_id]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }
    
    /**
     * @CreatedBy : Mohit Jain
     * @createdDate : 21-May-2022
     * @description : ACTION FOR ACCOUNT SETTING DETAILS
     * @returns $responsedata
     */
    
    public function accountDetailsAction() {
        $viewModel = new ViewModel();
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $company_id = $this->config()->getConfig()->company->companyId;
        $id = $this->params()->fromQuery('id');
        if(!empty($id)){
          $company_id= $id;  
        }
        $form = new AccountDetailsForm();
        $request = $this->getRequest();
        $compData = $this->getCompanySetupDetails($company_id);
        $form->setData($compData);
        if ($request->isPost()) {
            $post = $request->getPost()->toArray();            
            $form->setData($request->getPost());
            if (!empty($post)) {
                if ($form->isValid()){
                    $data = [];
                    $data = [
                        'driver_min_balance' => $post['driver_min_balance'],
                        'bank_name' => $post['bank_name'],
                        'ac_holder_name' => $post['ac_holder_name'],
                        'branch' => $post['branch'],
                        'ifsc_code' => $post['ifsc_code'],
                        'account_no' => $post['account_no'],
                        'modified_by' => $user_id,
                        'ip' => $_SERVER['REMOTE_ADDR'],
                        'id' => $company_id,
                    ];
                    //echo "<pre>"; print_r($data); die;
                    $compJsonData = $this->insertCompanySetUpDetails($company_id, $data);
                    if(!empty($compJsonData)) {
                        $this->flashMessenger()->addMessage(array('success' => 'Account Details updated successfully..'));
                        $result = ['result' => true, 'currentUrlRedirect' => 'Y'];
                    }
                } else {
                    $result = ['result' => false, 'message' => $form->getMessages()];
                }
                if(!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                    $viewModel = new JsonModel();
                }
                $viewModel->setVariables(['form' => $form, 'compData' => $compData, 'data' => $result]);
                return $viewModel;
            }
        }
        $viewModel = new ViewModel(['form' => $form,  'compId'=>$company_id]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    public function globalSettingHeadingAction() {

        $viewModel = new ViewModel();
        return $viewModel;
    }

    public function globalSettingLinksCommonAction() {

        $viewModel = new ViewModel();
        return $viewModel;
    }

    public function memberShipPackageAction() {

        $viewModel = new ViewModel();
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    public function globalSettingMembershipPackageAddnewAction() {

        $viewModel = new ViewModel();
        return $viewModel;
    }

    public function globalSettingOptionsAction() {

        $viewModel = new ViewModel();
        return $viewModel;
    }
    
    /**
     * @CreatedBy : Mohit Jain
     * @createdDate : 21-May-2022
     * @description : ACTION FOR PAGE MANAGEMENT SETTINGS DETAILS
     * @returns $responsedata
     */

    public function pageManagementAction() {

        $default_home_page = [
            '1' => 'Nossos products',
            '2' => 'Caca',
            '3' => 'Noticia',
            '4' => 'Eventos',
            '5' => 'Fale conosco',
        ];
        \Dashboard\Form\SetupGlobalsettingPageManagementForm:: $default_home_page = $default_home_page;

        $set_metadata = [
            '1' => 'Select an option',
            '2' => 'select new meta',
            '3' => 'Prepare with global congig3',
        ];
        \Dashboard\Form\SetupGlobalsettingPageManagementForm:: $set_metadata = $set_metadata;


//        echo "Mohit"; die;
        $form = new SetupGlobalsettingPageManagementForm();

        $viewModel = new ViewModel(['form' => $form]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }
    
    /**
     * @CreatedBy : Mohit Jain
     * @createdDate : 21-May-2022
     * @description : ACTION FOR USER ROLE DETAILS
     * @returns $responsedata
     */

    public function userRoleAction() {

        $role = [
            '1' => 'Administrator',
            '2' => 'Agent',
            '3' => 'Registered User',
        ];
        \Dashboard\Form\SetupGlobalSettingUserRoleForm:: $role = $role;

        $registration_role = [
            '1' => 'Administrator',
            '2' => 'Agent',
            '3' => 'Registered User',
        ];
        \Dashboard\Form\SetupGlobalSettingUserRoleForm:: $registration_role = $registration_role;

        $customer_role = [
            '1' => 'Administrator',
            '2' => 'Agent',
            '3' => 'Registered User',
        ];
        \Dashboard\Form\SetupGlobalSettingUserRoleForm:: $customer_role = $customer_role;

        $form = new SetupGlobalSettingUserRoleForm();
        $data = [];
        $uLicenseList = $this->getUserRoleList($data);
        $viewModel = new ViewModel(['form' => $form,'uLicenseList' => $uLicenseList]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }
    
    /**
     * @CreatedBy : Mohit Jain
     * @createdDate : 21-May-2022
     * @description : FUNCTION TO FETCH USER ROLE LIST
     * @returns $responsedata
     */
    
    public function getUserRoleList($data) {      
        $url = $this->apiUrl() . "/user-role/getUserRoleList";
        $val = $this->post($url, $data);
        $JsonData = $val->getBody();
        $responsedata = Json::decode($JsonData, true);
        $result = [];
        if($responsedata['responsedata']['status']=="success"){
            $result = $responsedata['responsedata']['data'];
        }
        return $result;
    }

    /**
     * @CreatedBy : Mohit Jain
     * @createdDate : 21-May-2022
     * @description : FUNCTION TO GET THE COUNTRY LIST
     * @returns $responsedata
     */
    public function getCountryList() {
        $countryJsonDataArray = [];
        $url = $this->apiUrl() . "/country";
        $resp = $this->get($url);
        $countryJsonData = Json::decode($resp->getBody(), true);
        foreach ($countryJsonData as $res) {
            $countryJsonDataArray[$res['id']] = $res['name'];
        }
        return $countryJsonDataArray;
    }

    /**
     * @CreatedBy : Mohit Jain
     * @createdDate : 21-May-2022
     * @description : FUNCTION TO GET THE LANGUAGE LIST
     * @returns $responsedata
     */
    public function getLanguageList() {
        $languageJsonDataArray = [];
        $url = $this->apiUrl() . "/master-language";
        $resp = $this->get($url);
        $languageJsonData = Json::decode($resp->getBody(), true);

        if($languageJsonData['status']=="success"){
        foreach ($languageJsonData['data'] as $res) {

            $languageJsonDataArray[$res['language_id']] = $res['language_name'];
        }
        }
        return $languageJsonDataArray;
    }

    /**
     * @CreatedBy : Mohit Jain
     * @createdDate : 21-May-2022
     * @description : FUNCTION TO GET THE CURRENCY LIST
     * @returns $responsedata
     */
    
    public function getCurrencyList() {
        $currencnyJsonDataArray = [];
        $url = $this->apiUrl() . "/master-currency";
        $resp = $this->get($url);
        $currencyJsonData = Json::decode($resp->getBody(), true);
        foreach ($currencyJsonData as $res) {
            $currencnyJsonDataArray[$res['id']] = '[' . $res['name'] . '] - ' . $res['country_name'];
        }
        return $currencnyJsonDataArray;
    }

    /**
     * @CreatedBy : Mohit Jain
     * @createdDate : 21-May-2022
     * @description : FUNCTION TO INSERT THE COMPANY SETUP DETAILS
     * @returns $responsedata
     */
    public function insertCompanySetUpDetails($id, $data) {
        $val = '{"id": "' . $id . '"}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/company-setup/upsertWithWhere?where=" . $val;
        $resp = $this->post($url, $data);
        $data = Json::decode($resp->getBody(), true);
        return $data;
    }

    /**
     * @CreatedBy : Mohit Jain
     * @createdDate : 21-May-2022
     * @description : FUNCTION TO INSERT THE WATER MARK SETUP DETAILS
     * @returns $responsedata
     */
    public function insertWaterMarkSetUpDetails($id, $data) {
        $val = '{"company_id": "' . $id . '"}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/company-watermark-setting/upsertWithWhere?where=" . $val;
        $resp = $this->post($url, $data);
        $data = Json::decode($resp->getBody(), true);
        return $data;
    }

    /**
     * @CreatedBy : Mohit Jain
     * @createdDate : 21-May-2022
     * @description : FUNCTION TO INSERT THE THIRD PARTY DETAILS
     * @returns $responsedata
     */
    public function insertThirdPartyDetails($id, $data) {
        //echo '<pre>';print_r($data);die('aa');
        $val = '{"company_id": "' . $id . '"}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/company-api-configuration/upsertWithWhere?where=" . $val;
        $resp = $this->post($url, $data);
        $data = Json::decode($resp->getBody(), true);
        return $data;
    }

    /**
     * @CreatedBy : Mohit Jain
     * @createdDate : 21-May-2022
     * @description : FUNCTION TO MANAGE THE COMPANY DETAILS
     * @returns $responsedata
     */

    public function manageCompanyAction() {

        $form = new SetupManageCompanyForm();
        $viewModel = new ViewModel(['form' => $form]);

        return $viewModel;
    }

    /**
     * @CreatedBy : Mohit Jain
     * @createdDate : 21-May-2022
     * @description : FUNCTION TO GET THE POSITION LIST
     * @returns $responsedata
     */
    public function getPositionList() {
        $data = [];
        $data = [
            'Left' => 'Left',
            'Right' => 'Right',
            'Top' => 'Top',
            'Bottom' => 'Bottom',
        ];
        return $data;
    }

    /**
     * @CreatedBy : Mohit Jain
     * @createdDate : 21-May-2022
     * @description : FUNCTION TO GET THE NUMBER LIST
     * @returns $responsedata
     */
    public function getNumbersList() {
        $data = [];
        $data = [
            '1' => '1',
            '2' => '2',
            '3' => '3',
            '4' => '4',
            '5' => '5',
        ];
        return $data;
    }

    /**
     * @CreatedBy : Mohit Jain
     * @createdDate : 21-May-2022
     * @description : FUNCTION TO GET THE DATE TIME FORMAT LIST
     * @returns $responsedata
     */
    public function getDateTimeFormatList() {
        $data = [];
        $data['date_short_format'] = ['d/m/y' => date('d/m/y'), 'd-m-Y' => date('d/m/Y'), 'm.d.y' => date('m.d.y'), 'm.d.Y' => date('m.d.Y'), 'y-m-d' => date('y-m-d'), 'Y-m-d' => date('Y-m-d')];
        $data['date_long_format'] = ['F j, Y' => date('F j, Y'), 'D M j Y' => date('D M j Y'), 'D/M/Y' => date('D/M/Y'), 'D-M-Y' => date('D-M-Y'), 'Y/M/D' => date('Y/M/D'), 'Y-M-D' => date('Y-M-D')];
        $data['time_short_format'] = ['g:i a' => date('g:i a'), 'h:i:s' => date('h:i:s'), 'g:i A' => date('g:i A'),];
        $data['time_long_format'] = ['G:i:s T' => date('G:i:s T')];
        return $data;
    }

    /**
     * @CreatedBy : Mohit Jain
     * @createdDate : 21-May-2022
     * @description : FUNCTION TO GET THE PRICE FORMAT LIST
     * @returns $responsedata
     */
    public function getPriceFormatList() {
        $data = [];
        $data = ['1,234.56' => '1,234.56', '1,234' => '1,234'];
        return $data;
    }

    /**
     * @CreatedBy : Mohit Jain
     * @createdDate : 21-May-2022
     * @description : FUNCTION TO GET THE SITE OWNER LIST
     * @returns $responsedata
     */
    public function getSiteOwnerList() {
        $data = [];
        $data = [
            '1' => 'Mihir',
            '2' => 'Mohit',
            '3' => 'Nitin',
            '4' => 'Niharika',
            '5' => 'Amir',];
        return $data;
    }

    /**
     * @CreatedBy : Mohit Jain
     * @createdDate : 21-May-2022
     * @description : FUNCTION TO GET THE MAP STYLE LIST
     * @returns $responsedata
     */
    public function getMapStyleList() {
        $data = [];
        $data = [
            'Hybrid' => 'Hybrid',
            'Roadmap' => 'Roadmap',
            'Satellite' => 'Satellite',
            'Terrain' => 'Terrain'
        ];
        return $data;
    }

    /**
     * @CreatedBy : Mohit Jain
     * @createdDate : 21-May-2022
     * @description : FUNCTION TO GET THE CAPTCHA TYPE LIST
     * @returns $responsedata
     */
    public function getCaptchaTypeList() {
        $data = [];
        $data = [
            'Zend/captcha' => 'Zend/captcha',
            'Google Recaptcha' => 'Google Recaptcha',
            'No captcha' => 'No captcha',
        ];
        return $data;
    }
    
    /**
     * @CreatedBy : Mohit Jain
     * @createdDate : 21-May-2022
     * @description : FUNCTION TO UPLOAD IMAGE DETAILS
     * @returns $responsedata
     */

    public function uploadImageAction() {
        $post = isset($_POST) ? $_POST : array();
        switch ($post['action']) {
            case 'save' :
                $this->saveAvatarTmp();
                break;
            default:
                $this->changeAvatar();
        }
    }
    
    /**
     * @CreatedBy : Mohit Jain
     * @createdDate : 21-May-2022
     * @description : FUNCTION TO UPLOAD THE IMAGE
     * @returns $responsedata
     */

    function changeAvatar() {
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $post = isset($_POST) ? $_POST : array();
        $max_width = "500";
        $path = 'images/tmp';
        $valid_formats = array("jpg", "png", "gif", "bmp", "jpeg", "pdf", "docx", "doc");
        $name = time() . $_FILES['photoimg']['name'];
        $size = $_FILES['photoimg']['size'];
        if (strlen($name)) {
            list($txt, $ext) = explode(".", $name);
            //Debug::dump($ext);
            //Debug::dump($valid_formats);
            //Debug::dump(in_array($ext, $valid_formats));exit;
            if (in_array($ext, $valid_formats)) {
                if ($size < (1024 * 1024)) { // Image size max 1 MB
                    $actual_image_name = 'avatar' . '_' . $user_id . '.' . $ext;
                    $tmp = $_FILES['photoimg']['tmp_name'];
                    $filePath = PUBLIC_PATH . '/temp/' . $name;
                    $filePreview = '/temp/' . $name;
                    if (move_uploaded_file($tmp, $filePath)) {
                        $width = $this->getWidth($filePath);
                        $height = $this->getHeight($filePath);
                        //Scale the image if it is greater than the width set above
                        if ($width > $max_width) {
                            $scale = $max_width / $width;
                            $uploaded = $this->resizeImage($filePath, $width, $height, $scale);
                        } else {
                            $scale = 1;
                            $uploaded = $this->resizeImage($filePath, $width, $height, $scale);
                        }
                        echo "<img class='photo' file-name='" . $name . "' class='' src='" . $filePreview . '?' . time() . "' class='preview'/>";
                    } else
                        echo "failed";
                } else
                    echo "Image file size max 1 MB";
            } else
                echo "Invalid file format..";
        } else
            echo "Please select image..!";
        exit;
    }
    
    /**
     * @CreatedBy : Mohit Jain
     * @createdDate : 21-May-2022
     * @description : FUNCTION TO SAVE THE AVATAR IMAGE DETAILS
     * @returns $responsedata
     */

    function saveAvatarTmp() {

        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;
        $post = isset($_POST) ? $_POST : array();
        $path = '\\images\uploads\tmp';
        $t_width = 300; // Maximum thumbnail width
        $t_height = 300;    // Maximum thumbnail height

        if (isset($_POST['t']) and $_POST['t'] == "ajax") {
            extract($_POST);

            $crop_enabled = $_POST['crop_enabled'];
            $loc = $_POST['loc'];
            if ($loc == "frontend_header_logo" || $loc == "admin_header_logo" || $loc == "admin_dashboard_logo" || $loc == "frontend_favicon" || $loc == "admin_favicon") {
                $user_folder = "company-setup";
            }
            $image_quality = '95';
            $imagePath = PUBLIC_PATH . '/upload/' . $user_folder . '/' . $_POST['image_name'];
            $new_image_thumb = PUBLIC_PATH . '/upload/thumb/100x100/' . $user_folder . '/' . $_POST['image_name'];

            $temp_path = PUBLIC_PATH . '/temp/' . $_POST['image_name'];

            if ($crop_enabled == "yes") {

                $ratio = ($t_width / $w1);
                $nw = ceil($w1 * $ratio);
                $nh = ceil($h1 * $ratio);
                $nimg = imagecreatetruecolor($nw, $nh);
                $im_src = imagecreatefromjpeg($temp_path);
                imagecopyresampled($nimg, $im_src, 0, 0, $x1, $y1, $nw, $nh, $w1, $h1);
                $result = imagejpeg($nimg, $imagePath, $image_quality);

                $crop_width = 30;
                $crop_height = 30;
                $thumbNew = imagecreatetruecolor($crop_width, $crop_height);
                imagecopyresampled($thumbNew, $im_src, 0, 0, $x1, $y1, $crop_width, $crop_height, $w1, $h1);
                $thumb = imagejpeg($thumbNew, $new_image_thumb, $image_quality);
            } elseif ($crop_enabled == "no") {
                //echo 'hello';exit;
                $result = copy($temp_path, $imagePath);
                $result1 = copy($temp_path, $new_image_thumb);
                $filename = $new_image_thumb;
                $image = imagecreatefromjpeg($filename);
                list($originalWidth, $originalHeight) = getimagesize($filename);

                // Size of image to create
                $width = 50;
                $height = 50;

                $background = imagecreatetruecolor($width, $height); //create the background 130x130
                $whiteBackground = imagecolorallocate($background, 255, 255, 255);
                imagefill($background, 0, 0, $whiteBackground); // fill the background with white
                imagecopyresampled($background, $image, 0, 0, 0, 0, $width, $height, $originalWidth, $originalHeight); // copy the image to the background
                header("Content-type: image/jpeg");
                ImageJpeg($background, $new_image_thumb, $image_quality); //display
            }
            //echo '<pre>';print_r();die();
            if ($result) {
                $image_path_sql = $user_folder . '/' . $_POST['image_name'];
                $response = '/upload/' . $image_path_sql;
            } else {
                $response = "error";
            }
        }
        //echo $imagePath.'?'.time();;
        echo $response;
        exit(0);
    }

}