<?php

namespace App\Http\Controllers\Cronjob;

use App\Http\Controllers\Controller;
use App\Models\BankMutation;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class BorneoMutationController extends Controller {
    public function get() {
        $bankList = [
            'BCA'   => website_config('borneo_mutation')->bca,
            'BNI'   => website_config('borneo_mutation')->bni,
            'OVO'   => website_config('borneo_mutation')->ovo,
            'GOPAY' => website_config('borneo_mutation')->gopay,
        ];
        foreach ($bankList as $key => $value) {
            if (website_config('borneo_mutation')->subscription_key == '') return 'Kunci Berlangganan kosong.';
            if ($value <> '') {
                $curl = Http::asForm()->withoutVerifying()->post('https://borneo-gateway.com/api/mutation', [
                    'subscription_key' => website_config('borneo_mutation')->subscription_key,
                    'access_token'     => $value,
                ]);
                if ($curl->ok() == true AND isset($curl->json()['status'])) {
                    $curl_response = $curl->json();
                    foreach ($curl_response['data'] as $item) {
                        if ($item['transaction_type'] == 'credit') {
                            $check_mutation = BankMutation::where([
                                ['bank', $key],
                                ['transaction_at', $item['transaction_at']], 
                                ['amount', $item['transaction_amount']],
                                ['note', $item['transaction_note']]
                            ])->count();
                            if ($check_mutation == 0) {
                                BankMutation::create([
                                    'bank'           => $key,
                                    'amount'         => $item['transaction_amount'],
                                    'balance'        => $item['transaction_amount'],
                                    'note'           => $item['transaction_note'],
                                    'transaction_at' => $item['transaction_at'],
                                ]);
                                print_r('Berhasil! Mutasi ditambahkan kedalam database. <br />');
                            } else {
                                print_r('Gagal! Mutasi sudah ada didalam database. <br />');
                            } 
                        }
                    }
                }
            }
        }
    }
}
