<?php

namespace App\Models\Warehouse;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use App\Models\User;

class EasyOutDispatch extends Model
{
    use HasFactory, SoftDeletes;

    protected $table = 'easy_out_dispatches';

    protected $fillable = [
        'reference_number',
        'dispatch_date',
        'bill_number',
        'mr_no',
        'item_description',
        'unit',
        'quantity',
        'project_id',
        'division_id',
        'purpose',
        'received_by',
        'notes',
        'created_by',
    ];

    protected $casts = [
        'dispatch_date' => 'date',
        'quantity'      => 'decimal:2',
    ];

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (empty($model->reference_number)) {
                $model->reference_number = static::generateReferenceNumber();
            }
            if (empty($model->created_by)) {
                $model->created_by = auth()->id();
            }
        });
    }

    public static function generateReferenceNumber(): string
    {
        $prefix = 'EO-' . date('Ymd') . '-';
        $last = static::withTrashed()
            ->where('reference_number', 'LIKE', $prefix . '%')
            ->orderBy('reference_number', 'desc')
            ->first();
        $seq = $last ? ((int) substr($last->reference_number, -4) + 1) : 1;
        return $prefix . str_pad($seq, 4, '0', STR_PAD_LEFT);
    }

    public function project()
    {
        return $this->belongsTo(Project::class, 'project_id');
    }

    public function division()
    {
        return $this->belongsTo(\App\Models\Warehouse\ProjectDivision::class, 'division_id');
    }

    public function createdBy()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function scopeForPeriod($query, $from, $to)
    {
        if ($from) {
            $query->whereDate('dispatch_date', '>=', $from);
        }
        if ($to) {
            $query->whereDate('dispatch_date', '<=', $to);
        }
        return $query;
    }
}
