1<?php
2/**
3 * Copyright (C) 2019 thirty bees
4 *
5 * NOTICE OF LICENSE
6 *
7 * This source file is subject to the Academic Free License (AFL 3.0)
8 * that is bundled with this package in the file LICENSE.md.
9 * It is also available through the world-wide-web at this URL:
10 * https://opensource.org/licenses/afl-3.0.php
11 * If you did not receive a copy of the license and are unable to
12 * obtain it through the world-wide-web, please send an email
13 * to license@thirtybees.com so we can send you a copy immediately.
14 *
15 * @author    thirty bees <modules@thirtybees.com>
16 * @copyright 2019 thirty bees
17 * @license   Academic Free License (AFL 3.0)
18 */
19
20if ( ! defined('_TB_VERSION_')) {
21    exit;
22}
23
24class AdminHTMLBlockController extends ModuleAdminController
25{
26    public function __construct()
27    {
28        $this->bootstrap = true;
29        $this->show_toolbar = true;
30        $this->identifier = 'id_block';
31        $this->table = 'tbhtmlblock';
32
33        parent::__construct();
34    }
35
36    public function initPageHeaderToolbar()
37    {
38        if (empty($this->display) || $this->display =='list') {
39            $this->page_header_toolbar_btn['new_block'] = [
40                'href' => static::$currentIndex.'&addtbhtmlblock&token='.$this->token,
41                'desc' => $this->l('Add new block', null, null, false),
42                'icon' => 'process-icon-new',
43            ];
44        }
45
46        parent::initPageHeaderToolbar();
47    }
48
49    public function renderList()
50    {
51        $blocks = $this->module->getAllBlocks();
52        $content = '';
53
54        if ($blocks) {
55            foreach ($blocks as $block) {
56                $fieldsList = [
57                    'id_block'  => [
58                        'title'   => 'ID',
59                        'align'   => 'center',
60                        'class'   => 'fixed-width-xs',
61                    ],
62                    'name'      => [
63                        'title'   => $this->l('Name'),
64                    ],
65                    'active'    => [
66                        'title'   => $this->l('Status'),
67                        'active'  => 'status',
68                        'type'    => 'bool',
69                    ],
70                    'position'  => [
71                        'title'     => $this->l('Position'),
72                        'position'  => 'position',
73                    ],
74                ];
75
76                $helper = new HelperList();
77                $helper->shopLinkType = '';
78                $helper->simple_header = true;
79                $helper->actions = ["edit", "delete"];
80                $helper->show_toolbar = false;
81                $helper->module = $this;
82                $helper->listTotal = count($blocks);
83                $helper->identifier = 'id_block';
84                $helper->position_identifier = 'position';
85                $helper->title = $block['name'];
86                $helper->orderBy = 'position';
87                $helper->orderWay = 'ASC';
88                $helper->table = $this->table;
89                $helper->token = Tools::getAdminTokenLite('AdminHTMLBlock');
90                $helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
91
92                $content .= $helper->generateList($block['blocks'], $fieldsList);
93            }
94        }
95
96        return $content;
97    }
98
99
100    public function renderForm()
101    {
102        $inputs[] = [
103            'type'  => 'text',
104            'label' => $this->l('Block Name (For your eyes only)'),
105            'name'  => 'name',
106        ];
107        $inputs[] = [
108            'type'  => 'textarea',
109            'label' => $this->l('Content'),
110            'name'  => 'content',
111            'lang'  => true,
112            'autoload_rte' => true,
113        ];
114        $inputs[] = [
115            'type'  => 'select',
116            'label' => $this->l('Hook'),
117            'name'  => 'hook_name',
118            'options' => [
119                    'query' => $this->module->getHooksWithNames(),
120                    'id'    => 'name',
121                    'name'  => 'title',
122                ],
123        ];
124        $inputs[] = [
125            'type'   => 'switch',
126            'label'  => $this->l("Active"),
127            'name'   => 'active',
128            'values' => [
129                [
130                    'id'    => 'active_on',
131                    'value' => 1,
132                ],
133                [
134                    'id'    => 'active_off',
135                    'value' => 0,
136                ],
137            ],
138        ];
139
140        if ($this->display == 'edit') {
141            $inputs[] = [
142                'type' => 'hidden',
143                'name' => 'id_block',
144            ];
145            $title = $this->l('Edit Block');
146            $action = 'submitEditBlock';
147            $this->fields_value = $this->module->getSingleBlockData(Tools::getValue('id_block'));
148        } else {
149            $title = $this->l('Add new Entry');
150            $action = 'submitAddBlock';
151        }
152
153        $this->fields_form = [
154            'legend' => [
155                'title' => $title,
156                'icon'  => 'icon-cogs',
157            ],
158            'input' => $inputs,
159            'submit' => [
160                'title' => $this->l('Save'),
161                'class' => 'btn btn-default pull-right',
162                'name'  => $action,
163            ],
164        ];
165
166        return parent::renderForm();
167    }
168
169    public function renderView()
170    {
171        $this->tpl_view_vars['object'] = $this->loadObject();
172
173        return parent::renderView();
174    }
175
176    public function postProcess()
177    {
178        if ($this->ajax) {
179            $action = Tools::getValue('action');
180            if ( ! empty($action)
181                && method_exists($this, 'ajaxProcess'.Tools::toCamelCase($action))
182            ) {
183                $return = $this->{'ajaxProcess'.Tools::toCamelCase($action)}();
184            }
185        } else {
186            if (Tools::isSubmit('submitAddBlock')) {
187                $this->processAdd();
188            } elseif (Tools::isSubmit('submitEditBlock')) {
189                $this->processUpdate();
190            } elseif (Tools::isSubmit('status'.$this->table)) {
191                $this->toggleStatus();
192            } elseif (Tools::isSubmit('delete'.$this->table)
193                && Tools::isSubmit('id_block')
194            ) {
195                $this->processDelete();
196            }
197        }
198    }
199
200    public function toggleStatus()
201    {
202        $idBlock = (int)Tools::getValue('id_block');
203        Db::getInstance()->update($this->module->table_name, ['active' => !$this->module->getBlockStatus($idBlock)], 'id_block = '.$idBlock);
204
205        if (empty($this->errors)) {
206            $this->redirect_after = static::$currentIndex.'&conf=4&token='.$this->token;
207        }
208    }
209
210    public function processAdd()
211    {
212        $blockName = Tools::getValue('name');
213
214        if ( ! $blockName || ! Validate::isGenericName($blockName)) {
215            $this->_errors[] = $this->l('Invalid name');
216        } else {
217            if ( ! Db::getInstance()->insert($this->module->table_name, ['name' => $blockName, 'active' => Tools::getValue('active')])) {
218                $this->_errors[] = $this->l('Error while adding the new block, please retry');
219            } else {
220                $blockId = Db::getInstance()->Insert_ID();
221
222                $hookName = Tools::getValue('hook_name');
223                $maxP = Db::getInstance()->getValue('SELECT MAX(position) FROM ' . _DB_PREFIX_ . $this->module->table_name_hook . ' WHERE hook_name = "' . pSQL($hookName).'"');
224
225                if ($maxP === false) {
226                    $maxP = 0;
227                } else {
228                    $maxP++;
229                }
230
231                $hookData = [
232                    'id_block'  => $blockId,
233                    'hook_name' => pSQL($hookName),
234                    'position'  => $maxP,
235                ];
236
237                if ( ! Db::getInstance()->insert($this->module->table_name_hook, $hookData)) {
238                    Db::getInstance()->delete($this->module->table_name, 'id_block = ' . $blockId);
239                    $this->_errors[] = $this->l('Error while adding the hook. ');
240                } else {
241                    foreach ($this->getLanguages() as $lang) {
242                        $content = Tools::getValue('content_'.$lang['id_lang']);
243                        if ( ! Db::getInstance()->insert($this->module->table_name_lang, ['id_block' => $blockId, 'id_lang' => $lang['id_lang'], 'content' => pSQL($content, TRUE)]))
244                            $this->_errors[] = $this->l('Error while adding the block\'s content for language "'.$lang['id_lang'].'"');
245                    }
246                }
247            }
248        }
249
250        if (empty($this->errors)) {
251            $this->redirect_after = static::$currentIndex.'&conf=3&token='.$this->token;
252        }
253    }
254
255    public function processUpdate()
256    {
257        $blockName = Tools::getValue('name');
258        if ( ! $blockName || ! Validate::isGenericName($blockName))
259            $this->_errors[] = $this->l('Invalid name');
260        else {
261            if (!Db::getInstance()->update($this->module->table_name, ['name' => $blockName, 'active' => Tools::getValue('active')], 'id_block = '. (int)Tools::getValue('id_block'))) {
262                $this->_errors[] = $this->l('Error while updating the block ');
263            } else {
264                if (!Db::getInstance()->update($this->module->table_name_hook, ['hook_name' => pSQL(Tools::getValue('hook_name'))], 'id_block = '. (int)Tools::getValue('id_block'))) {
265                    $this->_errors[] = $this->l('Error while updating the hook ');
266                } else {
267                    foreach ($this->getLanguages() as $lang) {
268                        $content = Tools::getValue('content_'.$lang['id_lang']);
269
270                        // add the language if not present
271                        $isLangAdded = Db::getInstance()->getValue('SELECT id_block FROM '._DB_PREFIX_.$this->module->table_name_lang.' WHERE id_block = '.(int)Tools::getValue('id_block').' AND id_lang = ' . $lang['id_lang']);
272                        if ( ! $isLangAdded) {
273                            Db::getInstance()->insert(
274                                $this->module->table_name_lang,
275                                [
276                                    'id_lang'   => $lang['id_lang'],
277                                    'id_block'  => (int)Tools::getValue('id_block'),
278                                    'content'   => '',
279                                ]
280                            );
281                        }
282
283                        if ( ! Db::getInstance()->update(
284                            $this->module->table_name_lang,
285                            ['content' => pSQL($content, true)],
286                            'id_block = '.(int) Tools::getValue('id_block').' AND id_lang = ' . $lang['id_lang']
287                        )) {
288                            $this->_errors[] = $this->l('Error while updating the block\'s content for language "'.$lang['id_lang'].'"');
289                        }
290                    }
291                }
292            }
293        }
294
295        if (empty($this->errors)) {
296            $this->redirect_after = static::$currentIndex.'&conf=4&token='.$this->token;
297        }
298    }
299
300    public function processDelete()
301    {
302        $idBlock = Tools::getValue('id_block');
303        Db::getInstance()->delete($this->module->table_name, 'id_block = ' . $idBlock);
304        Db::getInstance()->delete($this->module->table_name_hook, 'id_block = ' . $idBlock);
305        Db::getInstance()->delete($this->module->table_name_lang, 'id_block = ' . $idBlock);
306
307        $this->redirect_after = static::$currentIndex.'&conf=1&token='.$this->token;
308    }
309
310    public function ajaxProcessUpdatePositions()
311    {
312        $positions = Tools::getValue('block');
313
314        foreach ($positions as $position => $value) {
315            $pos = explode('_', $value);
316            Db::getInstance()->update($this->module->table_name_hook, ['position' => $position], 'id_block =' . (int)$pos[2]);
317        }
318    }
319}
320