<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Branch extends BasePosModel
{
    use SoftDeletes;

    protected static function booted(): void
    {
        static::creating(function (Branch $branch) {
            if (empty($branch->code)) {
                $count = static::where('company_id', $branch->company_id)->count() + 1;
                $prefix = Str::upper(Str::substr(Str::slug($branch->name), 0, 4));
                $branch->code = "BR-{$prefix}-" . str_pad((string) $count, 3, '0', STR_PAD_LEFT);
            }
        });
    }

    protected function casts(): array
    {
        return [
            'is_active' => 'boolean',
            'settings' => 'array',
        ];
    }

    public function company(): BelongsTo
    {
        return $this->belongsTo(Company::class);
    }

    public function shifts(): HasMany
    {
        return $this->hasMany(Shift::class);
    }
}
