<?php
//ADMIN
class ControllerModuleGiftTeaser extends Controller {

    public function index() { 
		
        $this->load->language('module/giftTeaser');
        $this->load->model('module/giftTeaser');
        $this->load->model('setting/store');
        $this->load->model('localisation/language');
        $this->load->model('design/layout');
		
        $catalogURL = $this->getCatalogURL();
		$this->document->addScript('view/javascript/giftTeaser/timepicker.js');
        $this->document->addScript('view/javascript/giftTeaser/bootstrap/js/bootstrap.min.js');
        $this->document->addStyle('view/javascript/giftTeaser/bootstrap/css/bootstrap.min.css');
        $this->document->addStyle('view/stylesheet/giftTeaser/font-awesome/css/font-awesome.min.css');
		$this->document->addScript('view/javascript/giftTeaser/bootbox.js');
		$this->document->addScript('view/javascript/giftTeaser/modal.js');
		$this->document->addScript('view/javascript/giftTeaser/modal-manager.js');
		$this->document->addStyle('view/stylesheet/giftTeaser/modal.css');
		$this->document->addStyle('view/stylesheet/giftTeaser/timepicker.css');
		$this->document->addScript('view/javascript/giftTeaser/colorpicker.js');
		$this->document->addStyle('view/stylesheet/giftTeaser/colorpicker.css');
		$this->document->addScript('view/javascript/ckeditor/ckeditor.js');
	    $this->document->addScript('view/javascript/giftTeaser/main.js');
		$this->document->addStyle('view/stylesheet/giftTeaser/giftTeaser.css');
	    $this->document->setTitle($this->language->get('heading_title'));

        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')) { 	
            if (!$this->user->hasPermission('modify', 'module/giftTeaser')) {
                $this->redirect($this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL'));
            }

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

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

			$this->model_module_giftTeaser->editSetting('giftTeaser_module', $this->request->post['giftTeaser_module'], $this->request->post['store_id']);
            $this->model_module_giftTeaser->editSetting('giftTeaser', $this->request->post, $this->request->post['store_id']);
            $this->session->data['success'] = $this->language->get('text_success');
			
            $this->redirect($this->url->link('module/giftTeaser', 'store_id='.$this->request->post['store_id'] . '&token=' . $this->session->data['token'], 'SSL'));
        }
		$this->data['modules']  = $this->model_module_giftTeaser->getSetting('giftTeaser_module', $store['store_id']);
		$this->data['layouts']  = $this->model_design_layout->getLayouts();
 		$this->data['error_code'] = '';
        if (isset($this->error['code'])) {
            $this->data['error_code'] = $this->error['code'];
        } 

        $this->data['breadcrumbs']   = array();
        $this->data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_home'),
            'href' => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
        );
        $this->data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_module'),
            'href' => $this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL'),
        );
        $this->data['breadcrumbs'][] = array(
            'text' => $this->language->get('heading_title'),
            'href' => $this->url->link('module/giftTeaser', 'token=' . $this->session->data['token'], 'SSL'),
        );
		
        $languageVariables = array(
            'entry_code',
            'heading_title',
            'error_input_form',
            'text_yes',
            'text_no',
            'text_default',
            'text_enabled',
            'text_disabled',
            'text_text',
            'save_changes',
            'button_cancel',
            'text_settings',
            'button_add',
            'button_edit',
            'button_remove',
            'text_special_duration',
            'entry_layout_options',
            'entry_position_options',
            'entry_layout',         
            'entry_position',       
            'entry_status',         
            'entry_sort_order',     
            'entry_layout_options',  
            'entry_position_options',
            'text_content_top', 
            'text_content_bottom',
            'text_column_left', 
            'text_column_right',
            'button_add_module',
            'button_remove',
            'default_heading_title',
            'custom_design',
            'widget_help',
            'store_front_widget',
            'text_custom',
            'text_text',
            'text_background',
            'text_border',
            'custom_css',
            'text_condition',
            'custom_colors',
            'wrap_in_widget',
            'heading_background',
            'gift_image_size',
            'entry_default',
            'add_new_gift',
            'entry_free_gift_label',
			'show_free_gifts',
			'free_gifts_message_title',    
        );
       
        foreach ($languageVariables as $languageVariable) {
            $this->data[$languageVariable] = $this->language->get($languageVariable);
        }
		
		$this->data['maxGiftId'] = $this->model_module_giftTeaser->getMaxGiftId();
        $this->data['stores'] = array_merge(array(0 => array('store_id' => '0', 'name' => $this->config->get('config_name') . ' ' . $this->data['text_default'], 'url' => HTTP_SERVER, 'ssl' => HTTPS_SERVER)), $this->model_setting_store->getStores());
        $this->data['error_warning']          = '';  
        $this->data['languages']              = $this->model_localisation_language->getLanguages();
        $this->data['store']                  = $store;
        $this->data['token']                  = $this->session->data['token'];
        $this->data['action']                 = $this->url->link('module/giftTeaser', 'token=' . $this->session->data['token'], 'SSL');
        $this->data['cancel']                 = $this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL');
        $this->data['data']                   = $this->model_module_giftTeaser->getSetting('giftTeaser', $store['store_id']);
        $this->data['catalog_url']            = $catalogURL;
	    $this->template = 'module/giftTeaser.tpl';
        $this->children = array('common/header', 'common/footer');
        $this->response->setOutput($this->render());
    }

	public function autocompleteProduct() {
		$json = array();
		$this->load->model('tool/image');
		if (isset($this->request->post['filter_name']) &&  isset($this->request->post['store_id']) ) {
			$this->load->model('module/giftTeaser');
			if (isset($this->request->post['filter_name'])) {
				$filter_name = $this->request->post['filter_name'];
			} else {
				$filter_name = '';
			}

			if (isset($this->request->get['limit'])) {
				$limit = $this->request->get['limit'];	
			} else {
				$limit = 20;	
			}			

			$data = array(
				'filter_name'  => $filter_name,
				'start'        => 0,
				'limit'        => $limit,
				'store_id'	   => $this->request->post['store_id']
			);

			$results = $this->model_module_giftTeaser->getProducts($data);
			
			foreach ($results as $result) {
	
				$option_data = array();
				$json[] = array(
					'product_id' => $result['product_id'],
					'name'       => strip_tags(html_entity_decode($result['name'], ENT_QUOTES, 'UTF-8')),	
					'model'      => $result['model'],
					'price'      => $result['price'],
					'quantity' 	 =>  $result['quantity'],
					'viewed' 	 => $result['viewed'],
					'date_added' => $result['date_added'],
					'image'		 => $this->model_tool_image->resize($result['image'], 100, 100),
					'link'       => $this->getCatalogURL().'index.php?route=product/product&product_id=' . $result['product_id'],
					'date_added' 	=>  $result['date_added'],
				);	
			}
		}

		$this->response->setOutput(json_encode($json));
	}
	
	public function autocompleteCategory() {
		$json = array();
		if (isset($this->request->post['filter_name']) && isset($this->request->post['store_id'])) {
			$this->load->model('module/giftTeaser');
			$data = array('filter_name' => $this->request->post['filter_name'], 'store_id' => $this->request->post['store_id']);
			$results = $this->model_module_giftTeaser->getCategories($data);
			foreach ($results as $result) {
				$json[] = array(
					'category_id' 	=> $result['category_id'], 
					'name'        	=> strip_tags(html_entity_decode($result['name'], ENT_QUOTES, 'UTF-8')),
					'link'       	=> $this->getCatalogURL().'index.php?route=product/category&path=' . $result['path_id'],
					'date_added' 	=> $result['date_added'],	
				);
			}		
		}
		$sort_order = array();
		foreach ($json as $key => $value) {
			$sort_order[$key] = $value['name'];
		}
		array_multisort($sort_order, SORT_ASC, $json);
		$this->response->setOutput(json_encode($json));
	}	

    public function giftList() {
    	$this->load->model('tool/image');
        $this->load->model('module/giftTeaser');
        $this->load->language('module/giftTeaser');
        $this->data['currencyRight'] = $this->currency->getSymbolRight($this->config->get('config_currency'));
        $this->data['currencyLeft'] =  $this->currency->getSymbolLeft($this->config->get('config_currency'));
		 

		$sort = 'start_date';
    	$order = 'ASC';
    	$page = 1;
        
        if (isset($this->request->get['sort'])) {
            $sort = $this->request->get['sort'];
        }

        if (isset($this->request->get['order'])) {
            $order = $this->request->get['order'];
        }

        if (isset($this->request->get['page'])) {
            $page = $this->request->get['page'];
        }
            
        $url = '';
		
        if (isset($this->request->get['sort'])) {
            $url .= '&sort=' . $this->request->get['sort'];
        }
        if (isset($this->request->get['order'])) {
            $url .= '&order=' . $this->request->get['order'];
        }
        if (isset($this->request->get['page'])) {
            $url .= '&page=' . $this->request->get['page'];
        }

        $data   = array(
            'sort' => $sort,
            'order' => $order,
            'start' => ($page - 1) * 10,//$this->config->get('config_admin_limit'),
            'limit' => 10,//$this->config->get('config_admin_limit'),
            'store_id' => $this->request->get['store_id']
        );    
		
        $gifts = $this->model_module_giftTeaser->getGifts($data); 

        $url = '';
        if ($order == 'ASC') {
            $url .= '&order=DESC';
        } else {
            $url .= '&order=ASC';
        }

        $this->data['name']    = 'index.php?route=module/giftTeaser/giftList&store_id='.$this->request->get['store_id'] . '&token=' . $this->session->data['token'] . '&sort=pd.name' . $url;
		$this->data['quantity']     = 'index.php?route=module/giftTeaser/giftList&store_id='.$this->request->get['store_id'] . '&token=' . $this->session->data['token'] . '&sort=p.quantity' . $url;
		$this->data['start_date']   = 'index.php?route=module/giftTeaser/giftList&store_id='.$this->request->get['store_id'] . '&token=' . $this->session->data['token'] . '&sort=gt.start_date' . $url;
		$this->data['end_date'] 	= 'index.php?route=module/giftTeaser/giftList&store_id='.$this->request->get['store_id'] . '&token=' . $this->session->data['token'] . '&sort=gt.end_date' . $url;
   		$this->data['sort_order'] 	= 'index.php?route=module/giftTeaser/giftList&store_id='.$this->request->get['store_id'] . '&token=' . $this->session->data['token'] . '&sort=gt.sort_order' . $url;
		$this->data['condition_type'] 	= 'index.php?route=module/giftTeaser/giftList&store_id='.$this->request->get['store_id'] . '&token=' . $this->session->data['token'] . '&sort=gt.condition_type' . $url;
        $url = '';
        if (isset($this->request->get['sort'])) {
            $url .= '&sort=' . $this->request->get['sort'];
        }
        if (isset($this->request->get['order'])) { 
            $url .= '&order=' . $this->request->get['order'];
        } 
		foreach ($gifts as $key => $gift) {
			$gifts[$key]['image'] = $this->model_tool_image->resize($gift['image'], 100, 100);
		} 
		
		 $languageVariables = array (
            'text_product',
            'text_quantity',
			'text_viewed',
			'text_total',
			'text_price',
			'text_changing',
			'text_start_date',
			'text_end_date',
			'text_added_on',
			'text_condition',
			'button_add',
            'button_edit',            
            'button_remove',
            'text_remains',
            'text_actions',
            'tooltip_quantity',
			'tooltip_start_date',
			'tooltip_end_date',
			'tooltip_sort_order',
			'tooltip_total',
			'text_sort_order',
        );
        foreach ($languageVariables as $languageVariable) {
            $this->data[$languageVariable] = $this->language->get($languageVariable);
        }
		
        $pagination               = new Pagination();
        $pagination->total        = $this->model_module_giftTeaser->getTotalGifts($this->request->get['store_id']); 
        $pagination->page         = $page;
        $pagination->limit        = 10;
        $pagination->text         = $this->language->get('text_pagination');
        $pagination->url          = 'index.php?route=module/giftTeaser/giftList&store_id='.$this->request->get['store_id'].'&token=' . $this->session->data['token'] . $url . '&page={page}';
        $this->data['pagination'] = $pagination->render();
        $this->data['sort']       = $sort;
        $this->data['order']      = $order;
        $this->data['gifts'] 	  = $gifts;
        $this->template = "module/giftTeaser/giftList.tpl";
		$this->response->setOutput($this->render());
    }
    
	public function removeGift() {
		$this->load->model('module/giftTeaser');
		$this->model_module_giftTeaser->removeGift($this->request->post['gift_id']);
	}
    
    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('module/giftTeaser');
	    $this->model_module_giftTeaser->install();
    }
    
    public function uninstall() {
    	$this->load->model('setting/setting');	
		$this->load->model('setting/store');
		$this->model_setting_setting->deleteSetting('giftTeaser_module', 0);
		$stores=$this->model_setting_store->getStores();
		foreach ($stores as $store) {
			$this->model_setting_setting->deleteSetting('giftTeaser_module', $store['store_id']);
		}
        $this->load->model('module/giftTeaser');
        $this->model_module_giftTeaser->uninstall();
    }
	
	public function giftForm() {	
		$this->load->language('module/giftTeaser');
		$this->load->model('tool/image');
		$this->load->model('module/giftTeaser');
		$this->load->model('localisation/language');
		$languageVariables = array(
			'entry_product',
			'entry_category', 
			'valid_from', 
			'valid_to', 
			'get_gift_when',
			'entry_sort_order',
			'condition_total',
			'condition_some',
			'condition_certain',
			'condition_category',
            'total_amount',
            'gift_options',
            'gift_description',
            'button_save',
            'button_cancel',
			'certain_product_help',
			'some_product_help',
		);
		
		if (($this->request->server['REQUEST_METHOD'] == 'POST')) { 	
            if (!$this->user->hasPermission('modify', 'module/giftTeaser')) {
                $this->redirect($this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL'));
            }
			$this->model_module_giftTeaser->saveGift($this->request->post);	
		}
		
		foreach ($languageVariables as $key => $v) {
			$this->data[$v] = $this->language->get($v);
		}
		$this->data['languages'] = $this->model_localisation_language->getLanguages();
		if(isset($this->request->get['gift_id'])){
			$this->data['gift_id'] = $this->request->get['gift_id'];
			$this->data['item_id'] = $this->request->get['item_id'];
			$item = $this->model_module_giftTeaser->getProductsById(array($this->request->get['item_id']));
			$item = $item[0];
			$this->data['item_name'] = $item['name'];
			$this->data['image'] = $this->model_tool_image->resize($item['image'], 50, 50);
			$this->data['gift'] =$this->model_module_giftTeaser->getGift($this->request->get['gift_id']);
			
			$properties = isset($this->data['gift']['condition_properties'])?unserialize($this->data['gift']['condition_properties']):array();
			$this->data['total'] = !empty($properties['total'])?$properties['total']:'';
			$this->data['total_max'] = !empty($properties['total_max'])?$properties['total_max']:'';
			$this->data['some_product_quantity'] = !empty($properties['some_product_quantity'])?$properties['some_product_quantity']:'1';
			$this->data['certain_product_quantity'] = !empty($properties['certain_product_quantity'])?$properties['certain_product_quantity']:'1';
			$this->data['certain'] = !empty($properties['certain'])?$this->model_module_giftTeaser->getProductsById($properties['certain']):array();
			$this->data['some'] = !empty($properties['some'])?$this->model_module_giftTeaser->getProductsById($properties['some']):array();
			$this->data['categories'] = !empty($properties['categories'])?$this->model_module_giftTeaser->getCategoriesById($properties['categories']):array();
		} else {
			$this->data['gift_id'] = '-1';
			$this->data['gift'] = array(); 
		}

		$this->template = 'module/giftTeaser/giftForm.tpl';
        $this->response->setOutput($this->render());
	}
	
	public function saveGift() {
		$this->load->model('module/giftTeaser');
		$this->model_module_giftTeaser->saveGift($this->request->post);	
	}
    
	public function saveCondition(){
		$this->load->model('module/giftTeaser');
		$this->model_module_giftTeaser->saveCondition($this->request->post);
	}	
}

?>