<?php
declare(strict_types=1);

namespace App\Model\Table;

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

/**
 * Users Model
 *
 * @property \App\Model\Table\BlogArticlesTable&\Cake\ORM\Association\HasMany $BlogArticles
 * @property \App\Model\Table\OrdersTable&\Cake\ORM\Association\HasMany $Orders
 * @property \App\Model\Table\UserPreferencesTable&\Cake\ORM\Association\HasMany $UserPreferences
 * @method \App\Model\Entity\User newEmptyEntity()
 * @method \App\Model\Entity\User newEntity(array $data, array $options = [])
 * @method \App\Model\Entity\User[] newEntities(array $data, array $options = [])
 * @method \App\Model\Entity\User get(mixed $primaryKey, array|string $finder = 'all', \Psr\SimpleCache\CacheInterface|string|null $cache = null, \Closure|string|null $cacheKey = null, mixed ...$args)
 * @method \App\Model\Entity\User findOrCreate($search, ?callable $callback = null, array $options = [])
 * @method \App\Model\Entity\User patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
 * @method \App\Model\Entity\User[] patchEntities(iterable $entities, array $data, array $options = [])
 * @method \App\Model\Entity\User|false save(\Cake\Datasource\EntityInterface $entity, array $options = [])
 * @method \App\Model\Entity\User saveOrFail(\Cake\Datasource\EntityInterface $entity, array $options = [])
 * @method \App\Model\Entity\User[]|\Cake\Datasource\ResultSetInterface|false saveMany(iterable $entities, array $options = [])
 * @method \App\Model\Entity\User[]|\Cake\Datasource\ResultSetInterface saveManyOrFail(iterable $entities, array $options = [])
 * @method \App\Model\Entity\User[]|\Cake\Datasource\ResultSetInterface|false deleteMany(iterable $entities, array $options = [])
 * @method \App\Model\Entity\User[]|\Cake\Datasource\ResultSetInterface deleteManyOrFail(iterable $entities, array $options = [])
 * @mixin \Cake\ORM\Behavior\TimestampBehavior
 * @mixin \App\Model\Behavior\CanAuthenticateBehavior
 */
class UsersTable extends Table
{
    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config): void
    {
        parent::initialize($config);

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

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

        // Existing association
        $this->hasMany('BlogArticles', [
            'foreignKey' => 'user_id',
        ]);

        // ✅ New associations for customer orders and preferences
        $this->hasMany('Orders', [
            'foreignKey' => 'user_id',
            'dependent' => true, // delete user → delete their orders
        ]);

        $this->hasMany('UserPreferences', [
            'foreignKey' => 'user_id',
            'dependent' => true, // delete user → delete their preferences
        ]);
    }

    /**
     * Default validation rules.
     *
     * @param \Cake\Validation\Validator $validator Validator instance.
     * @return \Cake\Validation\Validator
     */
    public function validationDefault(Validator $validator): Validator
    {
        $validator
            ->email('email')
            ->requirePresence('email', 'create')
            ->notEmptyString('email', 'Email is required');

        $validator
            ->scalar('password')
            ->requirePresence('password', 'create')
            ->notEmptyString('password', 'Password is required');

            
        $validator
            ->requirePresence('password_confirm', 'create')
            ->sameAs('password_confirm', 'password', 'Both passwords must match');

        $validator
            ->scalar('first_name')
            ->maxLength('first_name', 128)
            ->requirePresence('first_name', 'create')
            ->notEmptyString('first_name', 'First name is required');

        $validator
            ->scalar('last_name')
            ->maxLength('last_name', 128)
            ->requirePresence('last_name', 'create')
            ->notEmptyString('last_name', 'Last name is required');

        $validator
            ->scalar('avatar')
            ->allowEmptyString('avatar');

        $validator
            ->allowEmptyString('reset_token', null, 'create')
            ->allowEmptyDateTime('token_expiry', null, 'create');

        // ✅ Optional new profile fields
        $validator
            ->scalar('phone')
            ->maxLength('phone', 30)
            ->allowEmptyString('phone');

        $validator
            ->date('date_of_birth')
            ->allowEmptyDate('date_of_birth');

        return $validator;
    }

    /**
     * Rules checker for unique email etc.
     */
    public function buildRules(RulesChecker $rules): RulesChecker
    {
        $rules->add($rules->isUnique(['email']), ['errorField' => 'email']);
      
        return $rules;
    }

    /**
     * Finder for Authentication plugin
     */
    public function findAuth(\Cake\ORM\Query $query, array $options): \Cake\ORM\Query
    {
        $query
            ->select(['id', 'email', 'password', 'role'])
            ->where(['Users.email IS NOT' => null]);
            
        return $query;
    }
}

