<?php

namespace App\Models\Purchasing;

use App\Models\Branch;
use App\Models\Concerns\Auditable;
use App\Models\Concerns\BelongsToTenant;
use App\Models\Concerns\BranchScoped;
use App\Models\Inventory\Grn;
use App\Models\Lookups\Status;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class PurchaseOrder extends Model
{
    use Auditable, BelongsToTenant, BranchScoped, SoftDeletes;

    protected $fillable = [
        'uuid', 'po_number', 'supplier_id', 'branch_id', 'status_id',
        'expected_date', 'notes', 'created_by', 'updated_by', 'deleted_by',
    ];

    protected function casts(): array
    {
        return ['expected_date' => 'date'];
    }

    protected static function booted(): void
    {
        static::creating(function (self $po): void {
            if (! $po->uuid) {
                $po->uuid = (string) Str::ulid();
            }
        });
    }

    public function supplier(): BelongsTo
    {
        return $this->belongsTo(Supplier::class);
    }

    public function branch(): BelongsTo
    {
        return $this->belongsTo(Branch::class);
    }

    public function status(): BelongsTo
    {
        return $this->belongsTo(Status::class, 'status_id');
    }

    public function items(): HasMany
    {
        return $this->hasMany(PurchaseOrderItem::class);
    }

    public function grns(): HasMany
    {
        return $this->hasMany(Grn::class);
    }

    public function isDraft(): bool
    {
        return $this->status?->code === Status::PO_DRAFT;
    }

    public function isFullyReceived(): bool
    {
        return $this->items->every(fn (PurchaseOrderItem $item) => (float) $item->received_quantity >= (float) $item->ordered_quantity);
    }
}
