<?php

namespace App\Models;

use Exception;
use CodeIgniter\Model;

class UsersModel extends Model
{
    protected $table            = 'aspnetusers';
    protected $primaryKey       = 'Id';
    // protected $useAutoIncrement = false;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    protected $allowedFields    = [
        'Id', 'Email', 'EmailConfirmed', 'PasswordHash', 'SecurityStamp', 'PhoneNumber', 'PhoneNumberConfirmed', 'TwoFactorEnabled', 'LockoutEndDateUtc', 'LockoutEnabled', 'AccessFailedCount', 'UserName', 'Role'
    ];

    protected bool $allowEmptyInserts = false;

    // Dates
    protected $useTimestamps = false;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    // Validation
    protected $validationRules      = [];
    protected $validationMessages   = [];
    protected $skipValidation       = false;
    protected $cleanValidationRules = true;

    // Callbacks
    protected $allowCallbacks = true;
    protected $beforeInsert   = [];
    protected $afterInsert    = [];
    protected $beforeUpdate   = [];
    protected $afterUpdate    = [];
    protected $beforeFind     = [];
    protected $afterFind      = [];
    protected $beforeDelete   = [];
    protected $afterDelete    = [];

    public function findUserByEmailAddress(string $emailAddress)
    {
        $user = $this
            ->asArray()
            ->where(['Email' => $emailAddress])
            ->first();

        if (!$user)
            throw new Exception('User does not exist for specified email address');

        return $user;
    }

    public function findUserByPhoneNumber(string $phoneNumber)
    {
        $user = $this
            ->asArray()
            ->where(['phoneNumber' => $phoneNumber])
            ->first();
        return $user;
    }

    public function findUserById(string $id)
    {
        $user = $this
            ->asArray()
            ->where(['Id' => $id])
            ->first();

        if (!$user)
            throw new Exception('User does not exist for specified id');

        return $user;
    }
}
