<?php
class ControllerModulePromotion extends Controller {
	
	private $moduleData_module = 'promotion_module';

	private $moduleModel;
    private $moduleName;
    private $modulePath;
    private $callModel;
    private $moduleVersion;
    private $extensionLink;

    private $error = array();

    public function __construct($registry) {
        parent::__construct($registry);
        $this->config->load('isenselabs/promotion');

        $this->moduleName = $this->config->get('promotion_moduleName');
        $this->modulePath = $this->config->get('promotion_modulePath');
        $this->moduleVersion = $this->config->get('promotion_moduleVersion');
        $this->extensionLink = $this->url->link($this->config->get('promotion_extensionLink'), 'token=' . $this->session->data['token'].$this->config->get('promotion_extensionLink_type') , 'SSL');

        if(!$this->config->get($this->config->get('promotion_totalName').'_status')) {
            $version = (version_compare(VERSION, '2.2.0.0', '<')) ? 'FOR OC < 2.2.0.0' : 'FOR OC > 2.2.0.0';
            $order_total_path = (version_compare(VERSION, '2.2.0.0', '<')) ? '<strong>Extensions->Order Totals</strong>' : '<strong>Extensions->Extensions->Order Totals</strong>';
            $this->error['warning'] = 'Please go to '.$order_total_path.' and enable Promotion '.$version;
        }

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

        $this->load->model('tool/image');

        $this->callModel = $this->config->get('promotion_callModel');
        $this->moduleModel = $this->{$this->callModel};

        //Module loaders
        $this->load->model('setting/store');
        $this->load->model('localisation/language');
        $this->load->model('design/layout');
        $this->load->model('extension/module');
    }

    public function delete() {
        $this->load->language('extension/module');

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

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

        $this->load->model('extension/module');

        if (isset($this->request->get['module_id']) && $this->validateForm()) {
            $this->model_extension_module->deleteModule($this->request->get['module_id']);

            $this->session->data['success'] = $this->language->get('text_success');

            $this->response->redirect($this->url->link($this->modulePath, 'token=' . $this->session->data['token'], true));
        }
    }


	
    public function changeStatus() {
        if($this->request->server['REQUEST_METHOD'] == 'POST') {
            if(isset($this->request->post['module_id']) && isset($this->request->post['status'])) {
                $this->moduleModel->changeStatus($this->request->post['module_id'],$this->request->post['status']);
            }
        }
    }

    public function saveModuleSettings() {
        $this->load->model('setting/setting');

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

            //var_dump($this->request->post);exit;

            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']), 'SSL');
            }

            $this->model_setting_setting->editSetting($this->moduleName, $this->request->post);

            $this->session->data['success'] = $this->language->get('text_success');
            $this->response->redirect($this->url->link($this->modulePath, 'token=' . $this->session->data['token'], 'SSL'));
        }
    }

    public function promotion() { 
		$data['moduleName'] = $this->moduleName;
		$data['modulePath'] = $this->modulePath;
		$data['moduleData_module'] = $this->moduleData_module;
		$data['moduleModel'] = $this->callModel;
	 

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

		$data['heading_title'] = $this->language->get('heading_title') . ' ' . $this->moduleVersion;

        if(!isset($this->request->get['store_id'])) {
           $this->request->get['store_id'] = 0; 
        }
	
        $store = $this->getCurrentStore($this->request->get['store_id']);
		
        if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) { 

            //var_dump($this->request->post);exit;

            if(!isset($this->request->post['actions'])){
                $this->request->post['actions'] = array();
            }
            if(!isset($this->request->post['conditions'])){
                $this->request->post['conditions'] = array();
            } 

            foreach ($this->request->post['actions'] as $key => &$cond) { 

                    if(!isset($cond['mainSelect'])) {
                        $cond['mainSelect'] = '';
                        $cond['product'] = array();
                        $cond['category'] = array();
                    }
                    else if($cond['mainSelect'] != 'discount_on_products' && $cond['mainSelect'] != 'discount_on_categories' &&  $cond['mainSelect'] != 'add_product_cart'){
                        $cond['product'] = array();
                        $cond['category'] = array();
                    }
            }

            if (!isset($this->request->get['module_id'])) {
                $this->model_extension_module->addModule('promotion', $this->request->post);
            } else {
                $this->model_extension_module->editModule($this->request->get['module_id'], $this->request->post);
            }

            $this->session->data['success'] = $this->language->get('text_success');
            if (!isset($this->request->get['module_id'])) {
                $this->response->redirect($this->url->link($this->modulePath, 'token=' . $this->session->data['token'], 'SSL'));
            } else {
                $this->response->redirect($this->url->link($this->modulePath.'/promotion', 'module_id='. $this->request->get['module_id'] .'&token=' . $this->session->data['token'], 'SSL'));
            }
        }

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

        if (isset($this->request->get['module_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
            $module_info = $this->model_extension_module->getModule($this->request->get['module_id']);
            $data['moduleData'] =  $module_info;
            foreach ($data['moduleData']['conditions'] as $key => &$cond) {
                if(!empty($cond['product_id'])){
                   $cond['product_name'] =  $this->moduleModel->getProductNameByID($cond['product_id']);
                }
                if(!empty($cond['category_id'])){
                   $cond['category_name'] =  $this->moduleModel->getCategoryNameByID($cond['category_id']);
                }
                if(!empty($cond['manufacturer_id'])){
                   $cond['manufacturer_name'] =  $this->moduleModel->getManufacNameByID($cond['manufacturer_id']);
                }
                if(!empty($cond['customer_id'])){
                   $cond['customer_name'] =  $this->moduleModel->getCustomerNameByID($cond['customer_id']);
                }
            }

            if (!empty($module_info['information_page']['image'])) {
                $data['information_thumb'] = $this->model_tool_image->resize($module_info['information_page']['image'], 100, 100);
            } else {
                $data['information_thumb'] = $this->model_tool_image->resize('no_image.png', 100, 100);
            }
            $data['image_placeholder'] = $this->model_tool_image->resize('no_image.png', 100, 100);


            foreach ($data['moduleData']['actions'] as $key => &$cond) {        
                    if(isset($cond['product']) && !empty($cond['product'])){
                        foreach ($cond['product'] as $key1 => $value) {
                            $cond['product'][$key1] = array();
                            $cond['product'][$key1] = array(
                                                        'product_id' => $value,
                                                        'name' => $this->moduleModel->getProductNameByID($value)
                                                        );
                        }
                    } 

                    if(isset($cond['exclude_product']) && !empty($cond['exclude_product'])){
                        foreach ($cond['exclude_product'] as $key4 => $value) {
                            $cond['exclude_product'][$key4] = array();
                            $cond['exclude_product'][$key4] = array(
                                                        'product_id' => $value,
                                                        'name' => $this->moduleModel->getProductNameByID($value)
                                                        );
                        }
                    } 

                    if(isset($cond['exclude_product_from_cat']) && !empty($cond['exclude_product_from_cat'])){
                        foreach ($cond['exclude_product_from_cat'] as $key5 => $value) {
                            $cond['exclude_product_from_cat'][$key5] = array();
                            $cond['exclude_product_from_cat'][$key5] = array(
                                                        'product_id' => $value,
                                                        'name' => $this->moduleModel->getProductNameByID($value)
                                                        );
                        }
                    }

                    if(isset($cond['category']) && !empty($cond['category'])){
                        foreach ($cond['category'] as $key2 => $value) {
                            $cond['category'][$key2] = array();
                            $cond['category'][$key2] = array(
                                                        'category_id' => $value,
                                                        'name' => $this->moduleModel->getCategoryNameByID($value)
                                                        );
                        }
                    }   

                    if(isset($cond['exclude_category']) && !empty($cond['exclude_category'])){
                        foreach ($cond['exclude_category'] as $key3 => $value) {
                                $cond['exclude_category'][$key3] = array();
                                $cond['exclude_category'][$key3] = array(
                                                            'category_id' => $value,
                                                            'name' => $this->moduleModel->getCategoryNameByID($value)
                                                            );
                            }
                    }
            }  
        } else {
            $data['is_new'] = true;
            $data['image_placeholder'] = $this->model_tool_image->resize('no_image.png', 100, 100);
            $data['information_thumb'] = $this->model_tool_image->resize('no_image.png', 100, 100);
        }
		
		if (isset($this->session->data['success'])) {
			$data['success'] = $this->session->data['success'];
			unset($this->session->data['success']);
		} else {
			$data['success'] = '';
		}
		
		if (isset($this->error['warning'])) {
			$data['error_warning'] = $this->error['warning'];
		} else {
			$data['error_warning'] = '';
		}


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

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'],  'SSL')
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_module'),
			'href' => $this->extensionLink
		);

        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('heading_title_all_promos'),
            'href' => $this->url->link($this->modulePath, 'token=' . $this->session->data['token'], 'SSL')
        );

		if (!isset($this->request->get['module_id'])) {
            $data['breadcrumbs'][] = array(
                'text' => $this->language->get('heading_title'),
                'href' => $this->url->link($this->modulePath.'/promotion', 'token=' . $this->session->data['token'], 'SSL')
            );
        } else {
            $data['breadcrumbs'][] = array(
                'text' => $this->language->get('heading_title').' - '.$module_info['name'],
                'href' => $this->url->link($this->modulePath.'/promotion', 'token=' . $this->session->data['token'] . '&module_id=' . $this->request->get['module_id'], 'SSL')
            );
        }

        //Customer Groups
         if(VERSION >= '2.1.0.1') {
            $this->load->model('customer/customer_group');
            $data['customer_groups'] = $this->model_customer_customer_group->getCustomerGroups();
        } else {
            $this->load->model('sale/customer_group');
            $data['customer_groups'] = $this->model_sale_customer_group->getCustomerGroups();
        } 

        //Lang Data
        $language_strings = $this->language->load($this->modulePath);
        foreach ($language_strings as $code => $languageVariable) {
             $data[$code] = $languageVariable;
        }

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

		$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) {
            $data['languages'][$key]['flag_url'] = version_compare(VERSION, '2.2.0.0', "<") 
            ? 'view/image/flags/'.$data['languages'][$key]['image']
            : 'language/'.$data['languages'][$key]['code'].'/'.$data['languages'][$key]['code'].'.png"';
        }
        
        $data['store']                  = $store;
        $data['token']                  = $this->session->data['token'];

        $data['currency']               = $this->config->get('config_currency');
        
        if (!isset($this->request->get['module_id'])) {
            $data['action'] =   $this->url->link($this->modulePath.'/promotion', 'token=' . $this->session->data['token'], 'SSL');
        } else {
            $data['action'] = $this->url->link($this->modulePath.'/promotion', 'token=' . $this->session->data['token'] . '&module_id=' . $this->request->get['module_id'], 'SSL');
        }

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

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

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

    public function index(){

        if (isset($this->request->get['module_id'])) {
          $this->response->redirect($this->url->link($this->modulePath.'/promotion', 'module_id='. $this->request->get['module_id'] .'&token=' . $this->session->data['token'], 'SSL'));
        }

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

        $data['moduleName']         = $this->moduleName;
        $data['modulePath']         = $this->modulePath;
        $data['moduleNameSmall']    = $this->moduleName;
        $data['moduleData_module']  = $this->moduleData_module;
        $data['moduleModel']        = $this->moduleModel;
     
        $this->load->language($this->modulePath);
        $this->load->model($this->modulePath);

        $language_strings = $this->language->load($this->modulePath);
        foreach ($language_strings as $code => $languageVariable) {
             $data[$code] = $languageVariable;
        }


        $data['heading_title'] = $this->language->get('heading_title_all_promos');

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

        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_home'),
            'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'],  'SSL')
        );

        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_module'),
            'href' => $this->extensionLink
        );
        
        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('heading_title_all_promos'),
            'href' => $this->url->link($this->modulePath, 'token=' . $this->session->data['token'], 'SSL')
        );



        if (isset($this->error['warning'])) {
            $data['error_warning'] = $this->error['warning'];
        } else {
            $data['error_warning'] = '';
        }

        if (isset($this->session->data['success'])) {
            $data['success'] = $this->session->data['success'];
            unset($this->session->data['success']);
        } else {
            $data['success'] = '';
        }

        $data['promotion']              = $this->moduleModel->getAllPromos();

        //change status url
        $data['change_status_url']      = $this->url->link($this->modulePath.'/changeStatus', NULL , 'SSL');
        $data['action']                 = $this->url->link($this->modulePath.'/saveModuleSettings', 'token=' . $this->session->data['token'], 'SSL');
        $data['addnew']                 = $this->url->link($this->modulePath.'/promotion', 'token=' . $this->session->data['token'], 'SSL');
        $data['cancel']                 = $this->extensionLink;

        $data['moduleData']             = $this->config->get($this->moduleName);

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

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

        $this->response->setOutput($this->load->view($this->config->get('promotion_modulePath_stats').'.tpl', $data));
    }

	protected function validateForm() {
		if (!$this->user->hasPermission('modify', $this->modulePath)) {
			$this->error['warning'] = $this->language->get('error_permission');
		}
        
		return !$this->error;
	}

    private function getCatalogURL() {
        if (isset($_SERVER['HTTPS']) && (($_SERVER['HTTPS'] == 'on') || ($_SERVER['HTTPS'] == '1'))) {
            $storeURL = HTTPS_CATALOG;
        } else {
            $storeURL = HTTP_CATALOG;
        } 
        return $storeURL;
    }

    private function getServerURL() {
        if (isset($_SERVER['HTTPS']) && (($_SERVER['HTTPS'] == 'on') || ($_SERVER['HTTPS'] == '1'))) {
            $storeURL = HTTPS_SERVER;
        } else {
            $storeURL = HTTP_SERVER;
        } 
        return $storeURL;
    }

    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(); 
        }
        return $store;
    }
    
    public function install() {
	    $this->load->model($this->modulePath);
        $this->moduleModel->install();
    }
    
    public function uninstall() {
    	 $this->load->model($this->modulePath);
        $this->moduleModel->uninstall();
    }

}
