<?php

namespace App\Models;

use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class BagType extends Model
{
    /** Table name (dump অনুযায়ী) */
    protected $table = 'rm_bag_types';

    /** Mass-assignable fields */
    protected $fillable = [
        'name',
        'bag_size',
        'opening_quantity',
        'status',        // string '0' | '1'
        'created_by',
        'updated_by',
    ];

    /** Casts */
    protected $casts = [
        'bag_size'   => 'decimal:2',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    /*
    |--------------------------------------------------------------------------
    | Relationships
    |--------------------------------------------------------------------------
    */
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function updater()
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    /*
    |--------------------------------------------------------------------------
    | Scopes & Helpers
    |--------------------------------------------------------------------------
    */

    /** quick search: name / bag_size */
    public function scopeSearch(Builder $q, ?string $term): Builder
    {
        $term = trim((string) $term);
        if ($term === '') return $q;

        return $q->where(function (Builder $w) use ($term) {
            $w->where('name', 'like', "%{$term}%")
              ->orWhere('bag_size', 'like', "%{$term}%");
        });
    }

    /** active items */
    public function scopeActive(Builder $q): Builder
    {
        return $q->where('status', '1');
    }

    /** accessor: boolean active flag */
    public function getIsActiveAttribute(): bool
    {
        return (string) $this->status === '1';
    }

    /** mutator: status normalize to '1' / '0' */
    public function setStatusAttribute($value): void
    {
        $this->attributes['status'] = (string) ((int) (bool) $value);
    }
}

