<?php

namespace App\Models;

use CodeIgniter\Model;

class IpAttemptModel extends Model
{
    protected $table = 'ip_attempts';
    protected $primaryKey = 'id';

    protected $allowedFields = [
        'ip_address',
        'attempts',
        'last_attempt_at',
        'blocked_until'
    ];

    // Automatically handle timestamps
    protected $useTimestamps = true;
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';

    // Validation rules
    protected $validationRules = [
        'ip_address' => 'required|valid_ip|max_length[45]',
        'attempts'   => 'required|integer',
        'last_attempt_at' => 'required|valid_date',
        'blocked_until' => 'permit_empty|valid_date'
    ];

    // Method to get IP attempt data by IP address
    public function getAttemptByIp($ip)
    {
        return $this->where('ip_address', $ip)->first();
    }

    // Method to update the IP attempt data
    public function updateIpAttempt($ip, $data)
    {
        return $this->where('ip_address', $ip)->set($data)->update();
    }

    // Method to insert new IP attempt data
    public function insertIpAttempt($data)
    {
        return $this->insert($data);
    }
}
