<?php

namespace App\Http\Services;

use App\Models\Bank;
use App\Models\Gateway;
use App\Models\GatewayCurrency;
use App\Traits\ResponseTrait;
use Exception;
use Illuminate\Support\Facades\DB;

class GatewayService
{
    use ResponseTrait;

    public function getAll()
    {
        return Gateway::where('user_id', auth()->id())->get();;
    }

    public function getActiveAll($userId)
    {
        return Gateway::where('user_id', $userId)->where('status', ACTIVE)->get();
    }

    public function getActiveBanks($userId)
    {
        return Bank::where('user_id', $userId)->where('status', ACTIVE)->get();
    }

    public function getInfo($id)
    {
        return Gateway::findOrFail($id);
    }

    public function getCurrenciesByGatewayId($id)
    {
        $data['gateway'] = $this->getInfo($id);
        if ($data['gateway']->slug == 'bank') {
            $data['banks'] = $this->banks();
        }
        $data['image'] = $data['gateway']->icon;
        $currencies = GatewayCurrency::where('user_id', auth()->id())->where('gateway_id', $id)->get();
        foreach ($currencies as $currency) {
            $currency->symbol;
        }
        $data['currencies'] = $currencies;
        return $this->success($data);
    }

    public function banks()
    {
        return Bank::where('user_id', auth()->id())->get();
    }

    public function store($request)
    {
        DB::beginTransaction();
        try {
            $id = $request->get('id', '');
            $userId = auth()->id();
            if ($id != '') {
                $gateway = Gateway::where('user_id', $userId)->findOrFail($request->id);
            } else {
                $gateway = new Gateway();
            }
            if ($gateway->slug == 'bank') {
                $bankIds = [];
                for ($i = 0; $i < count($request->bank['name']); $i++) {
                    $bank = Bank::updateOrCreate([
                        'id' => $request->bank['id'][$i],
                        'user_id' => $userId
                    ], [
                        'gateway_id' => $gateway->id,
                        'user_id' => $userId,
                        'name' => $request->bank['name'][$i],
                        'details' => $request->bank['details'][$i],
                        'status' => $request->bank['status'][$i],
                    ]);
                    array_push($bankIds, $bank->id);
                }
                Bank::where('user_id', $userId)->whereNotIn('id', $bankIds)->delete();
            } else {
                $gateway->mode = $request->mode;
                $gateway->url = $request->url;
                $gateway->key = $request->key;
                $gateway->secret = $request->secret;
            }
            $gateway->status = $request->status;
            $gateway->user_id = $userId;
            $gateway->save();

            $gatewayCurrencyIds = [];
            if (is_array($request->currency)) {
                foreach ($request->currency as $key => $currency) {
                    $gatewayCurrency =   GatewayCurrency::updateOrCreate([
                        'id' => $request->currency_id[$key],
                        'user_id' => $userId
                    ], [
                        'gateway_id' => $gateway->id,
                        'user_id' => $userId,
                        'currency' => $currency,
                        'conversion_rate' => $request->conversion_rate[$key],
                    ]);
                    array_push($gatewayCurrencyIds, $gatewayCurrency->id);
                }
            } else {
                throw new Exception(__('Please add at least one currency'));
            }
            GatewayCurrency::where('user_id', $userId)->whereNotIn('id', $gatewayCurrencyIds)->where('gateway_id', $gateway->id)->delete();

            DB::commit();
            $message = $request->id ? __(UPDATED_SUCCESSFULLY) : __(CREATED_SUCCESSFULLY);
            return $this->success([], $message);
        } catch (Exception $e) {
            DB::rollBack();
            $message = getErrorMessage($e, $e->getMessage());
            return $this->error([],  $message);
        }
    }

    public function getCurrencyByGatewayId($id)
    {
        $currencies = GatewayCurrency::where('gateway_id', $id)->get();
        foreach ($currencies as $currency) {
            $currency->symbol =  $currency->symbol;
        }
        return $currencies;
    }
}
