<?php

namespace App\Classes\Modules\Transactions\Services;

use App\Classes\General\Eloquent\AbstractUpdateRecord;
use App\Classes\Modules\PerfexCRM\Processors\TransactionToPerfexCRMProcessorV2;
use App\Models\Transaction;
use App\Classes\Modules\Vouchers\Processors\Voucherify\TransactionToVoucherifyProcessor;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;

class UpdatesTransactionStatus extends AbstractUpdateRecord
{
    /** @var TransactionToPerfexCRMProcessorV2 */
    private $transactionToPerfexCRMProcessor;

    /** @var TransactionToVoucherifyProcessor */
    private $transactionToVoucherifyProcessor;

    /**
     * UpdatesTransactionStatus constructor.
     * @param TransactionToPerfexCRMProcessorV2 $transactionToPerfexCRMProcessor
     * @param TransactionToVoucherifyProcessor $transactionToVoucherifyProcessor
     */
    public function __construct(TransactionToPerfexCRMProcessorV2 $transactionToPerfexCRMProcessor, TransactionToVoucherifyProcessor $transactionToVoucherifyProcessor)
    {
        $this->transactionToPerfexCRMProcessor = $transactionToPerfexCRMProcessor;
        $this->transactionToVoucherifyProcessor = $transactionToVoucherifyProcessor;
    }


    /**
     * @param Transaction $model
     * @param int $status
     * @return \Illuminate\Database\Eloquent\Model
     * @throws \App\Classes\Exceptions\MalformedRequestException
     */
    public function execute(Transaction $model, int $status)
    {
        $transaction = clone($model);
        $model->status = $status;
        $result = $this->handler($model);
        if(config('perfexcrm.is_enabled') == 'true'){
            $this->transactionToPerfexCRMProcessor->execute($transaction, $status);
        }

        if($status == ApprovalStatus::APPROVED && ($transaction->type == TransactionType::PAYMENT || $transaction->type == TransactionType::TOP_UP)){
            $this->transactionToVoucherifyProcessor->execute($transaction, "PAID");
        }

        return $result;
    }
}
