<?php
namespace JExtstore\Component\JRealtimeAnalytics\Administrator\Model;
/**
 *
 * @package JREALTIMEANALYTICS::HEATMAP::administrator::components::com_jrealtimeanalytics
 * @subpackage models
 * @author Joomla! Extensions Store
 * @copyright (C) 2014 - Joomla! Extensions Store
 * @license GNU/GPLv2 http://www.gnu.org/licenses/gpl-2.0.html
 */
defined ( '_JEXEC' ) or die ( 'Restricted access' );
use Joomla\CMS\Language\Text;
use Joomla\CMS\HTML\HTMLHelper;
use JExtstore\Component\JRealtimeAnalytics\Administrator\Framework\Model as JRealtimeModel;
use JExtstore\Component\JRealtimeAnalytics\Administrator\Framework\Exception as JRealtimeException;

/**
 * Sources model concrete implementation <<testable_behavior>>
 *
 * @package JREALTIMEANALYTICS::HEATMAP::administrator::components::com_jrealtimeanalytics
 * @subpackage models
 * @since 2.4
 */
class HeatmapModel extends JRealtimeModel {
	/**
	 * Build list entities query
	 *
	 * @access protected
	 * @return string
	 */
	protected function buildListQuery() {
		// WHERE
		$where = array ();
		$order = array();
		$whereString = null;
		$orderString = null;
		
		// PERIOD FILTER
		$where [] = $this->dbInstance->quoteName('c.record_date') . " >= " . $this->dbInstance->quote($this->getState('fromPeriod'));
		$where [] = $this->dbInstance->quoteName('c.record_date') . " <= " . $this->dbInstance->quote($this->getState('toPeriod'));
		
		// TEXT FILTER
		if ($this->state->get ( 'searchword' )) {
			$where [] = "s.pageurl LIKE '%" . $this->state->get ( 'searchword' ) . "%'";
		}
		
		if (count ( $where )) {
			$whereString = "\n WHERE " . implode ( "\n AND ", $where );
		}
		
		// ORDERBY
		if ($this->state->get ( 'order' )) {
			$order[] = $this->state->get ( 'order' );
		}
		
		if(count($order)) {
			$orderString = "\n ORDER BY " . implode ( ", ", $order );
		}
		
		// ORDERDIR
		if ($this->state->get ( 'order_dir' )) {
			$orderString .= " " . $this->state->get ( 'order_dir' );
		}
		
		$query = "SELECT count(c.id) AS numclicks, s.id, s.pageurl" .
				 "\n FROM #__realtimeanalytics_heatmap AS s" . 
				 "\n INNER JOIN #__realtimeanalytics_heatmap_clicks AS c" .
				 "\n ON s.id = c.heatmap_id" .
				 $whereString . 
				 "\n GROUP BY s.pageurl" .
				 $orderString;
		return $query;
	}
	
	/**
	 * Return select lists used as filter for editEntity
	 *
	 * @access public
	 * @param Object $record
	 * @return array
	 */
	public function getLists($record = null): array {
		$lists = [];
	
		// Supported graph theme
		$themes = [];
		$themes[] = HTMLHelper::_('select.option', 'Universal', 'Universal');
		$themes[] = HTMLHelper::_('select.option', 'Aqua', 'Aqua');
		$themes[] = HTMLHelper::_('select.option', 'Orange', 'Orange');
		$themes[] = HTMLHelper::_('select.option', 'Pastel', 'Pastel');
		$themes[] = HTMLHelper::_('select.option', 'Rose', 'Rose');
		$themes[] = HTMLHelper::_('select.option', 'Softy', 'Softy');
		$themes[] = HTMLHelper::_('select.option', 'Vivid', 'Vivid');
	
		$lists ['graphTheme'] = HTMLHelper::_ ( 'select.genericlist', $themes, 'graphtheme', 'onchange="Joomla.submitform();"', 'value', 'text', $this->getState('graphTheme', 'Universal'));
	
		return $lists;
	}
	
	/**
	 * Return select lists used as filter for listEntities
	 *
	 * @access public
	 * @return array
	 */
	public function getFilters(): array {
		$filters = [];
		return $filters;
	}
	
	/**
	 * Delete entity
	 *
	 * @param array $ids        	
	 * @access public
	 * @return bool
	 */
	public function deleteEntity($ids): bool {
		try {
			// Check if valid array of ids passed
			if(!is_array($ids) || !count($ids)) {
				throw new JRealtimeException(Text::_('COM_JREALTIME_ERROR_DELETE_NO_RECORDS'), 'error');
			}
			
			// Transductor for the specific selector record ID to the pageurl globally applied
			$preQuery = "SELECT " . $this->dbInstance->quoteName('pageurl') .
						"\n FROM " . $this->dbInstance->quoteName('#__realtimeanalytics_heatmap') .
						"\n WHERE " . $this->dbInstance->quoteName('id') . " IN (" . implode(',', $ids) . ")";
			$pageUrls = $this->dbInstance->setQuery($preQuery)->loadColumn();
			array_walk ( $pageUrls, function (&$url, $key, $db) {
				$url = $db->quote ( $url );
			}, $this->dbInstance );
			
			$query = "DELETE " .
					$this->dbInstance->quoteName('heatmap') . "," .
					$this->dbInstance->quoteName('heatmapclicks') .
					"\n FROM #__realtimeanalytics_heatmap AS heatmap" .
					"\n LEFT JOIN #__realtimeanalytics_heatmap_clicks AS heatmapclicks" .
					"\n ON heatmap.id = heatmapclicks.heatmap_id" .
					"\n WHERE heatmap.pageurl IN (" . implode(',', $pageUrls) . ")";
			$this->dbInstance->setQuery($query);
			$this->dbInstance->execute();
		} catch (JRealtimeException $e) {
			$this->setException($e);
			return false;
		} catch (\Exception $e) {
			$jrealtimeException = new JRealtimeException($e->getMessage(), 'error');
			$this->setException($jrealtimeException);
			return false;
		}
		return true;
	}
}