<?php
namespace Joomla\Component\Panggilan\Administrator\Table;

use Joomla\CMS\Table\Table;
use Joomla\Database\DatabaseDriver;

defined('_JEXEC') or die;

class ItemTable extends Table
{
    public function __construct(DatabaseDriver $db)
    {
        parent::__construct('#__panggilan_items', 'id', $db);
        $this->setColumnAlias('published', 'state');
    }

    public function check()
    {
        // Required fields
        if (trim($this->party_name) == '') {
            $this->setError('Nama Pihak wajib diisi');
            return false;
        }
        if (trim($this->case_number) == '') {
            $this->setError('Nomor Perkara wajib diisi');
            return false;
        }
        if (trim($this->year) == '') {
            $this->setError('Tahun wajib diisi');
            return false;
        }

        // Validate URL
        if (!empty($this->file_url)) {
            $url = trim($this->file_url);

            // Check protocol
            if (!preg_match('#^https?://#i', $url)) {
                $this->setError('URL File harus dimulai dengan http:// atau https://');
                return false;
            }

            // Block javascript:
            if (stripos($url, 'javascript:') !== false) {
                $this->setError('URL tidak valid');
                return false;
            }
        }

        // Auto-fill ordering if 0
        if ($this->ordering === 0) {
            $this->ordering = self::getNextOrder();
        }

        // Set created/modified dates and users
        $date = \Joomla\CMS\Factory::getDate()->toSql();
        $user = \Joomla\CMS\Factory::getUser();

        if (empty($this->created)) {
            $this->created = $date;
            $this->created_by = $user->id;
        } else {
             // If we want to preserve original creator when editing as admin, logic is fine, 
             // but usually we set modified here.
        }

        // Always update modified
        $this->modified = $date;
        $this->modified_by = $user->id;

        // Ensure state is set
        if (empty($this->state)) {
            $this->state = 1;
        }

        return true;
    }
}
