<?php

namespace Modules\PurchaseRequisition\Entities;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class PrSupplierResponse extends Model
{
    use SoftDeletes;

    protected $table = 'pr_supplier_responses';

    protected $guarded = ['id'];

    protected $casts = [
        'submitted_at' => 'datetime',
        'approved_at' => 'datetime',
    ];

    /**
     * Get the purchase requisition.
     */
    public function prRequest()
    {
        return $this->belongsTo(PrRequest::class, 'pr_request_id');
    }

    /**
     * Get the supplier (contact).
     */
    public function supplier()
    {
        return $this->belongsTo(\App\Contact::class, 'supplier_id');
    }

    /**
     * Get the currency used in this response.
     */
    public function currency()
    {
        return $this->belongsTo(PrCurrency::class, 'currency_id');
    }

    /**
     * Get the supplier products for this response.
     */
    public function supplierProducts()
    {
        return $this->hasMany(PrSupplierProduct::class, 'pr_supplier_response_id');
    }

    /**
     * Get the user who approved this response.
     */
    public function approvedBy()
    {
        return $this->belongsTo(\App\User::class, 'approved_by');
    }

    /**
     * Scope to filter by business.
     */
    public function scopeForBusiness($query, $businessId)
    {
        return $query->where('business_id', $businessId);
    }

    /**
     * Scope to filter by status.
     */
    public function scopeByStatus($query, $status)
    {
        return $query->where('status', $status);
    }

    /**
     * Scope to find by token.
     */
    public function scopeByToken($query, $token)
    {
        return $query->where('share_token', $token);
    }
}
