<?php
/**
 * @version        1.9.7
 * @package        Joomla
 * @subpackage     Edocman
 * @author         Dang Thuc Dam
 * @copyright      Copyright (C) 2011 - 2024 Ossolution Team
 * @license        GNU/GPL, see LICENSE.php
 */

// No direct access
defined('_JEXEC') or die();
use Joomla\Filesystem\File;
use Joomla\CMS\Language\Text;

class EDocmanControllerConfiguration extends EDocmanController
{

	function __construct(OSInput $input = null, $config = array())
	{
		parent::__construct($input, $config);
	}

	/**
	 * Save configuration data
	 */
	public function save()
	{
		$data  = $this->input->getData();
		$model = $this->getModel('Configuration');
		$model->store($data);
        if (isset($data['custom_css']))
        {
            File::write(JPATH_ROOT . '/components/com_edocman/assets/css/custom.css', trim($data['custom_css']));
        }

		$folderPath = JPATH_ROOT . '/media/com_edocman/document/medium';
		if (is_dir($folderPath)) 
		{
			// Open the directory
			$dir = opendir($folderPath);

			// Loop through the files in the directory
			while (($file = readdir($dir)) !== false) 
			{
				// Skip . and .. (current and parent directory)
				if ($file == '.' || $file == '..') {
					continue;
				}

				// Define the full path to the image file
				$filePath = $folderPath . '/' . $file;

				// Check if the file is an image (you can adjust this to specific file types)
				if (is_file($filePath) && in_array(strtolower(pathinfo($file, PATHINFO_EXTENSION)), ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'])) 
				{
					// Delete the file
					unlink($filePath);
				}
			}

			// Close the directory
			closedir($dir);
		} 

		if($this->task == "apply"){
			$this->setRedirect('index.php?option=com_edocman&view=configuration', Text::_('EDOCMAN_CONFIGURATION_SAVED'));
		}else{
			$this->setRedirect('index.php?option=com_edocman', Text::_('EDOCMAN_CONFIGURATION_SAVED'));
		}
	}

	/**
	 * Redirect to default view of the component
	 */
	public function cancel()
	{
		$this->setRedirect('index.php?option=com_edocman&view=' . $this->defaultView);
	}
}
