<?php

namespace App\Models;

use CodeIgniter\Model;

class LoginOtpModel extends Model
{
    protected $table = 'login_otps';
    protected $primaryKey = 'id';
    protected $useTimestamps = false;
    protected $allowedFields = ['user_id', 'code', 'is_used', 'expires_at', 'created_at'];

    /** توليد كود جديد من 6 أرقام صالح لمدة 10 دقائق */
    public function generate(int $userId): string
    {
        $code = (string) random_int(100000, 999999);

        $this->insert([
            'user_id' => $userId,
            'code' => $code,
            'is_used' => 0,
            'expires_at' => date('Y-m-d H:i:s', strtotime('+10 minutes')),
            'created_at' => date('Y-m-d H:i:s'),
        ]);

        return $code;
    }

    public function verify(int $userId, string $code): bool
    {
        $row = $this->where('user_id', $userId)
            ->where('code', $code)
            ->where('is_used', 0)
            ->orderBy('id', 'DESC')
            ->first();

        if (! $row) return false;
        if (strtotime($row['expires_at']) < time()) return false;

        $this->update($row['id'], ['is_used' => 1]);
        return true;
    }
}
