<?php

namespace App\Http\Controllers;

use App\Http\Helpers\StripeClient;
use App\Models\BillingData;
use App\Models\StripeConnectedAccount;
use App\Models\StripeError;
use Carbon\Carbon;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redirect;
use Inertia\Inertia;

class BillingDataController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        //
    }


    public function store(Request $request)
    {
        try {
            $transaction = DB::transaction(function () use ($request) {
                if (Auth::user()->engineer != null) {
                    $entity = Auth::user()->engineer;
                } elseif (Auth::user()->firm != null) {
                    $entity = Auth::user()->firm;
                } else {
                    $entity = Auth::user();
                }
                $request->validate([
                    'token' => 'required',
                    'type' => 'required',
                ]);
                    if ($request->type === 'card') {
                        //dd($request->token);
                        $card = StripeClient::addCard($entity->stripe_connected_account, [
                            'external_account' => $request->token['id'],
                        ]);
                        $entity->billingAccounts()->create([
                            'stripe_id' => $card->id,
                            'object' => $card->object,
                            'last4' => $card->last4,
                            'currency' => $card->currency,
                            'country' => $card->country,
                            'stripe_account' => $card->account,
                            'exp_month' => $card->exp_month,
                            'exp_year' => $card->exp_year,
                            'brand' => $card->brand,
                            'account_holder_name' => $card->account_holder_name ?? $card->name,
                        ]);
                    } else {
                        $card = StripeClient::addBankAccount($entity->stripe_connected_account, [
                            'external_account' => $request->token['id'],
                        ]);
                        $entity->billingAccounts()->create([
                            'stripe_id' => $card->id,
                            'object' => $card->object,
                            'last4' => $card->last4,
                            'currency' => $card->currency,
                            'country' => $card->country,
                            'stripe_account' => $card->account,
                            'account_holder_name' => $card->account_holder_name,
                            'account_holder_type' => $card->account_holder_type,
                        ]);
                    }

            });
            return is_null($transaction)
                ? back(303)->with(["success" => "success"])
                : $transaction;
        } catch(\Stripe\Exception\CardException|\Stripe\Exception\ApiErrorException| \Stripe\Exception\InvalidRequestException $e) {
            if($e->getStripeCode()=="balance_insufficient"){
                return back(303)->with(["error" => 'your money still in it\'s way to bank, please try again in couple of days']);
            }else{
                return back(303)->with(["error"=>'Unexpected error has occurred please try again in couple of days']);
            }

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


    public function createConnectedAccount(Request $request){
        try{
            if (Auth::user()->engineer != null) {
                $entity = Auth::user()->engineer;
            } elseif (Auth::user()->firm != null) {
                $entity = Auth::user()->firm;
            } else {
                $entity = Auth::user();
            }
            return response('', 409)
                ->header('X-Inertia-Location', StripeClient::createAccount($entity, $request->country??'US', $request->city, $request->address));
            // return Redirect::to();
        }catch(\Stripe\Exception\CardException|\Stripe\Exception\ApiErrorException| \Stripe\Exception\InvalidRequestException $e) {
            if($e->getStripeCode()=="balance_insufficient"){
                return back(303)->with(["error" => 'your money still in it\'s way to bank, please try again in couple of days']);
            }else{
                return back(303)->with(["error"=>'Unexpected error has occurred please try again in couple of days']);
            }

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

    }
    /**
     * Display the specified resource.
     *
     * @param BillingData $billingData
     * @return Response
     */
    public function show(BillingData $billingData)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param BillingData $billingData
     * @return Response
     */
    public function edit(BillingData $billingData)
    {
        //
    }


    public function update(Request $request, $accountId)
    {
        try {
            // $request->validate([
            //     'account_id'=>'required'
            // ]);
            return Inertia::location(StripeClient::updateAccount($accountId));
        }catch(\Stripe\Exception\CardException|\Stripe\Exception\ApiErrorException| \Stripe\Exception\InvalidRequestException $e) {
            if($e->getStripeCode()=="balance_insufficient"){
                return back(303)->with(["error" => 'your money still in it\'s way to bank, please try again in couple of days']);
            }else{
                return back(303)->with(["error"=>'Unexpected error has occurred please try again in couple of days']);
            }

        }   catch (Exception $e) {

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

        //

    }


    public function destroy(Request $request, $accountId)
    {
        StripeClient::deleteConnectedAccount($accountId);
        StripeConnectedAccount::where('stripe_id',$accountId)->delete();
        return back(303)->with(['success' => 'success']);
    }
}
