<?php

class ControllerExtensionModuleOrderSuccessPage extends Controller {

	private $moduleName;

    private $moduleVersion;

    private $callModel;

    private $modulePath;

    private $moduleModel;

    private $extensionsLink;

    private $error = array(); 

    private $data = array(); 



    public function __construct($registry) {

        parent::__construct($registry);

        $this->config->load('isenselabs/ordersuccesspage');



        // Module VERSION

        $this->moduleVersion = $this->config->get('ordersuccesspage_moduleVersion');        

        





        /* OC version-specific declarations - Begin */

        $this->moduleName        = $this->config->get('ordersuccesspage_moduleName');        

        $this->callModel         = $this->config->get('ordersuccesspage_callModel');

        $this->modulePath        = $this->config->get('ordersuccesspage_modulePath');

        $this->extensionsLink    = $this->url->link($this->config->get('ordersuccesspage_extensionsLink'), 'user_token=' . $this->session->data['user_token'].$this->config->get('ordersuccesspage_extensionsLink_type'), 'SSL');

        /* OC version-specific declarations - End */





        /* Module-specific declarations - Begin */

        $this->load->language($this->modulePath);

        $this->load->model($this->modulePath);

        $this->moduleModel = $this->{$this->callModel};

        

        // Multi-Store

        $this->load->model('setting/store');

        // Settings

        $this->load->model('setting/setting');

        // Multi-Lingual

        $this->load->model('localisation/language');

        

        $this->load->model('catalog/product');



        /* Module-specific loaders - End */

    }



    public function index() {

		// Main Variables

		$data['moduleName'] 				= $this->moduleName;

		$data['moduleNameSmall']	 		= $this->moduleName;

		$data['moduleModel'] 				= $this->callModel;

        $data['modulePath']                 = $this->modulePath;



		// Load language files

        $this->load->language($this->modulePath);

		

		// Load models

        $this->load->model($this->modulePath);



        $this->load->model('localisation/language');

		

		

		// Load script & stylesheets

        $this->document->addStyle('view/stylesheet/'.$this->moduleName.'/'.$this->moduleName.'.css');

		$this->document->addScript('view/javascript/'.$this->moduleName.'/main.js');

		

		// Set main title

        $this->document->setTitle($this->language->get('heading_title'));



		// Check for set store_id

        if(!isset($this->request->get['store_id'])) {

           $this->request->get['store_id'] 	= 0; 

        }

		

		// Get store info

        $store 								= $this->getCurrentStore($this->request->get['store_id']);

		

		// Save module settings

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) { 	
            $this->moduleModel->removeEventHandlers();

            if (!empty($_POST['OaXRyb1BhY2sgLSBDb21'])) {
                $this->request->post[$this->moduleName]['LicensedOn'] = $_POST['OaXRyb1BhY2sgLSBDb21'];
            }

            if (!empty($_POST['cHRpbWl6YXRpb24ef4fe'])) {
                $this->request->post[$this->moduleName]['License'] = json_decode(base64_decode($_POST['cHRpbWl6YXRpb24ef4fe']), true);
            }



        	$this->model_setting_setting->editSetting($this->moduleName, $this->request->post, $this->request->post['store_id']);
            $this->session->data['success'] = $this->language->get('text_success');

            $status = (int)($this->request->post[$this->moduleName]['Enabled'] == 'yes');
            $this->model_setting_setting->editSetting($this->config->get('ordersuccesspage_status_group'), array($this->config->get('ordersuccesspage_status_value') => $status));

            if ($status) {
                $this->moduleModel->setupEventHandlers();
            }

            $this->response->redirect($this->url->link($this->modulePath, 'store_id='.$this->request->post['store_id'] . '&user_token=' . $this->session->data['user_token'], 'SSL'));
        }

		

		// Get success message

		if (isset($this->session->data['success'])) {

			$data['success'] 				= $this->session->data['success'];

			unset($this->session->data['success']);

		} else {

			$data['success'] 				= '';

		}

		

		// Get error/warning message

		if (isset($this->error['warning'])) {

			$data['error_warning'] 			= $this->error['warning'];

		} else {

			$data['error_warning'] 			= '';

		}



		// Breadcrumb data

        $data['breadcrumbs']   				= array();

        $data['breadcrumbs'][] 				= array(

            'text' 					=> $this->language->get('text_home'),

            'href' 					=> $this->url->link('common/dashboard', 'user_token=' . $this->session->data['user_token'], 'SSL'),

        );

        $data['breadcrumbs'][] 				= array(

            'text' 					=> $this->language->get('text_module'),

            'href' 					=> $this->extensionsLink,

        );

        $data['breadcrumbs'][] 				= array(

            'text' 					=> $this->language->get('heading_title'),

            'href' 					=> $this->url->link($this->modulePath, 'user_token=' . $this->session->data['user_token'], 'SSL'),

        );



		// Language variables	

        $languageVariables 					= array('heading_title', 'error_permission', 'text_success', 'text_enabled',

			'text_disabled', 'button_cancel', 'save_changes', 'text_default', 'text_module');

       

        foreach ($languageVariables as $languageVariable) {

            $data[$languageVariable] 		= $this->language->get($languageVariable);

        }

        $data['heading_title'] .= ' '.$this->moduleVersion;

		

		// Data for the template files

        $data['stores']						= array_merge(array(0 => array('store_id' => '0', 'name' => $this->config->get('config_name') . ' (' . $data['text_default'].')', 'url' => HTTP_SERVER, 'ssl' => HTTPS_SERVER)), $this->model_setting_store->getStores());

        $data['languages']              	= $this->model_localisation_language->getLanguages();



        foreach ($data['languages'] as $key => $value) {

			if(version_compare(VERSION, '2.2.0.0', "<")) {

				$data['languages'][$key]['flag_url'] = 'view/image/flags/'.$data['languages'][$key]['image'];



			} else {

				$data['languages'][$key]['flag_url'] = 'language/'.$data['languages'][$key]['code'].'/'.$data['languages'][$key]['code'].'.png"';

			}

		}



        $data['store']                  	= $store;

        $data['user_token']                  	= $this->session->data['user_token'];

        $data['action']                 	= $this->url->link($this->modulePath, 'user_token=' . $this->session->data['user_token'], 'SSL');

        $data['cancel']                 	= $this->url->link($this->modulePath, 'user_token=' . $this->session->data['user_token'], 'SSL');

		$data['moduleSettings']				= $this->model_setting_setting->getSetting($this->moduleName, $store['store_id']);

        $data['moduleData']					= (isset($data['moduleSettings'][$this->moduleName])) ? $data['moduleSettings'][$this->moduleName] : array();

		$data['language_id']				= $this->config->get('config_language_id');

		$data['modelCatalogProduct']		= $this->model_catalog_product;

		$data['currency']					= $this->config->get('config_currency');



		// Get the the main OpenCart admin styles & design

		$data['header']						= $this->load->controller('common/header');

		$data['column_left']				= $this->load->controller('common/column_left');

		$data['footer']						= $this->load->controller('common/footer');

		
        $data['unlicensed_notice']          = empty($data['moduleData']['LicensedOn']) ? base64_decode('ICAgIDxkaXYgY2xhc3M9ImFsZXJ0IGFsZXJ0LWRhbmdlciBmYWRlIGluIj4NCiAgICAgICAgPGJ1dHRvbiB0eXBlPSJidXR0b24iIGNsYXNzPSJjbG9zZSIgZGF0YS1kaXNtaXNzPSJhbGVydCIgYXJpYS1oaWRkZW49InRydWUiPsOXPC9idXR0b24+DQogICAgICAgIDxoND5XYXJuaW5nISBVbmxpY2Vuc2VkIHZlcnNpb24gb2YgdGhlIG1vZHVsZSE8L2g0Pg0KICAgICAgICA8cD5Zb3UgYXJlIHJ1bm5pbmcgYW4gdW5saWNlbnNlZCB2ZXJzaW9uIG9mIHRoaXMgbW9kdWxlISBZb3UgbmVlZCB0byBlbnRlciB5b3VyIGxpY2Vuc2UgY29kZSB0byBlbnN1cmUgcHJvcGVyIGZ1bmN0aW9uaW5nLCBhY2Nlc3MgdG8gc3VwcG9ydCBhbmQgdXBkYXRlcy48L3A+PGRpdiBzdHlsZT0iaGVpZ2h0OjVweDsiPjwvZGl2Pg0KICAgICAgICA8YSBjbGFzcz0iYnRuIGJ0bi1kYW5nZXIiIGhyZWY9ImphdmFzY3JpcHQ6dm9pZCgwKSIgb25jbGljaz0iJCgnYVtocmVmPSNpc2Vuc2Vfc3VwcG9ydF0nKS50cmlnZ2VyKCdjbGljaycpIj5FbnRlciB5b3VyIGxpY2Vuc2UgY29kZTwvYT4NCiAgICA8L2Rpdj4=') : '';
        $data['license_encoded']            = !empty($data['moduleData']['LicensedOn']) ? base64_encode(json_encode($data['moduleData']['License'])) : '';
        $data['license_expiration_date']    = !empty($data['moduleData']['LicensedOn']) ? date("F j, Y", strtotime($data['moduleData']['License']['licenseExpireDate'])) : '';
        $data['ticket_open_link']           = 'http://isenselabs.com/tickets/open/' . base64_encode('Support Request') . '/' . base64_encode('238') . '/' . base64_encode($_SERVER['SERVER_NAME']);

        if (!empty($data['moduleData']['PromotedProducts'])) {
            foreach ($data['moduleData']['PromotedProducts'] as $k=>$pid) {
                $data['moduleData']['PromotedProducts'][$k] = $this->model_catalog_product->getProduct($pid);
                $data['moduleData']['PromotedProducts'][$k]['id'] = $pid;
            }
        }

        $data['tab_mainsettings'] = $this->load->view($this->modulePath . '/tab_mainsettings', $data);
        $data['tab_orderinfo'] = $this->load->view($this->modulePath . '/tab_orderinfo', $data);
        $data['tab_promoteproducts'] = $this->load->view($this->modulePath . '/tab_promoteproducts', $data);
        $data['tab_controlpanel'] = $this->load->view($this->modulePath . '/tab_controlpanel', $data);
        $data['tab_support'] = $this->load->view($this->modulePath . '/tab_support', $data);

		$this->response->setOutput($this->load->view($this->modulePath, $data));

    }

    public function install() {
        $this->moduleModel->setupEventHandlers();
    }

    public function uninstall() {
        $this->moduleModel->removeEventHandlers();
    }

	// Check for permissions 

	protected function validateForm() {

		if (!$this->user->hasPermission('modify', $this->modulePath)) {

			$this->error['warning'] 		= $this->language->get('error_permission');

		}

		

		return !$this->error;

	}

	

	// Module-specific settings

	public function get_store_settings() {

        $this->load->model($this->modulePath);

        $this->load->model('setting/store');

		$this->load->model('setting/setting');

        $this->load->model('localisation/language');

		

		$data['languages']					= $this->model_localisation_language->getLanguages();

		$data['language_id']				= $this->config->get('config_language_id');

		$data['storedata']['id']			= $this->request->get['storedata_id'];

		$store_id							= $this->request->get['store_id'];

		$data['data']						= $this->model_setting_setting->getSetting($this->moduleName, $store_id);

		$data['moduleName']					= $this->moduleName;

		$data['moduleData']					= (isset($data['data'][$this->moduleName])) ? $data['data'][$this->moduleName] : array();

		$data['newAddition']				= true;

		

		// Outputs the data from the function

		$this->response->setOutput($this->load->view($this->modulePath.'/tab_storetab.tpl', $data));

	}

	// Gets the front-end URL

    private function getCatalogURL() {

        if (isset($_SERVER['HTTPS']) && (($_SERVER['HTTPS'] == 'on') || ($_SERVER['HTTPS'] == '1'))) {

            $storeURL 						= HTTPS_CATALOG;

        } else {

            $storeURL 						= HTTP_CATALOG;

        } 

        return $storeURL;

    }



	// Get the data about a given store

    private function getCurrentStore($store_id) {    

        if($store_id && $store_id != 0) {

            $store 							= $this->model_setting_store->getStore($store_id);

        } else {

            $store['store_id'] 				= 0;

            $store['name'] 					= $this->config->get('config_name');

            $store['url']					= $this->getCatalogURL(); 

			$store['ssl']					= $this->getCatalogURL();

        }

		

        return $store;

    }

}

?>
