<?php
declare(strict_types=1);

namespace App\Model\Table;

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

class BookingsTable extends Table
{
    public const STATUSES = ['pending', 'paid', 'cancelled', 'refunded'];

    public function initialize(array $config): void
    {
        parent::initialize($config);

        $this->setTable('bookings');
        $this->setDisplayField('customer_name');
        $this->setPrimaryKey('id');
        $this->addBehavior('Timestamp');

        $this->belongsTo('Teachers', ['foreignKey' => 'teacher_id']);
        $this->belongsTo('AvailabilitySlots', [
            'foreignKey' => 'slot_id',
            'propertyName' => 'slot',
        ]);
    }

    public function validationDefault(Validator $validator): Validator
    {
        $validator
            ->requirePresence('customer_name', 'create')
            ->notEmptyString('customer_name')
            ->maxLength('customer_name', 150);

        $validator
            ->email('customer_email')
            ->requirePresence('customer_email', 'create')
            ->notEmptyString('customer_email');

        $validator
            ->allowEmptyString('customer_phone')
            ->maxLength('customer_phone', 60);

        $validator
            ->integer('slot_id')
            ->requirePresence('slot_id', 'create');

        $validator
            ->integer('teacher_id')
            ->requirePresence('teacher_id', 'create');

        $validator
            ->scalar('status')
            ->inList('status', self::STATUSES);

        return $validator;
    }
}
