<?php

namespace Mamad\Transaction\Http\Controllers;


use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Mamad\Cart\Repository\CartRepository;
use Mamad\Product\Service\ProductService;
use Mamad\Shop\Service\ShopService;
use Mamad\Transaction\Events\TransactionSucceed;
use Mamad\Transaction\Models\Transaction;
use Mamad\Transaction\Repository\TransactionRepository;
use Shetabit\Multipay\Exceptions\InvalidPaymentException;
use Shetabit\Payment\Facade\Payment;


class TransactionController extends Controller
{
    public function verify(Request $request){
        if(isset($request->trans_id)){
            $transaction_id=$request->trans_id;
        }
        $transaction=TransactionRepository::find_by_transaction_id($transaction_id);
        try {
            $receipt = Payment::amount((integer) $transaction->price)->transactionId($transaction_id)->verify();
            TransactionRepository::updateErrorText($transaction," ");
            event(new TransactionSucceed($transaction));
            return ShopService::transaction_succeed_redirection($transaction->transactionable);
        } catch (InvalidPaymentException $exception) {
            TransactionRepository::updateStatus($transaction,Transaction::$FAILED);
            TransactionRepository::updateErrorText($transaction,$exception->getMessage());

            TransactionRepository::update_transactionAble_Status($transaction->transactionable,Transaction::$FAILED);


            toastMessage($exception->getMessage(),"خطایی رخ داد","error");
            return redirect()->route("home");
        }
    }

}
