<?php

namespace App\Models\Warehouse;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Unit extends Model
{
    use HasFactory;

    protected $table = 'units';

    protected $fillable = [
        'unit_code',
        'unit_name',
        'unit_symbol',
        'unit_type',
        'description',
        'status'
    ];

    protected $casts = [
        'status' => 'string',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    /**
     * Get all items that use this unit
     */
    public function items(): HasMany
    {
        return $this->hasMany(Item::class, 'unit_id');
    }

    /**
     * Scope to get only active units
     */
    public function scopeActive($query)
    {
        return $query->where('status', 'active');
    }

    /**
     * Scope to filter by unit type
     */
    public function scopeByType($query, $type)
    {
        return $query->where('unit_type', $type);
    }

    /**
     * Get units grouped by type for display
     */
    public static function getGroupedUnits()
    {
        return self::active()
            ->orderBy('unit_type')
            ->orderBy('unit_name')
            ->get()
            ->groupBy('unit_type');
    }

    /**
     * Get all active units for dropdown
     */
    public static function getDropdownOptions()
    {
        return self::active()
            ->orderBy('unit_name')
            ->get()
            ->map(function ($unit) {
                return [
                    'value' => $unit->id,
                    'text' => $unit->unit_name . ' (' . $unit->unit_symbol . ')',
                    'unit_code' => $unit->unit_code,
                    'unit_symbol' => $unit->unit_symbol,
                    'unit_type' => $unit->unit_type
                ];
            });
    }

    /**
     * Get unit display name with symbol
     */
    public function getDisplayNameAttribute()
    {
        return $this->unit_name . ' (' . $this->unit_symbol . ')';
    }

    /**
     * Check if unit can be deleted (no items associated)
     */
    public function getCanBeDeletedAttribute()
    {
        return $this->items()->count() === 0;
    }

    /**
     * Get the count of active items using this unit
     */
    public function getActiveItemsCountAttribute()
    {
        return $this->items()->where('status', 'active')->count();
    }
}