<?php

// app/Models/RfidCard.php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class RfidCard extends Model
{
    use HasFactory;

    protected $fillable = [
        'card_number', 'merchant_id', 'issued_date', 'expiry_date',
        'status', 'blocked_reason', 'metadata',
    ];

    protected $casts = [
        'issued_date' => 'date',
        'expiry_date' => 'date',
        'metadata' => 'array',
    ];

    const STATUS = [
        'active' => 'Ativo',
        'blocked' => 'Bloqueado',
        'expired' => 'Expirado',
        'lost' => 'Perdido',
    ];

    public function merchant()
    {
        return $this->belongsTo(Merchant::class);
    }

    public function movements()
    {
        return $this->hasMany(RfidMovement::class);
    }

    public function payments()
    {
        return $this->hasMany(Payment::class);
    }

    public function scopeActive($query)
    {
        return $query->where('status', 'active')
            ->where('expiry_date', '>=', now());
    }

    public function block(?string $reason = null)
    {
        $this->update([
            'status' => 'blocked',
            'blocked_reason' => $reason,
        ]);

        $this->movements()->create([
            'movement_type' => 'block',
            'metadata' => ['reason' => $reason],
        ]);

        return $this;
    }
}
