<?php
/**
 * @package     CMGiftCard
 * @subpackage  com_cmgiftcard
 * @copyright   Copyright (C) 2016-2024 CMExension
 * @license     GNU General Public License version 2 or later
 */

defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Response\JsonResponse;
use Joomla\CMS\MVC\Controller\BaseController;
use Joomla\CMS\MVC\Model\BaseDatabaseModel;
use Joomla\CMS\Filesystem\File;
use Joomla\CMS\Filesystem\Path;
use Joomla\CMS\Session\Session;

/**
 * Controller class for importing gift card codes.
 *
 * @package     CMGiftCard
 * @subpackage  com_cmgiftcard
 * @since       1.0.0
 */
class CMGiftCardControllerTools extends BaseController
{
	/**
	 * Import gift card codes.
	 *
	 * @return  boolean
	 *
	 * @since   1.0.0
	 */
	public function importCode()
	{
		$app = Factory::getApplication();

		if (!Session::checkToken('get'))
		{
			$app->enqueueMessage(Text::_('JINVALID_TOKEN'), 'error');
			echo new JsonResponse(null, null, true);

			return true;
		}

		$folderPath = JPATH_ROOT . '/administrator/components/com_cmgiftcard/uploads/';
		$fileName = $app->getUserState('com_cmgiftcard.tools.code_file', '');
		$source = Path::clean($folderPath . $fileName);

		if (File::exists($source))
		{
			$handle = fopen($source, 'r');

			if ($handle)
			{
				$params = ComponentHelper::getParams('com_cmgiftcard');
				$codeChar = $params->get('card_code_characters', 'alphanumeric');
				$codeLength = (int) $params->get('card_code_length', 5);
				$codes = array();

				while (($line = fgets($handle)) !== false)
				{
					$line = strtoupper(str_replace(' ', '', trim(strip_tags($line))));

					if ($codeChar == 'alphabetic')
					{
						$line = preg_replace("/[^A-Z]/", '', $line);
					}
					elseif ($codeChar == 'numeric')
					{
						$line = preg_replace('/[^0-9]/', '', $line);
					}
					else
					{
						$line = preg_replace('/[^A-Z0-9]/', '', $line);
					}

					if (strlen($line) > $codeLength)
					{
						$line = substr($line, 0, $codeLength);
					}

					if ($line != '' && !in_array($line, $codes))
						$codes[] = $line;
				}

				if (count($codes))
				{
					$model = BaseDatabaseModel::getInstance('Tools', 'CMGiftCardModel');
					$created = Factory::getDate()->toSql();
					$userId = Factory::getUser()->id;
					$successes = 0;

					foreach ($codes as $code)
					{
						$result = $model->importCode($code, $created, $userId);

						if ($result)
							$successes++;
					}

					fclose($handle);

					if ($handle = @opendir($folderPath))
					{
						while (($file = readdir($handle)) !== false)
						{
							if (($file != '.') && ($file != '..') && strpos($file, 'com_cmgiftcard_code') !== false)
							{
								File::delete($folderPath . $file);
							}
						}

						closedir($handle);
					}

					echo new JsonResponse(null, Text::sprintf('COM_CMGIFTCARD_TOOLS_CODE_IMPORT_SUCCESS', $successes, count($codes)));
				}
			}
			else
			{
				echo new JsonResponse(null, Text::_('COM_CMGIFTCARD_TOOLS_CODE_FILE_NOT_FOUND'), true);
			}
		}
		else
		{
			echo new JsonResponse(null, Text::_('COM_CMGIFTCARD_TOOLS_CODE_FILE_NOT_FOUND'), true);
		}

		$app->setUserState('com_cmgiftcard.tools.code_file', null);

		return true;
	}
}
