<?php
loadcontroller('base/module');

class ControllerModuleCustomLinks extends ControllerBaseModule
{
    protected $referencePathFile = 'module/custom_links';

    protected function actionUrls()
    {
        parent::actionUrls();

        $type = $this->request->get['type'];

        $this->dataVue['delete'] = $this->url->link(
            "$this->referencePathFile/delete",
            'token=' . $this->token . '&type=' . $type,
            'SSL'
        );
    }

    public function loadData()
    {
        parent::loadData();

        $this->dataVue['configurations']['customLinks'] = $this->getList();

        $this->dataVue['tabs'] = TypeCustomLinks::getTabs();

        $this->dataVue['TypesForJs'] = array(
            TypeCustomLinks::getTypeForJs(),
        );
    }

    public function save()
    {
        parent::loadLanguage();
        parent::loadModel();

        if (!$this->user->hasPermission('modify', $this->referencePathFile)) {
            $this->errors['warning'] = $this->language->get('error_permission');
            $this->responseJson['errors'] = $this->errors;
            return $this->response->setOutputJson($this->responseJson);
        }

        $this->errors = $this->validate();

        if ($this->errors) {
            $this->responseJson['errors'] = $this->errors;
            return $this->response->setOutputJson($this->responseJson);
        }

        $customLinks = $this->request->post['customLinks'];
        $customLinksId = $this->dmodel_module_custom_links->getListId();

        foreach ($customLinks as $linksIndex => $linksItem) {
            if (empty($linksItem['parent'])) {
                if (in_array($linksItem['custom_links_id'], $customLinksId)) {
                    $lastCustomLinksId = $this->dmodel_module_custom_links->edit(
                        $linksItem['custom_links_id'],
                        $customLinks[$linksIndex]
                    );
                } else {
                    $lastCustomLinksId = $this->dmodel_module_custom_links->add($customLinks[$linksIndex]);
                }
            }

            foreach ($customLinks as $subLinksIndex => $subLinksItem) {
                if ($linksItem['custom_links_id'] === $subLinksItem['parent']) {
                    $customLinks[$subLinksIndex]['parent'] = $lastCustomLinksId;
                    if (in_array($subLinksItem['custom_links_id'], $customLinksId)) {
                        $this->dmodel_module_custom_links->edit(
                            $subLinksItem['custom_links_id'],
                            $customLinks[$subLinksIndex]
                        );
                    } else {
                        $this->dmodel_module_custom_links->add($customLinks[$subLinksIndex]);
                    }
                }
            }
        }

        $this->responseJson['success'] = $this->language->get('text_success');
        $this->responseJson['customLinks'] = $this->getList();

        return $this->response->setOutputJson($this->responseJson);
    }

    public function delete()
    {
        parent::loadModel();

        $customLinksId = explode(',', $this->request->get['id']);
        foreach ($customLinksId as $customLinksIdIndex => $customLinksIdValue) {
            $this->dmodel_module_custom_links->delete($customLinksIdValue);
        }
    }

    protected function validate()
    {
        $errors = [];
        $customLinks = $this->request->post['customLinks'];

        foreach ($customLinks as $customLinksIndex => $customLinksItem) {
            $customLinksErrors = $this->validate->execute([
                'text_' .  $customLinksItem['custom_links_id'] => [
                    'value' => $customLinksItem['text'],
                    'validates' => ['isEmpty'],
                ],
                'link_' .  $customLinksItem['custom_links_id'] => [
                    'value' => $customLinksItem['link'],
                    'validates' => ['isEmpty', 'isUrl'],
                ],
            ]);

            if ($customLinksErrors) {
                $errors = array_merge($errors, $customLinksErrors);
            }
        }

        return $errors;
    }

    protected function getList()
    {
        parent::loadModel();
        $this->load->dmodel('tool/image');

        $customLinks = $this->dmodel_module_custom_links->getList();
        foreach ($customLinks as $customLinksIndex => &$customLinksItem) {
            if (preg_match("/\./", $customLinksItem['icon'])) {
                $customLinksItem['iconPreview'] = $this->dmodel_tool_image->resize(
                    "data/{$customLinksItem['icon']}",
                    Type_MiniatureSmall::Tp_width,
                    Type_MiniatureSmall::Tp_height
                );

                $customLinksItem['iconPreview'] = isset($customLinksItem['iconPreview'])? $customLinksItem['iconPreview'] : '';

            } else {
                $customLinksItem['iconPreview'] = isset($customLinksItem['icon'])?$customLinksItem['icon'] : '';
            }
        }

        return $customLinks;
    }
}
