<?php

namespace App\Models;

use CodeIgniter\Model;

class TrustedDeviceModel extends Model
{
    protected $table = 'trusted_devices';
    protected $primaryKey = 'id';
    protected $useTimestamps = false;
    protected $allowedFields = ['user_id', 'token', 'device_label', 'created_at', 'last_used_at'];

    public function isTrusted(int $userId, ?string $token): bool
    {
        if (! $token) return false;

        $row = $this->where('user_id', $userId)->where('token', $token)->first();
        if (! $row) return false;

        $this->update($row['id'], ['last_used_at' => date('Y-m-d H:i:s')]);
        return true;
    }

    public function trust(int $userId, string $deviceLabel = ''): string
    {
        $token = bin2hex(random_bytes(32));

        $this->insert([
            'user_id' => $userId,
            'token' => $token,
            'device_label' => $deviceLabel,
            'created_at' => date('Y-m-d H:i:s'),
            'last_used_at' => date('Y-m-d H:i:s'),
        ]);

        return $token;
    }
}
