<?php

namespace Hilco\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Throwable;

/**
 * Model Class ApprovalReason_StagedOrder
 * @property integer id
 * @property integer approvalreason_id
 * @property integer stagedorder_id
 * @property boolean is_approved
 * @property integer approver_salesrep_id
 * @method static Builder byOrderApproval($orderId, $approvalId)
 */
class ApprovalReason_StagedOrder extends StagingModel {
    protected $table = "ApprovalReason_StagedOrder";
    protected $fillable = ['approvalreason_id', 'stagedorder_id', 'is_approved', 'approver_salesrep_id'];

    /**
     * @param StagedOrder $stagedOrder
     * @param ApprovalReason $approvalReason
     * @return ApprovalReason_StagedOrder
     * @throws Throwable
     */
    public static function createForOrder (StagedOrder $stagedOrder, ApprovalReason $approvalReason): ApprovalReason_StagedOrder {
        $arso = ApprovalReason_StagedOrder::byOrderApproval($stagedOrder->id, $approvalReason->id)->first();
        if (isset($arso) && $arso instanceof ApprovalReason_StagedOrder) { // instanceof is just to keep the ide happy
            return $arso;
        }
        $arso = new ApprovalReason_StagedOrder([
            'approvalreason_id' => $approvalReason->id,
            'stagedorder_id' => $stagedOrder->id,
        ]);
        $arso->saveOrFail();
        return $arso;
    }

    /**
     * @param Builder $query
     * @param $orderId
     * @param $approvalId
     * @return Builder
     */
    public function scopeByOrderApproval (Builder $query, $orderId, $approvalId): Builder {
        return $query->where('stagedorder_id', '=', $orderId)->where('approvalreason_id', '=', $approvalId);
    }

    /**
     * @return BelongsTo
     */
    public function approvalReason(): BelongsTo {
        return $this->belongsTo(ApprovalReason::class, "approvalreason_id", "id");
    }

    /**
     * @return BelongsTo
     */
    public function stagedOrder(): BelongsTo {
        return $this->belongsTo(StagedOrder::class, "stagedorder_id", "id");
    }

    /**
     * @return BelongsTo
     */
    public function approver(): BelongsTo {
        return $this->belongsTo(SalesRep::class, "approver_salesrep_id", "id");
    }

    /**
     * @return bool
     */
    public function isApproved(): bool {
        return $this->is_approved;
    }
}
