<?php
class ControllerModulePromotions extends Controller
{
    private $data   = array();
    private $module = array();
    private $error  = array();

    public function __construct($registry)
    {
        parent::__construct($registry);

        $this->config->load('isenselabs/promotions');
        $this->module = $this->config->get('promotions');

        $this->load->model('setting/setting');
        $this->load->model($this->module['path']);

        $this->module['model'] = $this->{$this->module['model']};
        $this->module['url_token'] = sprintf($this->module['url_token'], $this->session->data['token']);

        if (isset($this->request->post['store_id'])) {
            $this->module['store_id'] = (int)$this->request->post['store_id'];
        } elseif (isset($this->request->get['store_id'])) {
            $this->module['store_id'] = (int)$this->request->get['store_id'];
        }

        $this->module['promo_id'] = 0;
        if (isset($this->request->get['promo_id'])) {
            $this->module['promo_id'] = (int)$this->request->get['promo_id'];
        }
        $this->module['url_module'] = $this->url->link($this->module['path'], 'store_id=' . $this->module['store_id'] . '&' . $this->module['url_token'], true);
        $this->module['url_module_form'] = $this->url->link($this->module['path'] . '/form', 'store_id=' . $this->module['store_id'] . '&' . $this->module['url_token'], true);

        // Module setting
        $setting = $this->model_setting_setting->getSetting($this->module['code'], $this->module['store_id']);
        $this->module['setting'] = array_replace_recursive(
            $this->module['setting'],
            !empty($setting[$this->module['code'] . '_setting']) ? $setting[$this->module['code'] . '_setting'] : array()
        );

        // Language variables
        $this->data = $this->load->language($this->module['path'], $this->module['name']);
    }

    // Standarize index() and form()
    private function initPage($data)
    {
        $this->load->model('setting/store');
        $this->load->model('localisation/language');
        $this->load->model('tool/image');

        $this->document->setTitle($this->module['title']);

        $this->document->addStyle('view/javascript/summernote/summernote.css');
        $this->document->addStyle('view/stylesheet/' . $this->module['code'] . '.css?v=' .  $this->module['version']);
        $this->document->addScript('view/javascript/summernote/summernote.min.js');
        $this->document->addScript('view/javascript/' . $this->module['code'] . '.js?v=' .  $this->module['version']);

        if (!$this->config->get($this->module['total_code'] . '_status')) {
            $order_total_path = version_compare(VERSION, '2.3.0.0', '<') ? '<strong>Extensions > Order Totals</strong>' : '<strong>Extensions > Extensions > Order Totals</strong>';
            $this->error['warning'] = 'Please go to ' . $order_total_path . ' and enable Promotions order total';
        }

        // ===

        $data['heading_title']    = $this->module['title'] . ' ' . $this->module['version'];

        $data['setting']          = $this->module['setting'];
        $data['store_id']         = $this->module['store_id'];
        $data['promo_id']         = $this->module['promo_id'];
        $data['url_token']        = $this->module['url_token'];
        $data['link_ext']         = $this->url->link($this->module['ext_link'], $this->module['url_token'] . $this->module['ext_type'], true);
        $data['link_module']      = $this->module['url_module'];
        $data['link_module_form'] = $this->module['url_module_form'];
        $data['module']           = array(
            'name'  => $this->module['name'],
            'path'  => $this->module['path']
        );

        $data['breadcrumbs']   = array();
        $data['breadcrumbs'][] = array(
            'text'      => $this->language->get('text_home'),
            'href'      => $this->url->link('common/dashboard', $this->module['url_token'], true)
        );
        $data['breadcrumbs'][] = array(
            'text'      => $data['text_modules'],
            'href'      => $data['link_ext']
        );
        $data['breadcrumbs'][] = array(
            'text'      => $data['text_promotions'],
            'href'      => $data['link_module']
        );

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

        // ===

        $page_url = $this->module['url_module_form'] . '&promo_id=' . $this->module['promo_id'];
        $data['text_promo_rule_alert'] = sprintf($data['text_promo_rule_alert'], $page_url . '#_notification');

        // ===

        $store_default = array(
            'store_id' => '0',
            'name'     => $this->config->get('config_name') . ' <b>(' .$this->language->get('text_default') . ')</b>',
            'url'      => HTTPS_CATALOG
        );
        $data['store']  = $this->module['store_id'] != 0 ? $this->model_setting_store->getStore($this->module['store_id']) : $store_default;
        $data['stores'] = array_merge(
            array(0 => $store_default),
            $this->model_setting_store->getStores()
        );

        $data['languages'] = $this->model_localisation_language->getLanguages();
        foreach ($data['languages'] as $key => $value) {
            $data['languages'][$key]['flag_url'] = 'view/image/flags/'.$data['languages'][$key]['image'];
        }

        $data['no_image'] = $this->model_tool_image->resize('no_image.png', 100, 100);
        $data['jsData']   = $data;

        return $data;
    }

    // Main module form
    public function index()
    {
        $this->setup();

        if ($this->request->server['REQUEST_METHOD'] == 'POST' && $this->validateForm()) {
            $module_status = $this->request->post[$this->module['code'] . '_setting']['status'];

            if (!empty($_POST['OaXRyb1BhY2sgLSBDb21'])) {
                $this->request->post[$this->module['code'] . '_setting']['LicensedOn'] = $_POST['OaXRyb1BhY2sgLSBDb21'];
            }
            if (!empty($_POST['cHRpbWl6YXRpb24ef4fe'])) {
                $this->request->post[$this->module['code'] . '_setting']['License'] = json_decode(base64_decode($_POST['cHRpbWl6YXRpb24ef4fe']), true);
            }

            $post = array_replace_recursive(
                $this->request->post,
                array($this->module['code'] . '_status' => $module_status)
            );

            $this->model_setting_setting->editSetting($this->module['code'], $post, $this->module['store_id']);

            $this->session->data['success'] = $this->data['text_success'];
            $this->response->redirect($this->module['url_module']);
        }

        $data = $this->initPage($this->data);

        $data['link_form']         = $data['link_module'];
        $data['link_cancel']       = $data['link_ext'];
        $data['link_item_list']    = $this->url->link($this->module['path'] . '/itemList', 'store_id=' . $this->module['store_id'] . '&' . $this->module['url_token'], true);
        $data['module_setting']    = $this->module['code'] . '_setting';

        $data['setting']['page']['banner_thumb'] = $data['no_image'];
        if ($data['setting']['page']['banner'] && is_file(DIR_IMAGE . $data['setting']['page']['banner'])) {
            $data['setting']['page']['banner_thumb'] = $this->model_tool_image->resize($data['setting']['page']['banner'], 100, 100);
        }

        // Support
        $data['unlincensedHtml']   = empty($this->module['setting']['LicensedOn']) ? base64_decode('ICAgIDxkaXYgY2xhc3M9ImFsZXJ0IGFsZXJ0LWRhbmdlciBmYWRlIGluIj4NCiAgICAgICAgPGJ1dHRvbiB0eXBlPSJidXR0b24iIGNsYXNzPSJjbG9zZSIgZGF0YS1kaXNtaXNzPSJhbGVydCIgYXJpYS1oaWRkZW49InRydWUiPsOXPC9idXR0b24+DQogICAgICAgIDxoND5XYXJuaW5nISBVbmxpY2Vuc2VkIHZlcnNpb24gb2YgdGhlIG1vZHVsZSE8L2g0Pg0KICAgICAgICA8cD5Zb3UgYXJlIHJ1bm5pbmcgYW4gdW5saWNlbnNlZCB2ZXJzaW9uIG9mIHRoaXMgbW9kdWxlISBZb3UgbmVlZCB0byBlbnRlciB5b3VyIGxpY2Vuc2UgY29kZSB0byBlbnN1cmUgcHJvcGVyIGZ1bmN0aW9uaW5nLCBhY2Nlc3MgdG8gc3VwcG9ydCBhbmQgdXBkYXRlcy48L3A+PGRpdiBzdHlsZT0iaGVpZ2h0OjVweDsiPjwvZGl2Pg0KICAgICAgICA8YSBjbGFzcz0iYnRuIGJ0bi1kYW5nZXIiIGhyZWY9ImphdmFzY3JpcHQ6dm9pZCgwKSIgb25jbGljaz0iJCgnYVtocmVmPSNpc2Vuc2Vfc3VwcG9ydF0nKS50cmlnZ2VyKCdjbGljaycpIj5FbnRlciB5b3VyIGxpY2Vuc2UgY29kZTwvYT4NCiAgICA8L2Rpdj4=') : '';
        $data['licenseDataBase64'] = !empty($this->module['setting']['License']) ? base64_encode(json_encode($this->module['setting']['License'])) : '';
        $data['supportTicketLink'] = 'http://isenselabs.com/tickets/open/' . base64_encode('Support Request').'/'.base64_encode('414').'/'. base64_encode($_SERVER['SERVER_NAME']);

        // Content
        $data['tab_list']          = $this->load->view($this->module['path'] .'/tab_list.tpl', $data);
        $data['tab_module']        = $this->load->view($this->module['path'] .'/tab_module.tpl', $data);
        $data['tab_page']          = $this->load->view($this->module['path'] .'/tab_page.tpl', $data);
        $data['tab_setting']       = $this->load->view($this->module['path'] .'/tab_setting.tpl', $data);
        $data['tab_support']       = $this->load->view($this->module['path'] .'/tab_support.tpl', $data);

        // Page element
        $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->module['path'] . '.tpl', $data));
    }

    // Tab manage: get list
    public function itemlist()
    {
        $data   = array();
        $reqGet = $this->request->get;
        $limit  = 25;
        $page   = isset($reqGet['page']) && (int)$reqGet['page'] > 0 ? (int)$reqGet['page'] : 1;

        $data['link_item_update'] = $this->url->link($this->module['path'] . '/itemUpdate', 'store_id=' . $this->module['store_id'] . '&' . $this->module['url_token'], true);
        $data['link_item_edit']   = $this->url->link($this->module['path'] . '/form', 'store_id=' . $this->module['store_id'] . '&' . $this->module['url_token'], true);
        $data['language_id']      = $this->config->get('config_language_id');

        $params = array(
            'page'  => $page,
            'limit' => $limit,
            'start' => ($page - 1) * $limit,
        );

        $data['items']      = $this->module['model']->getItems($params);
        $total_item         = $this->module['model']->getTotalItems($params);

        $pagination         = new Pagination();
        $pagination->total  = $total_item;
        $pagination->page   = $page;
        $pagination->limit  = $limit;
        $pagination->url    = $this->url->link($this->module['path'] . '/itemList', 'store_id=' . $this->module['store_id'] . '&' . $this->module['url_token'] . '&page={page}', true);

        $data['output']     = $this->load->view($this->module['path'] . '/promo_list.tpl', $data);
        $data['pagination'] = $pagination->render();
        $data['pagination_info'] = sprintf($this->language->get('text_pagination'), ($total_item) ? (($page - 1) * $limit) + 1 : 0, ((($page - 1) * $limit) > ($total_item - $limit)) ? $total_item : ((($page - 1) * $limit) + $limit), $total_item, ceil($total_item / $limit));


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

    // Tab manage: update promotion item in tab Manage
    public function itemUpdate()
    {
        $data = array();
        $post = $this->request->post;

        // Priority order
        if (!empty($post['priority_order'])) {
            foreach ($post['priority_order'] as $key => $value) {
                $this->db->query("UPDATE `" . DB_PREFIX . "promotions_item` SET `priority` = '" . (int)$value . "' WHERE `promotion_id` = '" . (int)$key . "'");
            }
        }

        // Update stop n status
        if (!empty($post['action']) && in_array($post['action'], array('stop', 'status'))) {
            $this->db->query("UPDATE `" . DB_PREFIX . "promotions_item` SET `" . $post['action'] . "` = '" . (int)$post['value'] . "' WHERE `promotion_id` = '" . (int)$post['id'] . "'");
        }

        // Delete
        if (!empty($post['action']) && $post['action'] == 'delete') {
            $this->db->query("DELETE FROM `" . DB_PREFIX . "promotions_item` WHERE `promotion_id` = '" . (int)$post['id'] . "'");
        }

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

    // ====================================

    // Promotion item form
    public function form()
    {
        if ($this->request->server['REQUEST_METHOD'] == 'POST' && !empty($this->request->post[$this->module['code'] . '_item']) && $this->validateFormItem()) {
            $post = $this->request->post[$this->module['code'] . '_item'];

            if ($this->module['promo_id']) {
                $this->module['model']->update($this->module['promo_id'], $post);
            } else {
                $this->module['model']->insert($post);
            }

            $this->session->data['success'] = $this->data['text_success'];
            $this->response->redirect($this->module['url_module']);
        }

        $data = $this->initPage($this->data);

        $data['breadcrumbs'][]  = array(
            'text' => $this->module['promo_id'] ? $data['text_edit_promo'] . ' #' . $this->module['promo_id'] : $data['text_add_promo'],
            'href' => $this->module['url_module_form'] . '&promo_id=' . $this->module['promo_id']
        );

        $data['link_form']      = $data['link_module_form'] . '&promo_id=' . $this->module['promo_id'];
        $data['link_cancel']    = $data['link_module'];
        $data['module_setting'] = $this->module['code'] . '_item';

        $data['sub_title']      = $this->module['promo_id'] ? $data['text_edit_promo'] . ' #' . $this->module['promo_id'] : $data['text_add_promo'];
        $data['currency']       = $this->config->get('config_currency');

        if (version_compare(VERSION, '2.1.0.0', '<')) { // 2.0
            $this->load->model('sale/customer_group');
            $this->isl_model_customer_group = $this->model_sale_customer_group;
        } else {
            $this->load->model('customer/customer_group');
            $this->isl_model_customer_group = $this->model_customer_customer_group;
        }
        $data['default_cust_group'] = $this->config->get('config_customer_group_id');
        $data['customer_groups']    = $this->isl_model_customer_group->getCustomerGroups();

        if (isset($this->request->post[$this->module['code'] . '_item'])) {
            $data['setting']['item'] = array_replace_recursive($data['setting']['item'], $this->request->post[$this->module['code'] . '_item']);
        } elseif ($this->module['promo_id']) {
            $data['setting']['item'] = array_replace_recursive($data['setting']['item'], $this->module['model']->getItem($this->module['promo_id']));
        }
        $this->session->data['promotions_item'] = $data['setting']['item'];

        $data['customer_ids'] = array();
        if ($data['setting']['item']['customer_ids']) {
            $data['customer_ids'] = $this->module['model']->getCustomersInId($data['setting']['item']['customer_ids']);
        }
        $data['setting']['item']['design_module_banner_thumb'] = $data['no_image'];
        if ($data['setting']['item']['design_module_banner'] && is_file(DIR_IMAGE . $data['setting']['item']['design_module_banner'])) {
            $data['setting']['item']['design_module_banner_thumb'] = $this->model_tool_image->resize($data['setting']['item']['design_module_banner'], 100, 100);
        }

        $data['setting']['item']['design_page_banner_thumb'] = $data['no_image'];
        if ($data['setting']['item']['design_page_banner'] && is_file(DIR_IMAGE . $data['setting']['item']['design_page_banner'])) {
            $data['setting']['item']['design_page_banner_thumb'] = $this->model_tool_image->resize($data['setting']['item']['design_page_banner'], 100, 100);
        }

        $data['jsData']   = $data;

        // Page element
        $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->module['path'] . '/form.tpl', $data));
    }

    // Load promotion rule form
    public function ruleForm()
    {
        $data   = array();
        $output = '';

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

            $data['module_setting']   = $this->module['code'] . '_item';
            $data['currency']         = $this->config->get('config_currency');
            $data['geo_zones']        = $this->model_localisation_geo_zone->getGeoZones();
            $data['manufacturers']    = $this->model_catalog_manufacturer->getManufacturers();
            $data['link_module']      = $this->module['url_module'];
            $data['link_module_form'] = $this->module['url_module_form'];

            $data['discount_product_ids_data']       = array();
            $data['condition_product_ids_data']      = array();
            $data['discount_category_ids_data']      = array();
            $data['condition_category_ids_data']     = array();
            $data['condition_manufacturer_ids_data'] = array();
            $data['condition_min_quantities_data']   = array();
            $data['condition_min_amounts_data']      = array();

            $data['setting'] = $this->module['setting'];
            if ($this->module['promo_id'] || isset($this->session->data['promotions_item'])) {
                $item = $this->module['model']->getItem($this->module['promo_id']);

                if (!$item) {
                    $item = $this->session->data['promotions_item'];
                }

                if ($this->request->get['promo_rule'] == $item['rule_group'] . '_' . $item['rule_type']) {
                    $data['setting']['item'] = $item;

                    if ($item['discount_product_ids']) {
                        $data['discount_product_ids_data'] = $this->module['model']->getProductsInId($item['discount_product_ids']);
                    }
                    if ($item['condition_product_ids']) {
                        $data['condition_product_ids_data'] = $this->module['model']->getProductsInId($item['condition_product_ids']);
                    }
                    if ($item['discount_category_ids']) {
                        $data['discount_category_ids_data'] = $this->module['model']->getCategoriesInId($item['discount_category_ids']);
                    }
                    if ($item['condition_category_ids']) {
                        $data['condition_category_ids_data'] = $this->module['model']->getCategoriesInId($item['condition_category_ids']);
                    }
                    if ($item['condition_manufacturer_ids']) {
                        $data['condition_manufacturer_ids_data'] = $this->module['model']->getManufacturerInId($item['condition_manufacturer_ids']);
                    }
                    if ($item['condition_min_quantities'] && $item['discount_values']) {
                        foreach ($item['condition_min_quantities'] as $key => $value) {
                            $data['condition_min_quantities_data'][$key] = array(
                                'quantity' => $value,
                                'discount' => isset($item['discount_values'][$key]) ? $item['discount_values'][$key] : '',
                            );
                        }
                    }
                    if ($item['condition_min_amounts'] && $item['discount_values']) {
                        foreach ($item['condition_min_amounts'] as $key => $value) {
                            $data['condition_min_amounts_data'][$key] = array(
                                'amount' => $value,
                                'discount' => isset($item['discount_values'][$key]) ? $item['discount_values'][$key] : '',
                            );
                        }
                    }
                }
            }

            $output = $this->load->view($this->module['path'] . '/rule/' . $this->request->get['promo_rule'] . '.tpl', $data);
        }

        $this->response->setOutput($output);
    }

    public function notificationEditor()
    {
        $this->load->model('localisation/language');

        $data                    = $this->data;
        $data['setting']         = $this->module['setting'];

        $item = $this->module['model']->getItem($this->module['promo_id']);
        if (!$item) {
            $item = $this->session->data['promotions_item'];
        }
        $data['setting']['item'] = $item;

        $data['module_setting']  = $this->module['code'] . '_item';
        $data['promo_type']      = !empty($this->request->get['promo_type']) ? $this->request->get['promo_type'] : '';
        $data['promo_reset']     = !empty($this->request->get['reset']) ? $this->request->get['reset'] : 0;
        $data['languages']       = $this->model_localisation_language->getLanguages();

        // Auto change notification editor content when promo rule change
        if ($data['promo_type'] !== $data['setting']['item']['rule_type']) {
            $data['promo_reset'] = 1;
        }

        foreach ($data['languages'] as $key => $value) {
            $data['languages'][$key]['flag_url'] = 'view/image/flags/'.$data['languages'][$key]['image'];
        }

        $this->response->setOutput($this->load->view($this->module['path'] . '/form_notification_editor.tpl', $data));
    }

    private function validateForm()
    {
        if (!$this->user->hasPermission('modify', $this->module['path'])) {
            $this->error['warning'] = $this->data['error_permission'];
        }

        return !$this->error;
    }

    private function validateFormItem()
    {
        if (!$this->user->hasPermission('modify', $this->module['path'])) {
            $this->error['warning'] = $this->data['error_permission'];

            return !$this->error;
        }

        $post = $this->request->post[$this->module['code'] . '_item'];

        foreach ($post['title'] as $title) {
            if ((utf8_strlen($title) < 3) || (utf8_strlen($title) > 225)) {
                $this->error['item']['title'] = $this->language->get('error_title');
            }
        }

        if (empty($post['rule_group']) || empty($post['rule_type'])) {
            $this->error['item']['promo_rule'] = $this->language->get('error_select_promo');
        }

        if (!empty($post['design_status']) && empty($post['design_module_banner'])) {
            $this->error['item']['banner_module'] = $this->language->get('error_banner_module');
        }

        if (!empty($this->error['item'])) {
            $message = $this->language->get('error_form');
            $message .= '<ul>';
            foreach ($this->error['item'] as $error) {
                $message .= '<li>' . $error . '</li>';
            }
            $message .= '</ul>';

            $this->error['warning'] = $message;
        }

        return !$this->error;
    }

    /**
     * Future update
     */
    public function setup()
    {
        $this->module['model']->setup();
    }

    /**
     * Installation through Extension Installer
     */
    public function install()
    {
        $this->module['model']->install(true);
    }

    public function uninstall()
    {
        $this->module['model']->uninstall();
    }
}
