<?php

class ControllerCatalogCategory extends Controller
{
    private $error = array();

    public function index()
    {
        $language = $this->language->load('catalog/category');
        $this->data = array_merge($this->data, $language);

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

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

        $this->getList();
    }


    public function update()
    {
        $language = $this->language->load('catalog/category');
        $this->data = array_merge($this->data, $language);

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

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


        $this->getForm();
    }

    public function getLinkUrl($remove = array())
    {
        $url = '';

        foreach ($remove as $key => $value) {
            unset($this->request->get[$value]);
        }

        $url = '';

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

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

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

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

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

        return $url;

    }

    protected function getList()
    {
        $this->document->addScript(array(
            'view/javascript/page.category.list.js'
        ));

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

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

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

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

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

        $url = $this->getLinkUrl(['page']);

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

        $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'),
            'separator' => false
        );

        $this->data['breadcrumbs'][] = array(
            'text' => $this->language->get('heading_title'),
            'href' => $this->url->link('catalog/category', 'token=' . $this->session->data['token'] . $url, 'SSL'),
            'separator' => ' :: '
        );

        $this->data['categories'] = array();

        $data = array(
            'start' => ($page - 1) * $this->config->get('config_admin_limit'),
            'limit' => $this->config->get('config_admin_limit'),
            'filter_name' => $filter_name,
            'filter_code' => $filter_code,
            'filter_id_futura' => $filter_id_futura,
            'filter_status' => $filter_status,
        );

        $this->data['filter_name'] = $filter_name;
        $this->data['filter_code'] = $filter_code;
        $this->data['filter_id_futura'] = $filter_id_futura;
        $this->data['filter_status'] = $filter_status;

        $category_total = $this->model_catalog_category->getTotalCategories($data);

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

        foreach ($results as $result) {
            $this->data['categories'][] = array(
                'category_id' => $result['category_id'],
                'name' => $result['name'],
                'status' => ($result['status'] ? true : false),
                'sort_order' => $result['sort_order'],
                'prod_maior_idade' => $result['prod_maior_idade'],
                'selected' => isset($this->request->post['selected']) && in_array($result['category_id'], $this->request->post['selected']),
                'href' => $this->url->link('catalog/category/update', 'token=' . $this->session->data['token'] . '&category_id=' . $result['category_id'] . $url, 'SSL')
            );
        }

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

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

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

        $this->data['filter_count'] = count(explode('&', str_replace('&page', '', $url))) - 1;

        $pagination = new Pagination();
        $pagination->total = $category_total;
        $pagination->page = $page;
        $pagination->limit = $this->config->get('config_admin_limit');
        $pagination->text = $this->language->get('text_pagination');
        $pagination->url = $this->url->link('catalog/category', 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');

        $this->data['pagination'] = $pagination->render();

        $this->template = 'catalog/category_list.twig';
        $this->children = array(
            'common/header',
            'common/footer'
        );

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

    protected function getForm()
    {

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

        if (isset($this->error['name'])) {
            $this->data['error_name'] = $this->error['name'];
        } else {
            $this->data['error_name'] = array();
        }

        $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'),
            'separator' => false
        );

        $this->data['breadcrumbs'][] = array(
            'text' => $this->language->get('heading_title'),
            'href' => $this->url->link('catalog/category', 'token=' . $this->session->data['token'] . $this->getLinkUrl(), 'SSL'),
            'separator' => ' :: '
        );


        $this->data['action'] = $this->url->link('catalog/category/update', 'token=' . $this->session->data['token'] . '&category_id=' . $this->request->get['category_id'], 'SSL');

        $this->data['back'] = $this->url->link('catalog/category', 'token=' . $this->session->data['token'] . $this->getLinkUrl(), 'SSL');

        if (isset($this->request->get['category_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
            $category_info = $this->model_catalog_category->getCategory($this->request->get['category_id']);
        }

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

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

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

        if (isset($this->request->post['category_description'])) {
            $this->data['category_description'] = $this->request->post['category_description'];
        } elseif (isset($this->request->get['category_id'])) {
            $this->data['category_description'] = $this->model_catalog_category->getCategoryDescriptions($this->request->get['category_id']);
        } else {
            $this->data['category_description'] = array();
        }

        if (isset($this->request->post['path'])) {
            $this->data['path'] = $this->request->post['path'];
        } elseif (!empty($category_info)) {
            $this->data['path'] = $category_info['path'];
        } else {
            $this->data['path'] = '';
        }

        if (isset($this->request->post['parent_id'])) {
            $this->data['parent_id'] = $this->request->post['parent_id'];
        } elseif (!empty($category_info)) {
            $this->data['parent_id'] = $category_info['parent_id'];
        } else {
            $this->data['parent_id'] = 0;
        }

        if (isset($this->request->post['keyword'])) {
            $this->data['keyword'] = $this->request->post['keyword'];
        } elseif (!empty($category_info)) {
            $this->data['keyword'] = $category_info['keyword'];
        } else {
            $this->data['keyword'] = '';
        }

        if (isset($this->request->post['category_id'])) {
            $this->data['category_id'] = $this->request->post['category_id'];
        } elseif (!empty($category_info)) {
            $this->data['category_id'] = $category_info['category_id'];
        } else {
            $this->data['category_id'] = '';
        }

        if (isset($this->request->post['id_futura'])) {
            $this->data['id_futura'] = $this->request->post['id_futura'];
        } elseif (!empty($category_info)) {
            $this->data['id_futura'] = $category_info['id_futura'];
        } else {
            $this->data['id_futura'] = '';
        }

        if (isset($this->request->post['image'])) {
            $this->data['image'] = $this->request->post['image'];
        } elseif (!empty($category_info)) {
            $this->data['image'] = $category_info['image'];
        } else {
            $this->data['image'] = '';
        }

        $this->load->dmodel('tool/image');
        $this->load->type('tipocomum');

        if (isset($this->request->post['image']) && file_exists(DIR_IMAGE . $this->request->post['image'])) {
            $this->data['thumb'] = $this->dmodel_tool_image->resize($this->request->post['image'], Type_MiniatureMedium::Tp_width, Type_MiniatureMedium::Tp_height);
        } elseif (!empty($category_info) && $category_info['image'] && file_exists(DIR_IMAGE . $category_info['image'])) {
            $this->data['thumb'] = $this->dmodel_tool_image->resize($category_info['image'], Type_MiniatureMedium::Tp_width, Type_MiniatureMedium::Tp_height);
        } else {
            $this->data['thumb'] = $this->dmodel_tool_image->resize('no_image.jpg', Type_MiniatureMedium::Tp_width, Type_MiniatureMedium::Tp_height);
        }

        if (isset($this->request->post['image']) && file_exists(DIR_IMAGE . $this->request->post['image'])) {
            $this->data['image'] = $this->dmodel_tool_image->resize($this->request->post['image'], $this->config->get('config_image_category_width'), $this->config->get('config_image_category_height'));
        } elseif (!empty($category_info) && $category_info['image'] && file_exists(DIR_IMAGE . $category_info['image'])) {
            $this->data['image'] = $this->dmodel_tool_image->resize($category_info['image'], $this->config->get('config_image_category_width'), $this->config->get('config_image_category_height'));
        } else {
            $this->data['image'] = false;
        }

        $this->data['no_image'] = $this->dmodel_tool_image->resize('no_image.jpg', Type_MiniatureMedium::Tp_width, Type_MiniatureMedium::Tp_height);

        if (isset($this->request->post['top'])) {
            $this->data['top'] = $this->request->post['top'];
        } elseif (!empty($category_info)) {
            $this->data['top'] = $category_info['top'];
        } else {
            $this->data['top'] = 0;
        }

        if (isset($this->request->post['column'])) {
            $this->data['column'] = $this->request->post['column'];
        } elseif (!empty($category_info)) {
            $this->data['column'] = $category_info['column'];
        } else {
            $this->data['column'] = 1;
        }

        if (isset($this->request->post['sort_order'])) {
            $this->data['sort_order'] = $this->request->post['sort_order'];
        } elseif (!empty($category_info)) {
            $this->data['sort_order'] = $category_info['sort_order'];
        } else {
            $this->data['sort_order'] = 0;
        }

        if (isset($this->request->post['status'])) {
            $this->data['status'] = $this->request->post['status'];
        } elseif (!empty($category_info)) {
            $this->data['status'] = $category_info['status'];
        } else {
            $this->data['status'] = 1;
        }

        if (isset($this->request->post['prod_maior_idade'])) {
            $this->data['prod_maior_idade'] = $this->request->post['prod_maior_idade'];
        } elseif (!empty($category_info)) {
            $this->data['prod_maior_idade'] = $category_info['prod_maior_idade'];
        } else {
            $this->data['prod_maior_idade'] = '';
        }

        $this->load->dmodel('design/layout');

        $this->data['layouts'] = $this->dmodel_design_layout->getLayouts();

        $this->template = 'catalog/category_form.tpl';
        $this->children = array(
            'common/header',
            'common/footer'
        );

        $this->response->setOutput($this->render('catalog/category_form'));
    }

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

    }

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

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

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

            $results = $this->model_catalog_category->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')),
                );
            }
        }

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