<?php

namespace App\Models;

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

class Tender extends Model
{
    use HasFactory;

    protected $fillable = [
        'society_id',
        'created_by',
        'tender_number',
        'title',
        'category',
        'tender_type',
        'location',
        'description',
        'technical_specifications',
        'budget',
        'emd_amount',
        'tender_fee',
        'minimum_bid_amount',
        'maximum_bid_amount',
        'deadline',
        'bid_submission_start',
        'bid_submission_end',
        'status',
        'approval_status',
        'is_suspended',
        'suspended_reason',
        'approved_by',
        'approved_at',
        'awarded_vendor_id'
    ];

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