1<?php
2/**
3 * 2007-2016 PrestaShop
4 *
5 * thirty bees is an extension to the PrestaShop e-commerce software developed by PrestaShop SA
6 * Copyright (C) 2017-2018 thirty bees
7 *
8 * NOTICE OF LICENSE
9 *
10 * This source file is subject to the Open Software License (OSL 3.0)
11 * that is bundled with this package in the file LICENSE.txt.
12 * It is also available through the world-wide-web at this URL:
13 * http://opensource.org/licenses/osl-3.0.php
14 * If you did not receive a copy of the license and are unable to
15 * obtain it through the world-wide-web, please send an email
16 * to license@thirtybees.com so we can send you a copy immediately.
17 *
18 * DISCLAIMER
19 *
20 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
21 * versions in the future. If you wish to customize PrestaShop for your
22 * needs please refer to https://www.thirtybees.com for more information.
23 *
24 *  @author    thirty bees <contact@thirtybees.com>
25 *  @author    PrestaShop SA <contact@prestashop.com>
26 *  @copyright 2017-2018 thirty bees
27 *  @copyright 2007-2016 PrestaShop SA
28 *  @license   http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
29 *  PrestaShop is an internationally registered trademark & property of PrestaShop SA
30 */
31
32/**
33 * Class ModuleGridEngineCore
34 *
35 * @since 1.0.0
36 */
37class ModuleGridEngineCore extends Module
38{
39    // @codingStandardsIgnoreStart
40    protected $_type;
41    private $_values;
42    private static $_columns;
43    // @codingStandardsIgnoreEnd
44
45    /**
46     * ModuleGridEngineCore constructor.
47     *
48     * @param null|string $type
49     *
50     * @since 1.0.0
51     * @version 1.0.0 Initial version
52     */
53    public function __construct($type)
54    {
55        $this->_type = $type;
56    }
57
58    /**
59     * @return bool
60     *
61     * @since 1.0.0
62     * @version 1.0.0 Initial version
63     */
64    public function install()
65    {
66        if (!parent::install()) {
67            return false;
68        }
69
70        return Configuration::updateValue('PS_STATS_GRID_RENDER', $this->name);
71    }
72
73    /**
74     * @return array
75     *
76     * @since 1.0.0
77     * @version 1.0.0 Initial version
78     */
79    public static function getGridEngines()
80    {
81        $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(
82            (new DbQuery())
83                ->select('m.`name`')
84                ->from('module', 'm')
85                ->leftJoin('module', 'm')
86                ->leftJoin('hook', 'h', 'hm.`id_hook` = h.`id_hook`')
87                ->where('h.`name` = \'displayAdminStatsGridEngine\'')
88        );
89
90        $arrayEngines = [];
91        foreach ($result as $module) {
92            $instance = Module::getInstanceByName($module['name']);
93            if (!$instance) {
94                continue;
95            }
96            $arrayEngines[$module['name']] = [$instance->displayName, $instance->description];
97        }
98
99        return $arrayEngines;
100    }
101
102    public static function hookGridEngine($params, $grider)
103    {
104        self::$_columns = $params['columns'];
105        if (!isset($params['emptyMsg']))
106            $params['emptyMsg'] = 'Empty';
107        $customParams = '';
108        if (isset($params['customParams'])) {
109            foreach ($params['customParams'] as $name => $value) {
110                $customParams .= '&'.$name.'='.urlencode($value);
111            }
112        }
113        $html = '
114		<table class="table" id="grid_1">
115			<thead>
116				<tr>';
117        foreach ($params['columns'] as $column)
118            $html .= '<th class="center"><span class="title_box active">'.$column['header'].'</span></th>';
119        $html .= '</tr>
120			</thead>
121			<tbody></tbody>
122			<tfoot><tr><th colspan="'.count($params['columns']).'"></th></tr></tfoot>
123		</table>
124		<script type="text/javascript">
125			function getGridData(url)
126			{
127				$("#grid_1 tbody").html("<tr><td style=\"text-align:center\" colspan=\"" + '.count($params['columns']).' + "\"><img src=\"../img/loadingAnimation.gif\" /></td></tr>");
128				$.get(url, "", function(json) {
129					$("#grid_1 tbody").html("");
130					var array = $.parseJSON(json);
131					$("#grid_1 tfoot tr th").html("'.addslashes($params['pagingMessage']).'");
132					$("#grid_1 tfoot tr th").html($("#grid_1 tfoot tr th").html().replace("{0}", array["from"]));
133					$("#grid_1 tfoot tr th").html($("#grid_1 tfoot tr th").html().replace("{1}", array["to"]));
134					$("#grid_1 tfoot tr th").html($("#grid_1 tfoot tr th").html().replace("{2}", array["total"]));
135					if (array["from"] > 1)
136						$("#grid_1 tfoot tr th").html($("#grid_1 tfoot tr th").html() + " &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a style=\\"cursor:pointer;text-decoration:none\\" onclick=\\"gridPrevPage(\'"+ url +"\');\\">&lt;&lt;</a>");
137					if (array["to"] < array["total"])
138						$("#grid_1 tfoot tr th").html($("#grid_1 tfoot tr th").html() + " | <a style=\\"cursor:pointer;text-decoration:none\\" onclick=\\"gridNextPage(\'"+ url +"\');\\">&gt;&gt;</a>");
139					var values = array["values"];
140					if (values.length > 0)
141						$.each(values, function(index, row){
142							var newLine = "<tr>";';
143        foreach ($params['columns'] as $column)
144            $html .= '	newLine += "<td'.(isset($column['align']) ? ' align=\"'.$column['align'].'\"' : '').'>" + row["'.$column['dataIndex'].'"] + "</td>";';
145        if (!isset($params['defaultSortColumn']))
146            $params['defaultSortColumn'] = false;
147        if (!isset($params['defaultSortDirection']))
148            $params['defaultSortDirection'] = false;
149        $html .= '		$("#grid_1 tbody").append(newLine);
150						});
151					else
152						$("#grid_1 tbody").append("<tr><td class=\"center\" colspan=\"" + '.count($params['columns']).' + "\">'.$params['emptyMsg'].'</td></tr>");
153				});
154			}
155
156			function gridNextPage(url)
157			{
158				var from = url.match(/&start=[0-9]+/i);
159				if (from && from[0] && parseInt(from[0].replace("&start=", "")) > 0)
160					from = "&start=" + (parseInt(from[0].replace("&start=", "")) + 40);
161				else
162					from = "&start=40";
163				url = url.replace(/&start=[0-9]+/i, "") + from;
164				getGridData(url);
165			}
166
167			function gridPrevPage(url)
168			{
169				var from = url.match(/&start=[0-9]+/i);
170				if (from && from[0] && parseInt(from[0].replace("&start=", "")) > 0)
171				{
172					var fromInt = parseInt(from[0].replace("&start=", "")) - 40;
173					if (fromInt > 0)
174						from = "&start=" + fromInt;
175					else
176						from = "&start=0";
177				}
178				else
179					from = "&start=0";
180				url = url.replace(/&start=[0-9]+/i, "") + from;
181				getGridData(url);
182			}
183			$(document).ready(function(){getGridData("'.$grider.'&sort='.urlencode($params['defaultSortColumn']).'&dir='.urlencode($params['defaultSortDirection']).$customParams.'");});
184		</script>';
185        return $html;
186    }
187
188    public function setColumnsInfos(&$infos)
189    {
190    }
191
192    public function setValues($values)
193    {
194        $this->_values = $values;
195    }
196
197    public function setTitle($title)
198    {
199        $this->_title = $title;
200    }
201
202    public function setSize($width, $height)
203    {
204        $this->_width = $width;
205        $this->_height = $height;
206    }
207
208    public function setTotalCount($totalCount)
209    {
210        $this->_totalCount = $totalCount;
211    }
212
213    public function setLimit($start, $limit)
214    {
215        $this->_start = (int)$start;
216        $this->_limit = (int)$limit;
217    }
218
219    public function render()
220    {
221        echo json_encode([
222            'total' => $this->_totalCount,
223            'from' => min($this->_start + 1, $this->_totalCount),
224            'to' => min($this->_start + $this->_limit, $this->_totalCount),
225            'values' => $this->_values
226        ]);
227        exit;
228    }
229}
230