<?php

namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{
    protected $table = 'users';
    protected $primaryKey = 'id';
    protected $useAutoIncrement = true;
    protected $returnType = 'array';
    protected $useSoftDeletes = false;
    protected $allowedFields = ['email', 'password', 'full_name', 'role', 'status'];
    protected $useTimestamps = true;
    protected $createdField = 'created_at';
    protected $updatedField = 'updated_at';

    // Validation rules
    protected $validationRules = [
        'email' => 'required|valid_email|is_unique[users.email]',
        'password' => 'required|min_length[6]',
        'full_name' => 'required',
        'role' => 'required|in_list[admin,finance,member]',
    ];

    protected $validationMessages = [
        'email' => [
            'required' => 'Email required',
            'valid_email' => 'Email invalid',
            'is_unique' => 'Email already exists',
        ],
    ];

    public function findByEmail($email)
    {
        return $this->where('email', $email)->first();
    }

    public function authenticate($email, $password)
    {
        $user = $this->findByEmail($email);
        if ($user && password_verify($password, $user['password'])) {
            return $user;
        }
        return null;
    }
}
