<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class EmployeeCard extends Model
{
    use HasFactory, HasUuids;

    public $incrementing = false;
    protected $keyType = 'string';

    protected $fillable = [
        'user_id',
        'company_id',
        'card_number',
        'qr_payload',
        'qr_signature',
        'card_status',
        'issued_at',
        'expires_at',
        'revoked_at',
        'revoked_reason',
    ];

    protected function casts(): array
    {
        return [
            'qr_payload' => 'array',
            'issued_at' => 'datetime',
            'expires_at' => 'datetime',
            'revoked_at' => 'datetime',
        ];
    }

    /**
     * Get the user that owns the card.
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Get the company that owns the card.
     */
    public function company(): BelongsTo
    {
        return $this->belongsTo(Company::class);
    }

    /**
     * Scope a query to only include active cards.
     */
    public function scopeActive($query)
    {
        return $query->where('card_status', 'active');
    }

    /**
     * Scope a query to only include revoked cards.
     */
    public function scopeRevoked($query)
    {
        return $query->where('card_status', 'revoked');
    }

    /**
     * Scope a query to only include expired cards.
     */
    public function scopeExpired($query)
    {
        return $query->where('card_status', 'expired');
    }

    /**
     * Check if the card is valid (active and not expired).
     */
    public function isValid(): bool
    {
        if ($this->card_status !== 'active') {
            return false;
        }

        if ($this->expires_at && $this->expires_at->isPast()) {
            return false;
        }

        return true;
    }

    /**
     * Revoke the card.
     */
    public function revoke(string $reason = null): bool
    {
        return $this->update([
            'card_status' => 'revoked',
            'revoked_at' => now(),
            'revoked_reason' => $reason,
        ]);
    }

    /**
     * Get the full QR data as JSON string for encoding.
     */
    public function getQrDataAttribute(): string
    {
        return json_encode([
            'payload' => $this->qr_payload,
            'signature' => $this->qr_signature,
        ]);
    }
}
