<?php

namespace App\Models;

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

class SalesType extends Model
{
    use HasFactory;

    protected $table = 'm_sales_types';

    protected $fillable = [
        'code',
        'name',
        'description',
        'is_active',
        'delete_flag',
        'created_by',
        'updated_by',
        'created_at',
        'updated_at',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'delete_flag' => 'boolean',
    ];

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

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

    // Scope for active sales types
    public function scopeActive($query)
    {
        return $query->where('is_active', true)->where('delete_flag', false);
    }

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (empty($model->code)) {
                $lastCode = static::selectRaw("code")
                    ->where('delete_flag', '0')
                    ->where('code', 'like', 'ST%')
                    ->orderByRaw("CAST(SUBSTRING(code FROM 3) AS INTEGER) DESC")
                    ->value('code');

                $lastNumber = $lastCode ? intval(substr($lastCode, 2)) : 0;
                $newNumber = $lastNumber + 1;

                $model->code = 'ST' . str_pad($newNumber, 3, '0', STR_PAD_LEFT);
            }
        });
    }
}