<?php

/**
 * @package         Tassos Code Snippets
 * @version         1.0.1-RC2 Free
 *
 * @author          Tassos Marinos <info@tassos.gr>
 * @link            https://www.tassos.gr
 * @copyright       Copyright © 2026 Tassos Marinos All Rights Reserved
 * @license         GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> or later
 */

namespace Tassos\CodeSnippets\Administrator\Table;

defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\Filter\OutputFilter;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Table\Table;
use Joomla\CMS\Tag\TaggableTableInterface;
use Joomla\CMS\Tag\TaggableTableTrait;
use Joomla\CMS\Versioning\VersionableTableInterface;
use Joomla\Database\DatabaseDriver;

/**
 * Snippet table class.
 */
class SnippetTable extends Table implements TaggableTableInterface, VersionableTableInterface
{
    use TaggableTableTrait;

    /**
     * The type alias for this content type.
     *
     * @var    string
     */
    public $typeAlias = 'com_tassoscodesnippets.snippet';

    /**
     * Constructor
     *
     * @param   DatabaseDriver  $db  Database connector object
     */
    public function __construct(DatabaseDriver $db)
    {
        $this->setColumnAlias('published', 'state');

        parent::__construct('#__tassos_codesnippets', 'id', $db);
    }

    /**
     * Overloaded check function.
     *
     * @return  boolean  True if the row is valid, false otherwise.
     */
    public function check()
    {
        try
        {
            parent::check();
        }
        catch (\Exception $e)
        {
            $this->setError($e->getMessage());
            return false;
        }

        // Check for a title
        if (trim($this->title) == '')
        {
            $this->setError(Text::_('COM_TASSOSCODESNIPPETS_WARNING_TITLE_REQUIRED'));
            return false;
        }

        // Generate alias from title if empty
        if (empty($this->alias))
        {
            $this->alias = $this->title;
        }

        $this->alias = OutputFilter::stringURLSafe($this->alias);

        // Set ordering
        if ($this->state < 0)
        {
            $this->ordering = 0;
        }
        elseif (empty($this->ordering))
        {
            // Get the largest ordering value for this category
            $db    = $this->getDbo();
            $query = $db->getQuery(true)
                ->select('MAX(' . $db->quoteName('ordering') . ')')
                ->from($db->quoteName('#__tassos_codesnippets'))
                ->where($db->quoteName('catid') . ' = ' . (int) $this->catid);

            $db->setQuery($query);
            $max = $db->loadResult();

            $this->ordering = $max + 1;
        }

        return true;
    }

    /**
     * Method to store a row in the database.
     *
     * @param   boolean  $updateNulls  True to update fields even if they are null.
     *
     * @return  boolean  True on success.
     */
    public function store($updateNulls = true)
    {
        $date = Factory::getDate()->toSql();
        $user = Factory::getApplication()->getIdentity();

        // Set created date if not set
        if (empty($this->created) || $this->created === $this->getDbo()->getNullDate())
        {
            $this->created = $date;
        }

        // Set modified date
        $this->modified = $date;

        if ($this->id)
        {
            // Existing item
            $this->modified_by = $user->get('id');
        }
        else
        {
            // New item
            if (empty($this->created_by))
            {
                $this->created_by = $user->get('id');
            }
        }

        return parent::store($updateNulls);
    }

    /**
     * Get the type alias for content type
     *
     * @return  string  The type alias
     */
    public function getTypeAlias()
    {
        return $this->typeAlias;
    }
}
