<?php

namespace App\Models;

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

class Collateral extends Model
{
    public const STATUSES = [
        'pending_inspection',
        'accepted',
        'in_custody',
        'ready_for_release',
        'released',
        'repossessed',
        'scheduled_for_sale',
        'sold',
        'returned',
    ];

    protected $fillable = [
        'customer_id', 'branch_id', 'category_id', 'sequence_number', 'code', 'item',
        'brand', 'model', 'serial_number', 'colour', 'description', 'estimated_value',
        'accepted_value', 'condition', 'received_at', 'store_room', 'shelf',
        'received_by', 'status', 'created_by', 'updated_by',
    ];

    protected static function booted(): void
    {
        static::updating(function (Collateral $collateral): void {
            foreach (['code', 'sequence_number', 'branch_id', 'customer_id'] as $field) {
                if ($collateral->isDirty($field)) {
                    $collateral->setAttribute($field, $collateral->getOriginal($field));
                }
            }
        });
    }

    protected function casts(): array
    {
        return [
            'received_at' => 'date',
            'estimated_value' => 'decimal:2',
            'accepted_value' => 'decimal:2',
        ];
    }

    public function customer(): BelongsTo { return $this->belongsTo(Customer::class); }
    public function branch(): BelongsTo { return $this->belongsTo(Branch::class); }
    public function category(): BelongsTo { return $this->belongsTo(CollateralCategory::class, 'category_id'); }
    public function receiver(): BelongsTo { return $this->belongsTo(User::class, 'received_by'); }
    public function creator(): BelongsTo { return $this->belongsTo(User::class, 'created_by'); }
    public function loans(): BelongsToMany { return $this->belongsToMany(Loan::class, 'loan_collateral')->withTimestamps(); }
    public function files(): HasMany { return $this->hasMany(CollateralFile::class); }
    public function movements(): HasMany { return $this->hasMany(CollateralMovement::class)->orderByDesc('moved_at')->orderByDesc('id'); }

    public function getStorageLocationAttribute(): string
    {
        return collect([$this->branch?->name, $this->store_room, $this->shelf])->filter()->join(' → ');
    }
}
