<?php

namespace App\Models;

use CodeIgniter\Model;

/**
 * AdminModel — manages admin_users table.
 */
class AdminModel extends Model
{
    protected $table            = 'admin_users';
    protected $primaryKey       = 'id';
    protected $useSoftDeletes   = true;
    protected $useTimestamps    = true;
    protected $createdField     = 'created_at';
    protected $updatedField     = 'updated_at';
    protected $deletedField     = 'deleted_at';

    protected $allowedFields = [
        'name', 'email', 'password', 'role',
        'is_active', 'last_login', 'reset_token', 'reset_expires',
    ];

    protected $returnType = 'array';

    protected $validationRules = [
        'name'  => 'required|min_length[2]|max_length[150]',
        'email' => 'required|valid_email|max_length[191]',
    ];

    // ----------------------------------------------------------------
    // Authentication helpers
    // ----------------------------------------------------------------

    /**
     * Find active admin by email.
     */
    public function findByEmail(string $email): ?array
    {
        return $this->where('email', $email)
                    ->where('is_active', 1)
                    ->first();
    }

    /**
     * Update last_login timestamp.
     */
    public function touchLogin(int $id): void
    {
        $this->update($id, ['last_login' => date('Y-m-d H:i:s')]);
    }

    /**
     * Store password-reset token.
     */
    public function setResetToken(int $id, string $token, string $expires): void
    {
        $this->update($id, [
            'reset_token'   => $token,
            'reset_expires' => $expires,
        ]);
    }

    /**
     * Find admin by valid (unexpired) reset token.
     */
    public function findByResetToken(string $token): ?array
    {
        return $this->where('reset_token', $token)
                    ->where('reset_expires >', date('Y-m-d H:i:s'))
                    ->first();
    }

    /**
     * Clear reset token after successful reset.
     */
    public function clearResetToken(int $id): void
    {
        $this->update($id, ['reset_token' => null, 'reset_expires' => null]);
    }
}
