<?php

namespace Modules\Inventory\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Modules\Core\Traits\HasStatus;
use Modules\Inventory\Models\Traits\HasInventoryDepartment;
use Illuminate\Database\Eloquent\Builder;
use Modules\Inventory\Models\Traits\CategoryRelationshipTrait;

class Category extends Model
{
    use HasStatus,
        HasInventoryDepartment,
        CategoryRelationshipTrait,
        SoftDeletes;

    /**
     * The attributes that are mass assignable.
     */
    protected $fillable = [
        'name',
        'code',
        'description',
        'inventory_department_id',
        'category_type',
        'has_stock',
        'has_batch',
        'has_expiry',
        'asset_account_id',
        'accum_dep_account_id',
        'dep_expense_account_id',
        'status'
    ];

    protected function casts(): array
    {
        return [
            'has_stock' => 'boolean',
            'has_batch' => 'boolean',
            'has_expiry' => 'boolean',
        ];
    }

    public $timestamps = false;

    public function scopeSearch(Builder $query, ?string $search): Builder
    {
        if (blank($search)) {
            return $query;
        }
        $like = "%{$search}%";

        return $query->where(function ($q) use ($like) {
            $q->where('name', 'LIKE', $like)
                ->orWhere('code', 'LIKE', $like);
        });
    }

    public function scopeByCategoryType(Builder $query, ?string $type): Builder
    {
        return $type ? $query->where('category_type', $type) : $query;
    }
}
