<?php

namespace App\Models\Warehouse;

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

class ItemCategory extends Model
{
    use HasFactory;

    protected $table = 'item_categories';

    protected $fillable = [
        'category_code',
        'category_name',
        'type_of_goods',
        'description',
        'status'
    ];

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

    /**
     * Get all items in this category
     */
    public function items(): HasMany
    {
        return $this->hasMany(Item::class, 'category_id');
    }

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

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

    /**
     * Get total stock value for this category
     */
    public function getTotalStockValueAttribute()
    {
        return $this->items()
            ->with('inventories')
            ->get()
            ->sum(function ($item) {
                return $item->inventories->sum('total_value');
            });
    }

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

    /**
     * Generate a unique category code based on category name
     */
    public static function generateCategoryCode($categoryName)
    {
        // Extract first 3 characters from category name
        $baseCode = strtoupper(substr(preg_replace('/[^A-Za-z]/', '', $categoryName), 0, 3));

        if (strlen($baseCode) < 3) {
            $baseCode = str_pad($baseCode, 3, 'X');
        }

        // Check if code exists and increment if necessary
        $counter = 1;
        $code = $baseCode;

        while (self::where('category_code', $code)->exists()) {
            $code = $baseCode . str_pad($counter, 2, '0', STR_PAD_LEFT);
            $counter++;
        }

        return $code;
    }

    /**
     * Boot method to auto-generate category code if not provided
     */
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($category) {
            if (empty($category->category_code)) {
                $category->category_code = self::generateCategoryCode($category->category_name);
            }
        });
    }
}