<?php

namespace App\Models;

use App\Support\FixedAssetOptions;

class FixedAsset extends BaseModel
{
    protected $fillable = [
        'company_id', 'category_id', 'code', 'name', 'location', 'serial_number',
        'purchase_date', 'in_service_date', 'purchase_cost', 'salvage_value',
        'useful_life_months', 'depreciation_method',
        'asset_account_id', 'accum_depreciation_account_id', 'depreciation_expense_account_id',
        'accumulated_depreciation', 'status', 'disposed_date', 'disposed_amount', 'notes', 'is_active',
    ];

    protected $casts = [
        'purchase_date'            => 'date',
        'in_service_date'          => 'date',
        'disposed_date'            => 'date',
        'purchase_cost'            => 'decimal:2',
        'salvage_value'            => 'decimal:2',
        'accumulated_depreciation' => 'decimal:2',
        'disposed_amount'          => 'decimal:2',
        'useful_life_months'       => 'integer',
        'is_active'                => 'boolean',
    ];

    public function category()
    {
        return $this->belongsTo(FixedAssetCategory::class, 'category_id');
    }

    public function assetAccount()
    {
        return $this->belongsTo(Account::class, 'asset_account_id');
    }

    public function accumDepreciationAccount()
    {
        return $this->belongsTo(Account::class, 'accum_depreciation_account_id');
    }

    public function depreciationExpenseAccount()
    {
        return $this->belongsTo(Account::class, 'depreciation_expense_account_id');
    }

    public function depreciations()
    {
        return $this->hasMany(FixedAssetDepreciation::class);
    }

    public function depreciableAmount(): float
    {
        return max(0, round((float) $this->purchase_cost - (float) $this->salvage_value, 2));
    }

    public function bookValue(): float
    {
        return max(0, round((float) $this->purchase_cost - (float) $this->accumulated_depreciation, 2));
    }

    public function monthlyDepreciation(): float
    {
        if ($this->useful_life_months <= 0) {
            return 0.0;
        }

        return round($this->depreciableAmount() / $this->useful_life_months, 2);
    }

    public function statusLabel(): string
    {
        return FixedAssetOptions::statusLabel($this->status);
    }

    public function depreciationMethodLabel(): string
    {
        return FixedAssetOptions::depreciationMethodLabel($this->depreciation_method);
    }
}
