<?php
declare(strict_types=1);

namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\Validation\Validator;
use Cake\ORM\RulesChecker;

class FaqsTable extends Table
{
    public function initialize(array $config): void
    {
        parent::initialize($config);

        $this->setTable('faqs');
        $this->setDisplayField('question');
        $this->setPrimaryKey('id');

        $this->addBehavior('Timestamp', [
            'events' => [
                'Model.beforeSave' => [
                    'created_at' => 'new',
                    'updated_at' => 'existing',
                ],
            ],
        ]);
    }

    public function validationDefault(Validator $validator): Validator
    {
        $validator
            ->scalar('category')
            ->maxLength('category', 255)
            ->requirePresence('category', 'create')
            ->notEmptyString('category', 'Category is required.');

        $validator
            ->scalar('question')
            ->requirePresence('question', 'create')
            ->notEmptyString('question', 'Question is required.')
            ->maxLength('question', 2000, 'Too long.');

        $validator
            ->scalar('answer')
            ->requirePresence('answer', 'create')
            ->notEmptyString('answer', 'Answer is required.')
            ->maxLength('answer', 10000, 'Too long.');

        $validator
            ->scalar('link')
            ->allowEmptyString('link')
            ->maxLength('link', 2000, 'URL is too long.')
            ->add('link', 'validUrl', [
                'rule' => function ($value) {
                    if ($value === null || $value === '') return true;
                    if (!filter_var($value, FILTER_VALIDATE_URL)) return false;
                    $scheme = parse_url($value, PHP_URL_SCHEME);
                    return in_array(strtolower((string)$scheme), ['http','https'], true);
                },
                'message' => 'Please enter a valid http/https URL.',
            ]);

        $validator
            ->scalar('tags')
            ->allowEmptyString('tags')
            ->maxLength('tags', 2000, 'Too long.')
            ->add('tags', 'validCsvTags', [
                'rule' => function ($value) {
                    if ($value === null || $value === '') return true;
                    $parts = array_filter(array_map('trim', explode(',', strtolower($value))));
                    foreach ($parts as $p) {
                        if ($p === '') continue;
                        if (strlen($p) > 32) return false;
                        if (!preg_match('/^[a-z0-9-]+$/', $p)) return false;
                    }
                    return true;
                },
                'message' => 'Tags must be comma-separated, using [a-z0-9-], each ≤ 32 characters.',
            ]);

        $validator->dateTime('created_at')->allowEmptyDateTime('created_at');
        $validator->dateTime('updated_at')->allowEmptyDateTime('updated_at');

        return $validator;
    }

    public function buildRules(RulesChecker $rules): RulesChecker
    {
        $rules->add($rules->isUnique(
            ['category', 'question'],
            'This question already exists under the same category.'
        ));
        return $rules;
    }
}
