<?php

namespace Modules\Auth\Models;

use CodeIgniter\Model;

class PasswordResetModel extends Model
{
    protected $table         = 'password_resets';
    protected $primaryKey    = 'id';
    protected $returnType    = 'array';
    protected $useTimestamps = false;

    protected $allowedFields = [
        'user_id', 'token_hash', 'ip_address', 'expires_at', 'used_at', 'created_at',
    ];

    public function createToken(int $userId, string $plainToken, string $ip, int $ttlMinutes): void
    {
        // Invalidate any previous unused tokens for this user first.
        $this->where('user_id', $userId)->where('used_at', null)->set('used_at', date('Y-m-d H:i:s'))->update();

        $this->insert([
            'user_id'    => $userId,
            'token_hash' => hash('sha256', $plainToken),
            'ip_address' => $ip,
            'expires_at' => date('Y-m-d H:i:s', time() + ($ttlMinutes * 60)),
            'created_at' => date('Y-m-d H:i:s'),
        ]);
    }

    public function findValidToken(string $plainToken): ?array
    {
        $row = $this->where('token_hash', hash('sha256', $plainToken))
            ->where('used_at', null)
            ->where('expires_at >=', date('Y-m-d H:i:s'))
            ->first();

        return $row ?: null;
    }

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