<?php

/**
 * @package         Google Structured Data
 * @version         6.2.1 Free
 *
 * @author          Tassos Marinos <info@tassos.gr>
 * @link            http://www.tassos.gr
 * @copyright       Copyright © 2026 Tassos Marinos All Rights Reserved
 * @license         GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> or later
*/

defined('_JEXEC') or die('Restricted access');

use GSD\Helper;
use GSD\Markdown;
use Joomla\CMS\MVC\Controller\FormController;

/**
 * Config controller class
 */
class GSDControllerConfig extends FormController
{
	protected $text_prefix = 'GSD';

	/**
	 * Markdown settings that change the generated output and therefore
	 * require the cached Markdown responses to be cleared when modified.
	 *
	 * @var  array
	 */
	private $markdownOutputKeys = ['markdown_frontmatter', 'markdown_schema_summary'];

	/**
	 * Save configuration and clear the Markdown cache when an output setting
	 * or the extraction method changes, so stored responses are regenerated.
	 *
	 * @param   string  $key
	 * @param   string  $urlVar
	 *
	 * @return  boolean
	 */
	public function save($key = null, $urlVar = null)
	{
		$params = Helper::getParams();

		$oldValues = [];

		foreach ($this->markdownOutputKeys as $name)
		{
			$oldValues[$name] = (int) $params->get($name, 0);
		}

		$oldExtraction = (string) $params->get('markdown_extraction', 'buffer');

		$saved = parent::save($key, $urlVar);

		if (!$saved)
		{
			return $saved;
		}

		$data          = $this->input->post->get('jform', [], 'array');
		$newExtraction = isset($data['markdown_extraction']) ? (string) $data['markdown_extraction'] : 'buffer';

		$shouldClear = $oldExtraction !== $newExtraction;

		if (!$shouldClear)
		{
			foreach ($this->markdownOutputKeys as $name)
			{
				$newValue = isset($data[$name]) ? (int) $data[$name] : 0;

				if ($newValue !== $oldValues[$name])
				{
					$shouldClear = true;

					break;
				}
			}
		}

		if ($shouldClear)
		{
			Markdown::clearCache();
		}

		return $saved;
	}
}
