<?php

namespace Modules\Financial\Payments;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Auth;
use Modules\Financial\Contracts\OnlinePayments;
use Modules\Financial\Entities\Gateway;
use Modules\Financial\Entities\Invoice;
use Modules\Financial\Entities\InvoiceTransaction;
use Modules\Financial\Entities\UserCredit;
use Modules\Training\Http\Controllers\CoachController;

class Wallet implements OnlinePayments
{

    public function pay($price, InvoiceTransaction $transaction ,$request=null)
    {

        $credit = UserCredit::credit($transaction->invoice->user_id);
        if($credit<$price){
            return 'err:insufficient funds';
        }
        if($price<0){
            abort(500,'what do you think about me?!hah?');
        }
        UserCredit::charge($transaction->invoice->user_id,-1*$price);
        $transaction->update(['transaction_reference_id'=>uniqid($transaction->invoice->user_id)]);
        return header('Location: '.url('/financial/payment_response/wallet?ref='.$transaction->transaction_reference_id));
    }

    /**
     * @param Request $request
     * @return array
     */
    public function response(Request $request){
        $transaction = InvoiceTransaction::where('transaction_reference_id',$request->ref)->first();
        if($transaction){
            return ['status'=>true,'transaction'=>$transaction];
        }else{
            return ['status'=>false,'transaction'=>null];
        }
    }
}
