<?php
/**
 * @package    VP Email Manager
 * @copyright  Copyright (C) 2012-2021 VirtuePlanet Services LLP. All rights reserved.
 * @license    GNU General Public License version 2 or later; see LICENSE.txt
 * @author     Abhishek Das <info@virtueplanet.com>
 * @link       https://www.virtueplanet.com
 */

defined('_JEXEC') or die;

jimport('joomla.application.component.controllerform');

use \Joomla\CMS\Factory;
use \Joomla\CMS\Uri\Uri;
use \Joomla\CMS\Router\Route;
use \Joomla\CMS\Language\Text;

/**
 * Event controller class.
 */
class VpemControllerMail extends \Joomla\CMS\MVC\Controller\FormController
{
	/**
	 * Constructor
	 *
	 * @throws Exception
	 */
	public function __construct()
	{
		$this->view_list = 'outbox';
		
		parent::__construct();
	}
	
	public function download()
	{
		$this->checkToken('POST');
		
		$app   = Factory::getApplication();
		$input = $app->input;
		$file  = $input->get('file', '', 'BASE64');
		$id    = $input->getInt('id', 0);
		
		if (empty($file) || (!$file = base64_decode($file)))
		{
			$app->enqueueMessage(Text::_('COM_VPEM_ERROR_INVALID_FILE'));
			$app->redirect(Route::_('index.php?option=com_vpem&view=mail&id=' . $id));
			
			return false;
		}
		
		if (!is_file($file))
		{
			$file = JPath::clean(JPATH_ROOT . DIRECTORY_SEPARATOR . $file);
		}
		
		if (!is_file($file))
		{
			$app->enqueueMessage(Text::_('COM_VPEM_ERROR_FILE_DOES_NOT_EXIST'));
			$app->redirect(Route::_('index.php?option=com_vpem&view=mail&id=' . $id));
			
			return false;
		}

		header('Content-Description: File Transfer');
		header('Content-Type: application/octet-stream');
		header('Content-Disposition: attachment; filename="' . basename($file) . '"');
		header('Expires: 0');
		header('Cache-Control: must-revalidate');
		header('Pragma: public');
		header('Content-Length: ' . filesize($file));
		readfile($file);
		
		$app->close();
	}
}
