<?php
declare(strict_types=1);

namespace App\Model\Table;

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

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

        $this->setTable('users');
        $this->setDisplayField('email');
        $this->setPrimaryKey('id');

        $this->addBehavior('Timestamp');
    }

    public function validationDefault(Validator $validator): Validator
    {
        $validator
            ->email('email')
            ->requirePresence('email', 'create')
            ->notEmptyString('email', 'Email is required')
            ->add('email', 'unique', [
                'rule' => 'validateUnique',
                'provider' => 'table',
                'message' => 'Email is already in use',
            ]);

        $validator
            ->scalar('password')
            ->minLength('password', 6, 'Password must be at least 6 characters')
            ->requirePresence('password', 'create')
            ->notEmptyString('password', 'Password is required');

        $validator
            ->add('password_confirm', 'compareWithPassword', [
                'rule' => ['compareWith', 'password'],
                'message' => 'Passwords do not match',
            ])
            ->notEmptyString('password_confirm', 'Please confirm your password');

        // Make first_name optional
        $validator
            ->allowEmptyString('first_name')  // Changed to allow empty
            ->scalar('first_name')
            ->maxLength('first_name', 255);  // Max length validation, if you prefer

        // Make last_name optional
        $validator
            ->allowEmptyString('last_name')  // Changed to allow empty
            ->scalar('last_name')
            ->maxLength('last_name', 255);  // Max length validation, if you prefer

        $validator
            ->scalar('nonce')
            ->maxLength('nonce', 255)
            ->allowEmptyString('nonce');

        $validator
            ->dateTime('nonce_expiry')
            ->allowEmptyDateTime('nonce_expiry');

        return $validator;
    }

    public function buildRules(RulesChecker $rules): RulesChecker
    {
        $rules->add($rules->isUnique(['email']), ['errorField' => 'email']);
        return $rules;
    }
}
