<?php

namespace App\Models;

use App\Models\BaseModel;

class IpAttempt extends BaseModel
{
    protected $table = 'ip_attempts';

    // ✅ CI: useTimestamps = true (created_at/updated_at)
    public $timestamps = true;

    protected $fillable = [
        'ip_address',
        'attempts',
        'last_attempt_at',
        'blocked_until',
        'created_at',
        'updated_at',
        'school_year',
        'semester',
    ];

    protected $casts = [
        'attempts'        => 'integer',
        'last_attempt_at' => 'datetime',
        'blocked_until'   => 'datetime',
    ];

    /**
     * Equivalent of CI getAttemptByIp()
     */
    public static function getAttemptByIp(string $ip): ?self
    {
        return static::query()
            ->where('ip_address', $ip)
            ->first();
    }

    /**
     * Equivalent of CI updateIpAttempt()
     */
    public static function updateIpAttempt(string $ip, array $data): bool
    {
        return static::query()
            ->where('ip_address', $ip)
            ->update($data) >= 0;
    }

    /**
     * Equivalent of CI insertIpAttempt()
     * Returns inserted id.
     */
    public static function insertIpAttempt(array $data): int
    {
        $row = static::query()->create($data);
        return (int) $row->id;
    }
}