<?php

/**
 * @version        1.9.7
 * @package        Joomla
 * @subpackage     Edocman
 * @author         Tuan Pham Ngoc
 * @copyright      Copyright (C) 2011 - 2024 Ossolution Team
 * @license        GNU/GPL, see LICENSE.php
 */

// No direct access.
defined('_JEXEC') or die();
use Joomla\CMS\Language\Text;
use Joomla\CMS\Factory;
use Joomla\Application\Web\WebClient;
use Joomla\CMS\Environment\Browser;

/**
 * Categories list controller class.
 */
class EdocmanControllerDownloadlog extends EDocmanController
{
	/**
	 * Method to empty the download logs database
	 *
	 */
	function delete()
	{
		$model = $this->getModel();
		$model->delete();
		$this->setRedirect('index.php?option=com_edocman&view=downloadlogs', Text::_('Download logs emptied'));
	}

	/**
	 * Method to export download logs into a csv file
	 */
	function export()
	{
		$db			= Factory::getContainer()->get('db');
		$input		= Factory::getApplication()->getInput();
		$start_date = $input->getString('start_date','');
		$end_date	= $input->getString('end_date','');
		$filter_search = $input->getString('filter_search','');

		$sql		= 'SELECT a.*, b.title, c.username AS downloader_username, c.email AS downloader_email FROM #__edocman_statistics AS a ' .
					  ' left JOIN #__edocman_documents AS b ON a.document_id=b.id' . ' LEFT JOIN #__users AS c ON a.user_id=c.id' . ' ';

		$sql		.= ' where 1=1';

		if($start_date != "" && $start_date != "0000-00-00 00:00:00")
		{
			$sql   .= ' and a.download_time >= '. $db->quote($start_date);
		}

		if($end_date != "" && $end_date != "0000-00-00 00:00:00")
		{
			$sql   .= ' and a.download_time <= '. $db->quote($end_date);
		}
		if($filter_search != "")
		{
			$sql   .= ' and (b.title like '.$db->quote('%'.$filter_search.'%').' or c.username like '.$db->quote('%'.$filter_search.'%').')';
		}

		$sql		.= ' order by a.download_time desc';
		$db->setQuery($sql);

		$rows = $db->loadObjectList();
		if (count($rows))
		{
			$results_arr = [];
			$csv_output  = Text::_('Document');
			$csv_output .= "," . Text::_('Username');
			$csv_output .= ", " . Text::_('Email');
			$csv_output .= ", " . Text::_('Download Time');
			$csv_output .= ', ' . Text::_('User IP');
			$csv_output .= ', ' . Text::_('Browser');
			$csv_output .= ', ' . Text::_('OS');
			$UTC = new DateTimeZone("UTC");
			$newTZ = new DateTimeZone(Factory::getApplication()->get('offset'));
			foreach ($rows as $r)
			{
				$results_arr   = [];
				$results_arr[] = $r->title;
				if (!$r->user_id)
				{
					$results_arr[] = $r->name;
					$results_arr[] = $r->email;
				}
				else 
				{
					$results_arr[] = $r->downloader_username;
					$results_arr[] = $r->downloader_email;
				}
				$date = new DateTime( $r->download_time, $UTC );
				$date->setTimezone( $newTZ );
				$config = EDocmanHelper::loadConfig();
				$date_format = $config->get('date_format');
				if($date_format == ""){
					$date_format = "m-d-Y H:i:s";
				}
				$results_arr[] = $date->format($date_format);
				$results_arr[] = $r->user_ip;
				$results_arr[] = $r->browser;
				$results_arr[] = $r->os;
				$csv_output .= "\n\"" . implode("\",\"", $results_arr) . "\"";
			}
			$csv_output .= "\n";
			
			$browser   = Factory::getApplication()->client->browser;
			$mime_type = ($browser == WebClient::IE || $browser == WebClient::OPERA) ? 'application/octetstream' : 'application/octet-stream';
			$filename  = "Download_log";
			@ob_end_clean();
			ob_start();
			header('Content-Type: ' . $mime_type);
			header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
			$UserBrowser = Browser::getInstance()->getBrowser();
			if ($UserBrowser == 'IE')
			{
				header('Content-Disposition: attachment; filename="' . $filename . '.csv"');
				header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
				header('Pragma: public');
			}
			else
			{
				header('Content-Disposition: attachment; filename="' . $filename . '.csv"');
				header('Pragma: no-cache');
			}
			print $csv_output;
			exit();
		}
	}
}
