<?php

namespace App\Models\Inventory;

use App\Models\Branch;
use App\Models\Concerns\Auditable;
use App\Models\Concerns\BelongsToTenant;
use App\Models\Concerns\BranchScoped;
use App\Models\Lookups\GrnStatus;
use App\Models\Purchasing\PurchaseOrder;
use App\Models\Purchasing\Supplier;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Grn extends Model
{
    use Auditable, BelongsToTenant, BranchScoped;

    protected $fillable = [
        'grn_number', 'branch_id', 'supplier_document_id', 'supplier_id', 'purchase_order_id',
        'reference', 'note', 'grn_status_id', 'confirmed_by', 'confirmed_at',
        'deleted_by', 'deleted_at',
    ];

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

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

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

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

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

    public function confirmedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'confirmed_by');
    }

    public function deletedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'deleted_by');
    }

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

    protected function casts(): array
    {
        return [
            'grn_status_id' => 'integer',
            'confirmed_at' => 'datetime',
            'deleted_at' => 'datetime',
        ];
    }

    public function isDraft(): bool
    {
        return $this->grn_status_id === GrnStatus::DRAFT;
    }

    public function isConfirmed(): bool
    {
        return $this->grn_status_id === GrnStatus::CONFIRMED;
    }

    public function isDeleted(): bool
    {
        return $this->grn_status_id === GrnStatus::DELETED;
    }
}
