<?php

namespace App\Models;

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

class FixedAsset extends Model
{
    public const STATUSES = [
        'active' => 'Active',
        'in_maintenance' => 'In Maintenance',
        'retired' => 'Retired',
        'disposed' => 'Disposed',
    ];

    public const DEPRECIATION_METHODS = [
        'straight_line' => 'Straight Line',
        'none' => 'Do Not Depreciate',
    ];

    public const ACQUISITION_SOURCES = [
        'opening' => 'Existing / Opening Asset',
        'financial_account' => 'Purchased From Financial Account',
    ];

    protected $fillable = [
        'business_id','branch_id','asset_number','name','category','description','serial_number','supplier','purchase_reference',
        'acquisition_source','acquisition_date','depreciation_start_date','acquisition_cost','residual_value','depreciation_method',
        'useful_life_months','accumulated_depreciation','book_value','financial_account_id','location','custodian_user_id','status',
        'next_maintenance_date','notes','created_by','updated_by',
    ];

    protected function casts(): array
    {
        return [
            'acquisition_date' => 'date',
            'depreciation_start_date' => 'date',
            'next_maintenance_date' => 'date',
            'acquisition_cost' => 'decimal:2',
            'residual_value' => 'decimal:2',
            'accumulated_depreciation' => 'decimal:2',
            'book_value' => 'decimal:2',
            'useful_life_months' => 'integer',
        ];
    }

    public function business(): BelongsTo { return $this->belongsTo(Business::class); }
    public function branch(): BelongsTo { return $this->belongsTo(Branch::class); }
    public function financialAccount(): BelongsTo { return $this->belongsTo(FinancialAccount::class); }
    public function custodian(): BelongsTo { return $this->belongsTo(User::class, 'custodian_user_id'); }
    public function creator(): BelongsTo { return $this->belongsTo(User::class, 'created_by'); }
    public function updater(): BelongsTo { return $this->belongsTo(User::class, 'updated_by'); }
    public function depreciations(): HasMany { return $this->hasMany(FixedAssetDepreciation::class)->orderByDesc('period_date'); }
    public function maintenances(): HasMany { return $this->hasMany(FixedAssetMaintenance::class)->orderByDesc('maintenance_date')->orderByDesc('id'); }

    public function isDepreciable(): bool
    {
        return $this->depreciation_method === 'straight_line' && (int) $this->useful_life_months > 0;
    }
}
