<?php

namespace App\Models;

use CodeIgniter\Model;

class ApiTokenModel extends Model
{
    protected $table            = 'api_tokens';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $useTimestamps    = false;

    protected $allowedFields = [
        'user_id', 'church_id', 'token_hash', 'expires_at', 'last_used_at',
        'is_platform_admin', 'platform_admin_id',
    ];

    public function findByHash(string $hash): ?array
    {
        return $this->where('token_hash', $hash)
                    ->where('expires_at >', date('Y-m-d H:i:s'))
                    ->first();
    }

    public function touch(int $id): void
    {
        $this->update($id, ['last_used_at' => date('Y-m-d H:i:s')]);
    }
}
