<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class TwoFactorCode extends Model
{
    protected $fillable = ['user_id', 'code', 'attempts', 'expires_at'];

    protected $casts = [
        'expires_at' => 'datetime',
    ];

    /**
     * Relasi ke User
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Generate 6-digit OTP code
     */
    public static function generateCode(): string
    {
        return str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);
    }

    /**
     * Create OTP untuk user (expire dalam 10 menit)
     */
    public static function createForUser(User $user): self
    {
        // Hapus OTP lama jika ada
        $user->twoFactorCodes()->delete();

        return static::create([
            'user_id' => $user->id,
            'code' => static::generateCode(),
            'expires_at' => now()->addMinutes(10),
        ]);
    }

    /**
     * Check apakah OTP masih valid
     */
    public function isValid(): bool
    {
        return $this->expires_at->isFuture() && $this->attempts < 3;
    }

    /**
     * Check apakah user terkunci (3x salah)
     */
    public function isLocked(): bool
    {
        return $this->attempts >= 3;
    }

    /**
     * Increment failed attempts
     */
    public function incrementAttempts(): void
    {
        $this->increment('attempts');
    }
}
