<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;use App\Models\Concerns\BelongsToCompany;


class Asset extends Model
{
    use SoftDeletes, LogsActivity, BelongsToCompany;

    protected $fillable = [
        'code','name','serial_number','category_id','model_id','status',
        'location','department_id','assigned_to','purchase_date','purchase_price',
        'warranty_until','notes','qr_code'
    ];

    protected function casts(): array {
        return [
            'purchase_date'  => 'date',
            'warranty_until' => 'date',
            'purchase_price' => 'decimal:2',
        ];
    }

    public static array $statuses = [
        'active'         => ['label' => 'Activo',          'color' => 'bg-green-100 text-green-800'],
        'in_repair'      => ['label' => 'En Reparación',   'color' => 'bg-yellow-100 text-yellow-800'],
        'in_storage'     => ['label' => 'En Almacén',      'color' => 'bg-gray-100 text-gray-800'],
        'decommissioned' => ['label' => 'Dado de Baja',    'color' => 'bg-red-100 text-red-800'],
        'on_loan'        => ['label' => 'En Préstamo',     'color' => 'bg-blue-100 text-blue-800'],
    ];

    // ── Relaciones ────────────────────────────────────────────────────────────
    public function category(): BelongsTo     { return $this->belongsTo(AssetCategory::class); }
    public function model(): BelongsTo        { return $this->belongsTo(AssetModel::class); }
    public function department(): BelongsTo   { return $this->belongsTo(Department::class); }
    public function assignedUser(): BelongsTo { return $this->belongsTo(User::class, 'assigned_to'); }
    public function fieldValues(): HasMany    { return $this->hasMany(AssetFieldValue::class); }
    public function assignments(): HasMany    { return $this->hasMany(AssetAssignment::class)->latest(); }
    public function interventions(): HasMany  { return $this->hasMany(AssetIntervention::class)->latest(); }
    public function tickets(): HasMany        { return $this->hasMany(Ticket::class); }

    // ── Scopes ────────────────────────────────────────────────────────────────
    public function scopeActive($q)     { return $q->where('status', 'active'); }
    public function scopeAssigned($q)   { return $q->whereNotNull('assigned_to'); }
    public function scopeUnassigned($q) { return $q->whereNull('assigned_to'); }

    // ── Helpers ───────────────────────────────────────────────────────────────
    public static function generateCode(): string {
        $last = static::withTrashed()->orderBy('id', 'desc')->first();
        $next = $last ? ((int) substr($last->code, 4)) + 1 : 1;
        return 'ACT-' . str_pad($next, 4, '0', STR_PAD_LEFT);
    }

    public function getStatusLabelAttribute(): string {
        return self::$statuses[$this->status]['label'] ?? $this->status;
    }

    public function getStatusColorAttribute(): string {
        return self::$statuses[$this->status]['color'] ?? 'bg-gray-100 text-gray-800';
    }

    public function isWarrantyExpired(): bool {
        return $this->warranty_until && $this->warranty_until->isPast();
    }

    public function isWarrantyExpiringSoon(): bool {
        return $this->warranty_until
            && !$this->warranty_until->isPast()
            && $this->warranty_until->diffInDays(now()) <= 30;
    }

    // Obtener valor de campo personalizado
    public function getFieldValue(int $fieldId): ?string {
        return $this->fieldValues->where('field_id', $fieldId)->first()?->value;
    }

    public function getActivitylogOptions(): LogOptions {
        return LogOptions::defaults()
            ->logOnly(['name', 'status', 'assigned_to', 'location'])
            ->logOnlyDirty()
            ->setDescriptionForEvent(fn($e) => "Activo {$this->code}: {$e}");
    }
}
