<?php

namespace App\Models;

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

class MaintenanceBill extends Model
{
    use HasFactory;

    protected $fillable = [
        'society_id',
        'unit_id',
        'bill_number',
        'billing_month',
        'amount',
        'status',
        'paid_at'
    ];

    protected static function boot()
    {
        parent::boot();
        static::creating(function ($bill) {
            $latest = self::orderBy('id', 'desc')->first();
            $number = $latest ? (int) substr($latest->bill_number, 6) + 1 : 1;
            do {
                $code = 'SMBill' . str_pad($number, 7, '0', STR_PAD_LEFT);
                $exists = self::where('bill_number', $code)->exists();
                if ($exists)
                    $number++;
            } while ($exists);
            $bill->bill_number = $code;
        });
    }
}
