<?php namespace AhmadFatoni\ApiGenerator\Controllers\API;

use Illuminate\Http\Request;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use October\Rain\Support\Facades\Event;
use TPS\Birzha\Classes\TranslatedErrSucMsgResponseApi;
use TPS\Birzha\Models\Payment;
use TPS\Birzha\Classes\TransactionResource;
use TPS\Birzha\Models\Settings;

class TransactionsApiController extends KabinetAPIController
{

    public function index(Request $request) {

        $validator = Validator::make($request->all(), [
            'transactions_per_page' => 'numeric',
        ]);

        if($validator->fails()) {
            return response()->json($validator->errors(), 400);
        }

        // $transactions = $this->user->transactions()
        //     ->orderBy('id', 'desc')
        //     ->paginate($request->transactions_per_page ? $request->transactions_per_page : 5);
        
        $transactions = TransactionResource::collection($this->user->transactions()
            ->orderBy('id', 'desc')
            ->paginate($request->transactions_per_page ? $request->transactions_per_page : 5))->response()->getData();

        return response()->json($transactions, 200);
    }

    /**
     * Get user's balance
     */
    public function myBalance() {

        return response()->json($this->user->getBalance() . ' TMT', 200);
    }

    public function updateBalance(Request $request){

        $validator = Validator::make($request->all(), [
            'type' => 'required|in:bank,online',
            'card_type' => 'required_if:type,online|in:halkbank,rysgal,senagat',
            'amount' => 'required_if:type,online|numeric|gt:0',
            'bank_file' => 'required_if:type,bank|mimes:pdf,jpg,png',
        ]);

        if($validator->fails()) {
            return response()->json($validator->errors(), 400);
        }

        $formData = $request->all();

        $payment = $this->createNewPayment(false, $formData);

        if($payment->payment_type == 'online'){

            $url = url('bank_result', ['payment_id' => $payment->id]);

            try {
                // Halkbank or Rysgal or Senagat
                $onlinePaymentClass = Config::get('bank.' . $formData['card_type'] . '.class');
                $onlinePayment = new $onlinePaymentClass;

                $response = $onlinePayment->registerOrder($payment, $url);

                $result = json_decode($response->body, true);

                $successfullyRegistered = $onlinePayment->checkRegisterOrderErrorCode($result);
                if($successfullyRegistered) {

                    $payment->order_id = $result['orderId'];

                    $payment->save();

                    return response()->json(['formUrl' => $result['formUrl']], 200);

                } else {
                    
                    return response()->json(TranslatedErrSucMsgResponseApi::translateErrorMessage('error', 'api.bank_services_unavailable'), 200);
                }

            } catch(\Throwable $th){
                $payment->status = 'failed';
                $payment->save();

                Log::info($th->getMessage());

                return response()->json(TranslatedErrSucMsgResponseApi::translateErrorMessage('error', 'api.online_payment_failed'), 200);
            }
        }
        elseif($payment->payment_type == 'bank'){
            $payment->amount = 0;
            $payment->bank_file = \Input::file('bank_file');

            if($payment->save()){
                Event::fire('tps.payment.received',$payment);
                return response()->json(TranslatedErrSucMsgResponseApi::translateErrorMessage('success', 'api.bank_payment_saved'), 200);
            } else {
                return response()->json(TranslatedErrSucMsgResponseApi::translateErrorMessage('error', 'api.bank_payment_failed'), 500);
            }
        }

        return response()->json('The payment saving failed.', 500);

    }


    protected function createNewPayment($bank_file, $formData) {
        $newPayment = new Payment;
        $newPayment->user_id = $this->user->id;
        $newPayment->amount = $formData['amount'] ?? 0;
        $newPayment->payment_type = $formData['type'];
        $newPayment->card_type = isset($formData['card_type']) ? $formData['card_type'] : null;
        $newPayment->save();

        // attach file to payment
        if($bank_file) {
            $newPayment->bank_file = $bank_file;
            $newPayment->save();
        }

        return $newPayment;
    }

}
