<?php
/**
 * @package         ReReplacer
 * @version         12.4.0PRO
 * 
 * @author          Peter van Westen <info@regularlabs.com>
 * @link            http://regularlabs.com
 * @copyright       Copyright © 2022 Regular Labs All Rights Reserved
 * @license         http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 */

namespace RegularLabs\Component\ReReplacer\Administrator\Table;

use Exception;
use Joomla\CMS\Language\Text as JText;
use Joomla\CMS\Table\Table;
use Joomla\Database\DatabaseDriver;

defined('_JEXEC') or die;

class ItemTable extends Table
{
    /**
     * @param DatabaseDriver $db Database object.
     */
    public function __construct(DatabaseDriver $db)
    {
        parent::__construct('#__rereplacer', 'id', $db);
    }

    /**
     * Overloaded check function
     *
     * @return  boolean
     *
     * @since   1.6
     */
    public function check()
    {
        try
        {
            parent::check();
        }
        catch (Exception $e)
        {
            $this->setError($e->getMessage());

            return false;
        }

        $this->name   = trim($this->name);
        $this->search = trim($this->search);

        // Check for valid name
        if (empty($this->name))
        {
            $this->setError(JText::_('RR_THE_ITEM_MUST_HAVE_A_NAME'));

            return false;
        }

        // Check for valid search
        if (strpos($this->params, '"use_xml":"1"') !== false)
        {
            if (strpos($this->params, '"xml":""') !== false)
            {
                $this->setError(JText::_('RR_THE_ITEM_MUST_HAVE_AN_XML_FILE'));

                return false;
            }

            return true;
        }

        if (trim($this->search) == '')
        {
            $this->setError(JText::_('RR_THE_ITEM_MUST_HAVE_SOMETHING_TO_SEARCH_FOR'));

            return false;
        }

        return true;
    }
}
