<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_notifly
 *
 * @copyright   Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

defined('_JEXEC') or die;

/**
 * View class for a list of featured articles.
 *
 * @since  1.6
 */
class NotiflyViewDashboard extends JViewLegacy
{
	/**
	 * The sidebar markup
	 *
	 * @var  string
	 */
	protected $sidebar;

	/**
	 * component config
	 *
	 * @var  jobject
	 */
	protected $config;

	/**
	 * Display the view
	 *
	 * @param   string  $tpl  The name of the template file to parse; automatically searches through the template paths.
	 *
	 * @return  mixed  A string if successful, otherwise an Error object.
	 */
	public function display($tpl = null)
	{
		NotiflyHelper::addSubmenu('dashboard');
		$this->config = JComponentHelper::getParams('com_notifly');
		
		// Check for errors.
		if (count($errors = $this->get('Errors')))
		{
			throw new Exception(implode("\n", $errors), 500);
		}
		$this->items = $this->getLogs();
		// print_r($this->items);die;
		$this->addToolbar();
		$this->sidebar = JHtmlSidebar::render();

		return parent::display($tpl);
	}

	/**
	 * Add the page title and toolbar.
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function addToolbar()
	{
		// $state = $this->get('State');
		$canDo = JHelperContent::getActions('com_notifly');

		JToolbarHelper::title(JText::_('COM_NOTIFLY_DASHBOARD_TITLE'), 'star dashboard');

		// JToolbarHelper::custom('articles.unfeatured', 'unfeatured.png', 'featured_f2.png', 'JUNFEATURE', true);

		if ($canDo->get('core.admin') || $canDo->get('core.options'))
		{
			JToolbarHelper::preferences('com_notifly');
		}
		
		$help_url  = 'https://www.themexpert.com/docs';
		JToolbarHelper::help( 'COM_NOTIFLY_HELP_SITE', false, $help_url );
	}

	public function getLogs(){
		// $date = date('m', strtotime('+1 month'));
		$db = JFactory::getDbo();
		$query = $db->getQuery(true);
		$query->select("a.*")
			  ->from('#__notifly_logs as a')
			  // $db->quote(JFactory::getDate()->format('Y-m-d') . ' 00:00:00')
			  ->where($db->quoteName('a.date') . ' BETWEEN ' . $db->quote(JFactory::getDate()->format('Y-m-01') . ' 00:00:00') . ' AND ' . $db->quote(JFactory::getDate()->format('Y-m-'. date("t")) . ' 00:00:00'))
			  ->group($db->quoteName('a.date'))
			  ->order($db->quoteName('a.id') . ' DESC')


			  // get the limit form config
			  ->limit('20');
		// echo $query->__toString();die;
		$db->setQuery($query);
		$results = $db->loadObjectList();
		$return = [];
		foreach ($results as $key => $result) {
			$return[$result->date] = $result;
		}
		// print_r($return);die;
		return $return;
	}

	
}
