<?php

namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{
    protected $table = 'users';
    protected $primaryKey = 'id';
    protected $allowedFields = [
        'email', 'password_hash', 'first_name', 'last_name', 'phone',
        'role', 'is_active', 'last_login', 'failed_attempts', 'locked_until', 'remember_token'
    ];
    protected $returnType = 'array';
    protected $useTimestamps = true;
    protected $useSoftDeletes = true;

    protected $validationRules = [
        'email' => 'required|valid_email|is_unique[users.email,id,{id}]',
        'password_hash' => 'required',
        'first_name' => 'required|min_length[2]|max_length[100]',
        'last_name' => 'required|min_length[2]|max_length[100]',
        'role' => 'required|in_list[admin,comptable,manager,lecture]',
    ];

    public function findByEmail(string $email): ?array
    {
        return $this->where('email', $email)->where('is_active', 1)->first();
    }

    public function updateLogin(int $id): bool
    {
        return $this->update($id, [
            'last_login' => date('Y-m-d H:i:s'),
            'failed_attempts' => 0,
            'locked_until' => null,
        ]);
    }

    public function incrementFailedAttempts(int $id): bool
    {
        $user = $this->find($id);
        if (!$user) return false;

        $attempts = ($user['failed_attempts'] ?? 0) + 1;
        $data = ['failed_attempts' => $attempts];

        if ($attempts >= 5) {
            $data['locked_until'] = date('Y-m-d H:i:s', strtotime('+30 minutes'));
        }

        return $this->update($id, $data);
    }

    public function isLocked(int $id): bool
    {
        $user = $this->find($id);
        if (!$user || empty($user['locked_until'])) return false;
        return strtotime($user['locked_until']) > time();
    }
}
