<?php
declare(strict_types=1);

namespace App\Model\Table;

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

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

        $this->setTable('participant_contacts');
        $this->setPrimaryKey('id');

        $this->belongsTo('Participants', [
            'foreignKey' => 'participant_id',
            'joinType'   => 'INNER',
        ]);

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

    public function validationDefault(Validator $v): Validator
    {
        $v->requirePresence('type', 'create')
            ->inList('type', ['phone','email']);

        $v->scalar('label')->maxLength('label', 20);

        $v->requirePresence('value', 'create')->notEmptyString('value');

        $v->add('value', 'format', [
            'rule' => function ($val, $ctx) {
                $type = $ctx['data']['type'] ?? '';
                if ($type === 'email') {
                    return (bool)filter_var($val, FILTER_VALIDATE_EMAIL);
                }
                return (bool)preg_match('/^\+?\d[\d\s\-]{7,15}$/', $val);
            },
            'message' => 'Please enter a valid value.',
        ]);

        $v->boolean('is_primary')
        ->boolean('is_emergency')->allowEmptyString('is_emergency');

        return $v;
    }

    public function buildRules(RulesChecker $rules): RulesChecker
    {
        $rules->add($rules->existsIn('participant_id', 'Participants'));
        return $rules;
    }
}
