<?php

namespace App\Models\Control;

use CodeIgniter\Model;
use Config\Lookups;

/**
 * Control DB. Platform-operator logins — see CreateAdminUsersTable for why
 * this is a completely separate account space from any tenant's UserModel.
 */
class AdminUserModel extends Model
{
    protected $table            = 'admin_users';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'object';
    protected $useTimestamps    = true;

    protected $allowedFields = [
        'full_name',
        'email',
        'password_hash',
        'role',
        'is_active',
        'last_login_at',
    ];

    public function __construct()
    {
        parent::__construct();

        $roles = array_keys((new Lookups())->adminRoles);

        $this->validationRules = [
            'full_name' => 'required|max_length[150]',
            'email'     => 'required|valid_email|max_length[150]|is_unique[admin_users.email,id,{id}]',
            'role'      => 'required|in_list[' . implode(',', $roles) . ']',
        ];
    }

    /**
     * Same null-for-any-failure shape as UserModel::verifyCredentials —
     * a login form never reveals whether the email or the password was
     * the wrong part.
     */
    public function verifyCredentials(string $email, string $password): ?object
    {
        $admin = $this->where('email', $email)->where('is_active', 1)->first();

        if ($admin === null || ! password_verify($password, $admin->password_hash)) {
            return null;
        }

        unset($admin->password_hash);

        return $admin;
    }

    public function touchLastLogin(int $id): void
    {
        $this->update($id, ['last_login_at' => date('Y-m-d H:i:s')]);
    }
}
