<?php

namespace App\Http\Controllers;

use App\Http\Helpers\StripeClient;
use App\Models\Configuration;
use App\Models\PayoutRequest;
use App\Models\StripeError;
use App\Models\Wallet;
use Exception;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Notification;
use App\Notifications\PayoutRequestCreated;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Permission;

class PayoutRequestController extends Controller
{
    public function store(Request $request){
        try {
            $minimum_withdrawal_amount = (int)Configuration::where('key', 'minimum_withdrawal_amount')->first()->value;
        $request->validate([
            'amount' => 'required',
            'billing_id' => 'required',
            'id'=>'required',
        ]);
            $user = Auth::user();
            if (Auth::user()->engineer != null) {
                $entity = Auth::user()->engineer;
            } elseif (Auth::user()->firm != null) {
                $entity = Auth::user()->firm;
            } else {
                $entity = Auth::user();
            }
            $accountId=null;

            foreach ($entity->billingAccounts as $account){
                if(StripeClient::stripe()->accounts->retrieve($account->stripe_id)->external_accounts->total_count>0){
                    foreach (StripeClient::stripe()->accounts->retrieve($account->stripe_id)->external_accounts->data as $datum){
                        if($datum->id == $request->billing_id){
                            $accountId=$datum->account;
                        }
                    }
                }
            }

        if($request->amount < $minimum_withdrawal_amount){
            return back(303)->with(["warning" => 'Can not withdraw less than $' . $minimum_withdrawal_amount . ' USD']);
        }else if ($request->amount > Wallet::find($request->id)->available_funds){
            return back(303)->with(["error" => 'Can not withdraw more than your available funds']);
        }
        $payout = PayoutRequest::create([
            'amount' => $request->amount * 100,
            'wallet_id'=>$request->id,
            'billing_data_id' => $request->billing_id,
            'stripe_account_id'=>$accountId,
        ]);

        if ($request->amount <= Wallet::find($request->id)->available_funds){
            $payout->approve();
            return back(303)->with(["success" => 'success']);
        }
        }catch(\Stripe\Exception\CardException|\Stripe\Exception\ApiErrorException| \Stripe\Exception\InvalidRequestException $e) {
            StripeError::create([
                'user_id'=>Auth::user()->id,
                'error_message'=>$e->getMessage(),
                'error_code'=>$e->getJsonBody()['error']['request_log_url'],
                'stripe_url'=>$e->getStripeCode(),
            ]);
            if($e->getStripeCode()=="balance_insufficient"){
                return back(303)->with(["warning" => 'your money still in it\'s way to bank, please try again in couple of days']);
            }else{
                return back(303)->with(["fail"=>'Unexpected error has occurred please try again in couple of days']);
            }

        }   catch (Exception $e) {
            return back(303)->with(["fail"=>'Unexpected error has occurred please try again in couple of days']);
        }
    }
}
