<?php
declare(strict_types=1);

namespace App\Model\Table;

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

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

        $this->setTable('contact_messages');
        $this->setPrimaryKey('id');
        $this->addBehavior('Timestamp');
    }

    public function validationDefault(Validator $validator): Validator
    {
        $validator
            ->scalar('first_name')
            ->maxLength('first_name', 30, 'First name must be 30 characters or fewer.')
            ->requirePresence('first_name', 'create')
            ->notEmptyString('first_name', 'First name is required.');

        $validator
            ->scalar('last_name')
            ->allowEmptyString('last_name')
            ->maxLength('last_name', 30, 'Last name must be 30 characters or fewer.');

        $validator
            ->scalar('phone')
            ->maxLength('phone', 11, 'Phone number must be 11 digits or fewer.')
            ->requirePresence('phone', 'create')
            ->notEmptyString('phone', 'Phone number is required.')
            ->add('phone', 'validFormat', [
                'rule' => function ($value) {
                    return preg_match('/^\d{1,11}$/', (string)$value) === 1;
                },
                'message' => 'Phone number must contain digits only and be at most 11 digits.'
            ]);

        $validator
            ->scalar('email')
            ->allowEmptyString('email')
            ->maxLength('email', 40, 'Email must be 40 characters or fewer.')
            ->email('email', false, 'Please enter a valid email address.');

        $validator
            ->scalar('message')
            ->requirePresence('message', 'create')
            ->notEmptyString('message', 'Message is required.');

        return $validator;
    }
}