<?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 EasyInPurchase extends Model
{
    use HasFactory, SoftDeletes;

    protected $table = 'easy_in_purchases';

    protected $fillable = [
        'reference_number',
        'purchase_date',
        'item_description',
        'unit',
        'quantity',
        'unit_price',
        'total_amount',
        'division_id',
        'supplier_name',
        'invoice_number',
        'lpo_number',
        'notes',
        'created_by',
    ];

    protected $casts = [
        'purchase_date' => 'date',
        'quantity'      => 'decimal:2',
        'unit_price'    => 'decimal:2',
        'total_amount'  => '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 = 'EI-' . 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 createdBy()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

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

    public function scopeSearch($query, $term)
    {
        return $query->where(function ($q) use ($term) {
            $q->where('item_description', 'LIKE', "%{$term}%")
              ->orWhere('reference_number', 'LIKE', "%{$term}%")
              ->orWhere('supplier_name', 'LIKE', "%{$term}%")
              ->orWhere('invoice_number', 'LIKE', "%{$term}%");
        });
    }

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