<?php

namespace App\Models;

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

class Tender extends BaseModel
{
    use HasFactory;

    protected $fillable = [
        'title',
        'reference',
        'project_id',
        'closing_date',
        'status',
        'tender_issued_date',
        'rfi_cut_off_date',
        'scope_of_work',
        'reminder_days_before',
        'allow_late_submissions',
        'allow_bidder_document_uploads',
        'submitted_at',
        'bidder_id',
        'total_base_bid',
        'exclusions_clarifications',
        'is_late_submission',
        'customer_id',
        'workspace_id',
    ];

    protected $hidden = [
        'customer_id',
        'workspace_id',
    ];

    /**
     * Boot method to auto-generate unique reference
     */
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($tender) {
            if (empty($tender->reference)) {
                $tender->reference = static::generateUniqueReference();
            }
        });
    }

    /**
     * Generate unique reference in format: TM-DD-YYYY-XXX
     * Where DD is day, YYYY is year, and XXX is sequential number
     */
    protected static function generateUniqueReference()
    {
        $day = Carbon::now()->format('d');
        $year = Carbon::now()->format('Y');
        $prefix = "PT-{$day}-{$year}";
        
        // Get the last reference for today
        $lastTender = static::where('reference', 'like', "{$prefix}-%")
            ->orderBy('reference', 'desc')
            ->first();
        
        if ($lastTender) {
            // Extract the sequential number from the last reference
            $lastNumber = (int) substr($lastTender->reference, -3);
            $nextNumber = $lastNumber + 1;
        } else {
            $nextNumber = 1;
        }
        
        // Format with leading zeros (001, 002, etc.)
        $sequential = str_pad($nextNumber, 3, '0', STR_PAD_LEFT);
        
        $reference = "{$prefix}-{$sequential}";
        
        // Double-check uniqueness (in case of race condition)
        while (static::where('reference', $reference)->exists()) {
            $nextNumber++;
            $sequential = str_pad($nextNumber, 3, '0', STR_PAD_LEFT);
            $reference = "{$prefix}-{$sequential}";
        }
        
        return $reference;
    }

    /**
     * Get the project associated with the tender.
     */
    public function project()
    {
        return $this->belongsTo(Project::class, 'project_id');
    }

    /**
     * Get the bidder (user) associated with the tender.
     */
    public function bidder()
    {
        return $this->belongsTo(User::class, 'bidder_id');
    }

    /**
     * Get all line items for this tender.
     */
    public function lineItems()
    {
        return $this->hasMany(TenderLineItem::class, 'tender_id');
    }

    /**
     * Get all bids for this tender.
     */
    public function bids()
    {
        return $this->hasMany(TenderLineItemsBid::class, 'tender_id');
    }

    /**
     * Get all participants for this tender.
     */
    public function participants()
    {
        return $this->hasMany(TenderParticipant::class, 'tender_id');
    }

    /**
     * Get all RFIs for this tender.
     */
    public function rfis()
    {
        return $this->hasMany(TenderRfi::class, 'tender_id');
    }
}

