<?php


namespace App\Http\Controllers;

use App\Core\Mail\LogMail;
use App\Core\Service\PropertyPaymentService;
use App\Exceptions\ApiErrorException;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

use Illuminate\Support\Facades\App;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Mail\Mailer;
use Mews\Pos\Pos;


class PaymentController
{

    public function __construct(
        PropertyPaymentService $propertyPaymentService,
        Mailer $mailer
    )
    {

        $this->propertyPaymentService = $propertyPaymentService;
        $this->mailer = $mailer;
    }

    public function initializePayment(Request $request)
    {

        /*
                $response = ['status' => false, 'message' => '', 'data' => null, 'statusCode' => 500];
                try {

                    if (is_null($this->request->getContent())) {
                        throw new ApiErrorException(lang('Parameter Error.'));
                    }

                    $params = json_decode($this->request->getContent(), 1);


                    dd($params);


                    $responseData = [
                        'bookingCode' => $bookingCode,
                        'total' => $totalRoomsPrice,
                        'currency' => $currencyCode
                    ];


                    $response = ['status' => 1, 'statusCode' => 200, 'message' => null, 'data' => $responseData];

                } catch (ApiErrorException $e) {
                    $response['message'] = implode(', ', $e->getMessageArr());
                    $response['statusCode'] = 400;
                } catch (Exception $e) {
                    $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
                    Log::error($message);
                    $response['message'] = $e->getMessage();
                    $response['statusCode'] = 500;
                }

                return apiResponse($response['status'], $response['message'], $response['data'], $response['statusCode']);


        */


    }

    public function paymentRedirect(Request $request, $paymentCode)
    {

        $response = ['status' => false, 'message' => ''];

        try {

            $paymentTransaction = $this->propertyPaymentService->getPaymentTransactionDetail($paymentCode);

            if (!$paymentTransaction['status']) {
                throw new ApiErrorException($paymentTransaction['message']);
            }

            $paymentTransaction = $paymentTransaction['data'];

            if ($paymentTransaction['status'] == 1) {
                return redirect()->to($paymentTransaction['paramsArray']['responseUrl']);
            }

            //Set Redirect Status
            $this->propertyPaymentService->updatePaymentTransaction($paymentTransaction['id'], ['status' => 3]);

            if ($paymentTransaction['payment_type_mapping']['payment_type']['pos_code'] == 'POS') {


                //TODO: Burada PAN replace edilecek
                //$this->propertyPaymentService->updatePaymentTransaction($paymentTransaction['id'], ['status' => 3]);

                $formData = $paymentTransaction['extraParamsArray'];
                return view('threeDSecureForm', compact('formData'));

            } elseif ($paymentTransaction['payment_type_mapping']['payment_type']['pos_code'] == 'STR') {

                if (isset($paymentTransaction['extraParamsArray']['redirect']['url'])) {
                    return redirect()->to($paymentTransaction['extraParamsArray']['redirect']['url']);
                }

            } elseif ($paymentTransaction['payment_type_mapping']['payment_type']['pos_code'] == 'ENW') {

                if (isset($paymentTransaction['extraParamsArray']['redirect']['url'])) {
                    return redirect()->to($paymentTransaction['extraParamsArray']['redirect']['url']);
                }

            } elseif ($paymentTransaction['payment_type_mapping']['payment_type']['pos_code'] == 'SPY') {

                $formData = $paymentTransaction['extraParamsArray'];
                return view('threeDSecureForm', compact('formData'));

            } elseif ($paymentTransaction['payment_type_mapping']['payment_type']['pos_code'] == 'MOK') {

                if (isset($paymentTransaction['extraParamsArray'])) {
                    return redirect()->to($paymentTransaction['extraParamsArray']);
                }

            } elseif ($paymentTransaction['payment_type_mapping']['payment_type']['pos_code'] == 'BOG') {

                $redirectUrl = collect($paymentTransaction['extraParamsArray']['links'])->where('method', 'REDIRECT')->first();

                if (isset($redirectUrl['href'])) {
                    return redirect()->to($redirectUrl['href']);
                }

            } elseif ($paymentTransaction['payment_type_mapping']['payment_type']['pos_code'] == 'TBC') {

                $redirectUrl = collect($paymentTransaction['extraParamsArray']['links'])->where('method', 'REDIRECT')->first();

                if (isset($redirectUrl['uri'])) {
                    return redirect()->to($redirectUrl['uri']);
                }

            } elseif ($paymentTransaction['payment_type_mapping']['payment_type']['pos_code'] == 'QNB') {

                $formData = $paymentTransaction['extraParamsArray'];
                return view('threeDSecureForm', compact('formData'));

            } elseif ($paymentTransaction['payment_type_mapping']['payment_type']['pos_code'] == 'WEE') {

                if (isset($paymentTransaction['extraParamsArray']['threeDSecureUrl'])) {
                    return redirect()->to($paymentTransaction['extraParamsArray']['threeDSecureUrl']);
                }

            } elseif ($paymentTransaction['payment_type_mapping']['payment_type']['pos_code'] == 'HLK') {

                $formData = $paymentTransaction['extraParamsArray'];
                return view('threeDSecureForm', compact('formData'));

            } elseif ($paymentTransaction['payment_type_mapping']['payment_type']['pos_code'] == 'ESN') {

                if (isset($paymentTransaction['extraParamsArray']['URL_3DS'])) {
                    return redirect()->to($paymentTransaction['extraParamsArray']['URL_3DS']);
                }

            } elseif ($paymentTransaction['payment_type_mapping']['payment_type']['pos_code'] == 'KVY') {

                $formData = $paymentTransaction['extra_params'];
                echo $formData; die();

            } elseif ($paymentTransaction['payment_type_mapping']['payment_type']['pos_code'] == 'RTL') {

                $extraParams = json_decode($paymentTransaction['extra_params'],1);
                echo $extraParams['form3d_html']; die();

            } elseif ($paymentTransaction['payment_type_mapping']['payment_type']['pos_code'] == 'PYR') {

                $redirectUrl = $paymentTransaction['extraParamsArray']['payload'];

                if (isset($redirectUrl['paymentUrl'])) {
                    return redirect()->to($redirectUrl['paymentUrl']);
                }

            }


        } catch (ApiErrorException $e) {
            $response['message'] = implode(', ', $e->getMessageArr());
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $response['message'] = $e->getMessage();
        }


        //TODO: Burada bir yere yönlendirilmeli
        dd($response);


    }

    public function paymentCheck(Request $request, $paymentCode)
    {

        $responseData = ['status' => false];

        try {

            $checkPayment = $this->propertyPaymentService->checkPayment($paymentCode, $request->all());

            $responseData['paymentCode'] = $checkPayment['data']['paymentCode'];

            if ($checkPayment['status']) {
                $responseData['status'] = true;
                $responseData['bankOrderId'] = $checkPayment['data']['bankOrderId'];
            } else {
                $responseData['message'] = $checkPayment['message'];
            }

            if (isset($checkPayment['data']['paymentTransactionDetail']['property'])) {
                $responseData['paymentTransactionDetail']['amount'] = $checkPayment['data']['paymentTransactionDetail']['amount'];
                $responseData['paymentTransactionDetail']['currency'] = $checkPayment['data']['paymentTransactionDetail']['currency'];
                $responseData['paymentTransactionDetail']['message'] = $checkPayment['data']['paymentTransactionDetail']['message'];
                $responseData['property'] = $checkPayment['data']['paymentTransactionDetail']['property'];
            }

            //$logMessage
            $mailParams = [
                'title' => 'PaymentCheck',
                'logMessage' => '<pre>' . print_r($responseData, true) . '</pre>'
            ];

            $this->mailer->onQueue(
                'logMail',
                new LogMail($mailParams)
            );
            //$logMessage

        } catch (ApiErrorException $e) {
            $responseData['message'] = implode(', ', $e->getMessageArr());
        } catch (Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::error($message);
            $responseData['message'] = $e->getMessage();
        }

        return redirect()->to($checkPayment['data']['responseUrl']);


    }


}
