<?php

namespace App\Models;

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

class AccountLedger extends Model
{
    use HasFactory;

    protected $fillable = [
        'society_id',
        'transaction_id',
        'type',
        'amount',
        'category',
        'description',
        'transaction_date'
    ];

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