<?php

namespace App\Models;

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

class DamagedItem extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'item_id',
        'quantity',
        'unit',
        'unit_cost',
        'total_cost',
        'source_type',
        'source_reference',
        'project_id',
        'project_details',
        'inventory_id',
        'inventory_reference',
        'damage_description',
        'damage_severity',
        'damage_notes',
        'cost_responsibility',
        'status',
        'recoverable_amount',
        'loss_amount',
        'reported_by',
        'approved_by',
        'reported_at',
        'approved_at',
        'attachments',
        'resolution_notes',
        'disposal_method',
        'disposed_at',
    ];

    protected $casts = [
        'quantity' => 'decimal:4',
        'unit_cost' => 'decimal:4',
        'total_cost' => 'decimal:4',
        'recoverable_amount' => 'decimal:4',
        'loss_amount' => 'decimal:4',
        'reported_at' => 'datetime',
        'approved_at' => 'datetime',
        'disposed_at' => 'datetime',
        'attachments' => 'array',
    ];

    protected $dates = [
        'reported_at',
        'approved_at',
        'disposed_at',
        'deleted_at',
    ];

    // Relationships
    public function item(): BelongsTo
    {
        return $this->belongsTo(\App\Models\Warehouse\Item::class);
    }

    public function project(): BelongsTo
    {
        return $this->belongsTo(\App\Models\Warehouse\Project::class);
    }

    public function inventory(): BelongsTo
    {
        return $this->belongsTo(\App\Models\Warehouse\Inventory::class);
    }

    public function reportedBy(): BelongsTo
    {
        return $this->belongsTo(\App\Models\User::class, 'reported_by');
    }

    public function approvedBy(): BelongsTo
    {
        return $this->belongsTo(\App\Models\User::class, 'approved_by');
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(\App\Models\User::class, 'reported_by');
    }

    // Scopes
    public function scopeBySeverity($query, $severity)
    {
        return $query->where('damage_severity', $severity);
    }

    public function scopeByStatus($query, $status)
    {
        return $query->where('status', $status);
    }

    public function scopeBySource($query, $sourceType)
    {
        return $query->where('source_type', $sourceType);
    }

    public function scopeByProject($query, $projectId)
    {
        return $query->where('project_id', $projectId);
    }

    // Helper methods
    public function getTotalLossAttribute()
    {
        return $this->total_cost - $this->recoverable_amount;
    }

    public function isRecoverable()
    {
        return $this->recoverable_amount > 0;
    }

    public function canBeApproved()
    {
        return $this->status === 'reported';
    }
}
