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

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

    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->token = $this->config->get('promotion_token') . '=' . $this->session->data[$this->config->get('promotion_token')];

        $this->extensionLink = $this->url->link($this->config->get('promotion_extensionLink'), $this->token.$this->config->get('promotion_extensionLink_type') , 'SSL');

        if(!$this->config->get($this->config->get('promotion_totalName').'_status')) {
            $order_total_path = 'Eklentiler->Eklentiler->Sipariş Toplamları';
            $this->error['warning'] = 'Kurulumu tamamlamak için  '.$order_total_path.' menüsünden kampanyalar eklentisini kurup durumunu aktif edin.';
        }

        $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($this->config->get('promotion_setting_model_path'));
        $this->moduleSettings = $this->{$this->config->get('promotion_setting_model')};
    }

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

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

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

        if (isset($this->request->get['module_id']) && $this->user->hasPermission('modify', $this->modulePath)) {
            $this->moduleSettings->deleteModule($this->request->get['module_id']);

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

            $this->response->redirect($this->url->link($this->modulePath, $this->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->user->hasPermission('modify', $this->modulePath)) { 

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

            
            $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, $this->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('//scripts.piyersoft.com/ps-panel/promotion/js/promotion.js');
        $this->document->addStyle('//scripts.piyersoft.com/ps-panel/promotion/css/promotion.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->user->hasPermission('modify', $this->modulePath)) { 

            //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->moduleSettings->addModule('promotion', $this->request->post);
            } else {
                $this->moduleSettings->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, $this->token, 'SSL'));
            } else {
                $this->response->redirect($this->url->link($this->modulePath.'/promotion', 'module_id='. $this->request->get['module_id'] .'&'.$this->token, 'SSL'));
            }
        }

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

        if (isset($this->request->get['module_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
            $module_info = $this->moduleSettings->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['option_id'])){
                   $cond['option_data'] =  $this->moduleModel->getOptionNameByID($cond['option_id']);
                   $cond['option_data_values'] =  $this->moduleModel->getOptionValuesNameByID($cond['option_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(isset($cond['product_list']) && !empty($cond['product_list'])){
                    foreach ($cond['product_list'] as $product_key => $value) {
                        $cond['product_list'][$product_key] = array();
                        $cond['product_list'][$product_key] = array(
                            'product_id' => $value,
                            'name' => $this->moduleModel->getProductNameByID($value)
                        );
                    }
                }
                    
            }

            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)
                        );
                    }
                }

                if(isset($cond['manufacturer']) && !empty($cond['manufacturer'])){
                    foreach ($cond['manufacturer'] as $key7 => $value) {
                        $cond['manufacturer'][$key7] = array(
                            'manufacturer_id' => $value,
                            'name' => $this->moduleModel->getManufacNameByID($value)
                        );
                    }
                }

                if(isset($cond['exclude_product_from_manufacturer']) && !empty($cond['exclude_product_from_manufacturer'])){
                    foreach ($cond['exclude_product_from_manufacturer'] as $key6 => $value) {
                        $cond['exclude_product_from_manufacturer'][$key6] = array(
                            'product_id' => $value,
                            'name' => $this->moduleModel->getProductNameByID($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', $this->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, $this->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', $this->token, 'SSL')
            );
        } else {
            $data['breadcrumbs'][] = array(
                'text' => $this->language->get('heading_title').' - '.$module_info['name'],
                'href' => $this->url->link($this->modulePath.'/promotion', $this->token . '&module_id=' . $this->request->get['module_id'], 'SSL')
            );
        }

        //Customer Groups

        $this->load->model('customer/customer_group');
		$data['customer_groups'] = $this->model_customer_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->token;

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

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

        //autocomplete links
        $data['customerAutocomplete']     = html_entity_decode($this->url->link($this->modulePath.'/customerAutocomplete', $this->token, 'SSL'));
        $data['manufacturerAutocomplete'] = html_entity_decode($this->url->link($this->modulePath.'/manufacturerAutocomplete', $this->token, 'SSL'));
        $data['categoryAutocomplete']     = html_entity_decode($this->url->link($this->modulePath.'/categoryAutocomplete', $this->token, 'SSL'));
        $data['productAutocomplete']      = html_entity_decode($this->url->link($this->modulePath.'/productAutocomplete', $this->token, 'SSL'));
        $data['productOptionAutocomplete']= html_entity_decode($this->url->link($this->modulePath.'/productOptionAutocomplete', $this->token, 'SSL'));

		$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));

        if(file_exists(DIR_LOCAL_TEMPLATE .'extension/module/promotion.tpl')){
            $this->response->setOutput($this->load->view( DIR_LOCAL_TEMPLATE .'extension/module/promotion', $data));
        }else{
            $this->response->setOutput($this->load->view(DIR_TEMPLATE . 'extension/module/promotion', $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'] .'&'.$this->token, 'SSL'));
        }

        $this->document->addStyle('//scripts.piyersoft.com/ps-panel/promotion/css/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', $this->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, $this->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', $this->token, 'SSL');
        $data['addnew']                 = $this->url->link($this->modulePath.'/promotion', $this->token, 'SSL');
        $data['cancel']                 = $this->extensionLink;

        //autocomplete links
        $data['customerAutocomplete']     = html_entity_decode($this->url->link($this->modulePath.'/customerAutocomplete', $this->token, 'SSL'));
        $data['manufacturerAutocomplete'] = html_entity_decode($this->url->link($this->modulePath.'/manufacturerAutocomplete', $this->token, 'SSL'));
        $data['categoryAutocomplete']     = html_entity_decode($this->url->link($this->modulePath.'/categoryAutocomplete', $this->token, 'SSL'));
        $data['productAutocomplete']      = html_entity_decode($this->url->link($this->modulePath.'/productAutocomplete', $this->token, 'SSL'));
        $data['productOptionAutocomplete']= html_entity_decode($this->url->link($this->modulePath.'/productOptionAutocomplete', $this->token, 'SSL'));

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

        $data['token']                  = $this->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));
        if(file_exists(DIR_LOCAL_TEMPLATE .'extension/module/promotion_stats.tpl')){
            $this->response->setOutput($this->load->view( DIR_LOCAL_TEMPLATE .'extension/module/promotion_stats', $data));
        }else{
            $this->response->setOutput($this->load->view(DIR_TEMPLATE . 'extension/module/promotion_stats', $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();
    }

    //Autocompletes
    public function customerAutocomplete() {
        $json = array();

        if (isset($this->request->get['filter_name']) || isset($this->request->get['filter_email'])) {
            if (isset($this->request->get['filter_name'])) {
                $filter_name = $this->request->get['filter_name'];
            } else {
                $filter_name = '';
            }

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

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

            $filter_data = array(
                'filter_name'  => $filter_name,
                'filter_email' => $filter_email,
                'start'        => 0,
                'limit'        => 5
            );

            $results = $this->model_customer_customer->getCustomers($filter_data);

            foreach ($results as $result) {
                $json[] = array(
                    'customer_id'       => $result['customer_id'],
                    'customer_group_id' => $result['customer_group_id'],
                    'name'              => strip_tags(html_entity_decode($result['name'], ENT_QUOTES, 'UTF-8')),
                    'customer_group'    => $result['customer_group'],
                    'firstname'         => $result['firstname'],
                    'lastname'          => $result['lastname'],
                    'email'             => $result['email'],
                    'telephone'         => $result['telephone'],
                    'fax'               => $result['fax'],
                    'custom_field'      => json_decode($result['custom_field'], true),
                    'address'           => $this->model_customer_customer->getAddresses($result['customer_id'])
                );
            }
        }

        $sort_order = array();

        foreach ($json as $key => $value) {
            $sort_order[$key] = $value['name'];
        }

        array_multisort($sort_order, SORT_ASC, $json);

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

    public function manufacturerAutocomplete() {
        $json = array();

        if (isset($this->request->get['filter_name'])) {
            $this->load->model('catalog/manufacturer');

            $filter_data = array(
                'filter_name' => $this->request->get['filter_name'],
                'start'       => 0,
                'limit'       => 5
            );

            $results = $this->model_catalog_manufacturer->getManufacturers($filter_data);

            foreach ($results as $result) {
                $json[] = array(
                    'manufacturer_id' => $result['manufacturer_id'],
                    'name'            => strip_tags(html_entity_decode($result['name'], ENT_QUOTES, 'UTF-8'))
                );
            }
        }

        $sort_order = array();

        foreach ($json as $key => $value) {
            $sort_order[$key] = $value['name'];
        }

        array_multisort($sort_order, SORT_ASC, $json);

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

    public function productAutocomplete() {
        $json = array();

        if (isset($this->request->get['filter_name']) || isset($this->request->get['filter_model'])) {
            $this->load->model('catalog/product');
            $this->load->model('catalog/option');

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

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

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

            $filter_data = array(
                'filter_name'  => $filter_name,
                'filter_model' => $filter_model,
                'start'        => 0,
                'limit'        => $limit
            );

            $results = $this->model_catalog_product->getProducts($filter_data);

            foreach ($results as $result) {
                $option_data = array();

                $product_options = $this->model_catalog_product->getProductOptions($result['product_id']);

                foreach ($product_options as $product_option) {
                    $option_info = $this->model_catalog_option->getOption($product_option['option_id']);

                    if ($option_info) {
                        $product_option_value_data = array();

                        foreach ($product_option['product_option_value'] as $product_option_value) {
                            $option_value_info = $this->model_catalog_option->getOptionValue($product_option_value['option_value_id']);

                            if ($option_value_info) {
                                $product_option_value_data[] = array(
                                    'product_option_value_id' => $product_option_value['product_option_value_id'],
                                    'option_value_id'         => $product_option_value['option_value_id'],
                                    'name'                    => $option_value_info['name'],
                                    'price'                   => (float)$product_option_value['price'] ? $this->currency->format($product_option_value['price'], $this->config->get('config_currency')) : false,
                                    'price_prefix'            => $product_option_value['price_prefix']
                                );
                            }
                        }

                        $option_data[] = array(
                            'product_option_id'    => $product_option['product_option_id'],
                            'product_option_value' => $product_option_value_data,
                            'option_id'            => $product_option['option_id'],
                            'name'                 => $option_info['name'],
                            'type'                 => $option_info['type'],
                            'value'                => $product_option['value'],
                            'required'             => $product_option['required']
                        );
                    }
                }

                $json[] = array(
                    'product_id' => $result['product_id'],
                    'name'       => strip_tags(html_entity_decode($result['name'], ENT_QUOTES, 'UTF-8')),
                    'model'      => $result['model'],
                    'option'     => $option_data,
                    'price'      => $result['price']
                );
            }
        }

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

    public function categoryAutocomplete() {
        $json = array();

        if (isset($this->request->get['filter_name'])) {
            $this->load->model('catalog/category');

            $filter_data = array(
                'filter_name' => $this->request->get['filter_name'],
                'sort'        => 'name',
                'order'       => 'ASC',
                'start'       => 0,
                'limit'       => 5
            );

            $results = $this->model_catalog_category->getCategories($filter_data);

            foreach ($results as $result) {
                $json[] = array(
                    'category_id' => $result['category_id'],
                    'name'        => strip_tags(html_entity_decode($result['name'], ENT_QUOTES, 'UTF-8'))
                );
            }
        }

        $sort_order = array();

        foreach ($json as $key => $value) {
            $sort_order[$key] = $value['name'];
        }

        array_multisort($sort_order, SORT_ASC, $json);

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

    public function productOptionAutocomplete() {
        $json = array();

        if (isset($this->request->get['filter_name'])) {
            $this->load->model('catalog/option');

            $filter_data = array(
                'filter_name' => $this->request->get['filter_name'],
                'sort'        => 'name',
                'order'       => 'ASC',
                'start'       => 0,
                'limit'       => 5
            );

            $results = $this->model_catalog_option->getOptions($filter_data);

            foreach ($results as $result) {

                $option_values = $this->model_catalog_option->getOptionValues($result['option_id']);

                $json[] = array(
                    'option_id' => $result['option_id'],
                    'name'        => strip_tags(html_entity_decode($result['name'], ENT_QUOTES, 'UTF-8')),
                    'option_values' => json_encode($option_values, true)
                );
            }
        }

        $sort_order = array();

        foreach ($json as $key => $value) {
            $sort_order[$key] = $value['name'];
        }

        array_multisort($sort_order, SORT_ASC, $json);

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

}
