<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\Pelanggan;

class Zone extends Model
{
    protected $table = 'zones';
    protected $primaryKey = 'id_zones';
    public $incrementing = false;
    protected $keyType = 'string';

    protected static function booted()
    {
        static::creating(function ($zone) {
            if (!$zone->id_zones) {
                do {
                    $randomId = 'ZN' . mt_rand(100, 999);
                } while (self::where('id_zones', $randomId)->exists());
                $zone->id_zones = $randomId;
            }
        });
    }

    public function getIdAttribute()
    {
        return $this->attributes[$this->primaryKey] ?? null;
    }

    public function setIdAttribute($value)
    {
        $this->attributes[$this->primaryKey] = $value;
    }

    protected $fillable = [
        'name',
        'kabupaten',
        'zone_type',
        'shipping_cost'
    ];

    public function customers()
    {
        return $this->hasMany(Pelanggan::class, 'id_zones', 'id_zones');
    }
}
