<?php
/**
 * @package            Joomla
 * @subpackage         Documents Seller
 * @author             Tuan Pham Ngoc
 * @copyright          Copyright (C) 2010 - 2024 Ossolution Team
 * @license            GNU/GPL, see LICENSE.php
 */

defined('_JEXEC') or die;

use Joomla\CMS\Factory;

class EDocmanModelChart extends OSModel
{
	/**
	 * Constructor
	 *
	 * @param   array  $config
	 *
	 * @throws Exception
	 */
	public function __construct(array $config = [])
	{
		parent::__construct($config);

		$this->state->insert('filter_category_id', 'int', 0);
	}

	/**
	 * Get sales data in last 12 months
	 *
	 * @return array
	 *
	 * @throws Exception
	 */
	public function getData()
	{
		$db    = $this->getDbo();
		$query = $db->getQuery(true);
		$today = Factory::getDate('Now', Factory::getApplication()->get('offset'));
		$sales = [];

		for ($i = 0; $i < 12; $i++)
		{
			if ($i > 0)
			{
				$today->modify('-1 month');
			}

			$month = $today->format('n', true);
			$year  = $today->format('Y', true);

			$startMonth = clone $today;
			$endMonth   = clone $today;

			$startMonth->setTime(0, 0, 0);
			$startMonth->setDate($year, $month, 1);
			$endMonth->setTime(23, 59, 59);
			$endMonth->setDate($year, $month, $today->format('t', true));	

			$query = "Select count(a.id) from #__edocman_statistics as a inner join #__edocman_document_category as b on a.document_id = b.document_id where a.download_time >= ".$db->quote($startMonth->toSql())." and a.download_time <= ".$db->quote($endMonth->toSql())."";

			if ($this->state->filter_category_id)
			{
				$query .= " and b.is_main_category = '1' and b.category_id = '".$this->state->filter_category_id."'";
				$subCats = [];
				EdocmanHelper::retrieveAllChildCategories($this->state->filter_category_id, $subCats);
				if(count($subCats))
				{
					$query .= " and b.is_main_category = '1' and b.category_id in (".implode(",",$subCats).")";
				}
			}
			$db->setQuery($query);
			$sales[$today->format('M') . '/ ' . $year] = (int) $db->loadResult();
		}

		return (array)$sales;
	}
}