<?php

namespace App\Core\Payment\Esnekpos;

use App\Exceptions\ApiErrorException;
use App\Exceptions\ApplicationError;
use Auth;
use Carbon\Carbon;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ServerException;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Log;
use Exception;

class Esnekpos
{

    private $requestUrl;

    public function __construct($paymentInitializeParam)
    {
        $this->restClient = new Client();

        $this->requestUrl = 'https://posservice.esnekpos.com';
        if ($paymentInitializeParam['env'] == 'test') {
            $this->requestUrl = 'https://posservicetest.esnekpos.com';
        }


        $this->merchant = $paymentInitializeParam['merchant'];
        $this->merchantKey = $paymentInitializeParam['merchantKey'];
        $this->contactMail = $paymentInitializeParam['contactMail'];
        $this->ipAddress = isset($paymentInitializeParam['ipAddress']) ? $paymentInitializeParam['ipAddress'] : '185.137.215.118';

        $this->currencyMapping = [
            'TRY' => 'TRY',
            'USD' => 'USD',
            'EUR' => 'EUR',
            'GBP' => 'GBP',
        ];

    }

    private function makeRequest($method, $payloadData)
    {

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

        try {

            $requestParams['headers']['Content-Type'] = 'application/json';

            $requestParams['body'] = json_encode($payloadData);

            $result = $this->restClient->post($this->requestUrl . '/' . $method, $requestParams);

            $getResponseBody = $result->getBody()->getContents();
            $getResponseData = $getResponseBody ? json_decode($getResponseBody, 1) : [];

            if ($getResponseData['STATUS'] == 'SUCCESS') {
                $response = [
                    'status' => true,
                    'serviceResponse' => $getResponseData
                ];
            } else {
                throw new Exception($getResponseData['RETURN_MESSAGE']);
            }

        } catch (ClientException  $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            $response['message'] = $message;
            Log::debug($message);

        } catch (ServerException | Exception $e) {
            $message = $e->getFile() . " " . $e->getLine() . " " . $e->getMessage();
            Log::debug($message);
            $response['message'] = $e->getMessage();

        }

        if (!$response['status']) {
            Log::error($method);
            Log::error($payloadData);
            Log::error($response);
        }

        if (isset($getResponseData)) {
            $response['serviceResponse'] = $getResponseData;
        }

        return $response;

    }


    public function generateHashKey($total, $installment, $currency_code, $invoice_id)
    {

        $data = $total . '|' . $installment . '|' . $currency_code . '|' . $this->merchantKey . '|' . $invoice_id;

        $iv = substr(sha1(mt_rand()), 0, 16);
        $password = sha1($this->appSecret);

        $salt = substr(sha1(mt_rand()), 0, 4);
        $saltWithPassword = hash('sha256', $password . $salt);

        $encrypted = openssl_encrypt("$data", 'aes-256-cbc', "$saltWithPassword", null, $iv);

        $msg_encrypted_bundle = "$iv:$salt:$encrypted";
        $msg_encrypted_bundle = str_replace('/', '__', $msg_encrypted_bundle);

        return $msg_encrypted_bundle;
    }

    public function EYV3DPay($param)
    {

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

            $param['creditCard']['installment'] = $param['creditCard']['installment'] == 0 ? 1 : $param['creditCard']['installment'];

            $items = [];
            $items[] = [
                'PRODUCT_ID' => $param['orderCode'],
                'PRODUCT_NAME' => 'Booking',
                'PRODUCT_CATEGORY' => 'Booking',
                'PRODUCT_DESCRIPTION' => 'Booking',
                'PRODUCT_AMOUNT' => $param['amount']
            ];

            $method = 'api/pay/EYV3DPay';
            $payloadData = [
                'Config' => [
                    'MERCHANT' => $this->merchant,
                    'MERCHANT_KEY' => $this->merchantKey,
                    'BACK_URL' => $param['paymentCheckUrl'],
                    'PRICES_CURRENCY' => isset($this->currencyMapping[$param['currencyCode']]) ? $this->currencyMapping[$param['currencyCode']] : $param['currencyCode'],
                    'ORDER_REF_NUMBER' => $param['orderId'],
                    'ORDER_AMOUNT' => $param['amount'],
                ],
                'CreditCard' => [
                    'CC_NUMBER' => $param['creditCard']['number'],
                    'EXP_MONTH' => $param['creditCard']['expiryMonth'],
                    'EXP_YEAR' => $param['creditCard']['expiryYear'],
                    'CC_CVV' => $param['creditCard']['cvv'],
                    'CC_OWNER' => $param['creditCard']['holderName'],
                    'INSTALLMENT_NUMBER' => $param['creditCard']['installment'],
                ],
                'Customer' => [
                    'FIRST_NAME' => $param['orderId'],
                    'LAST_NAME' => $param['orderId'],
                    'MAIL' => $this->contactMail,
                    'PHONE' => '5555555555',
                    'CITY' => $param['orderId'],
                    'STATE' => $param['orderId'],
                    'ADDRESS' => $param['orderId'],
                    'CLIENT_IP' => $this->ipAddress,
                ],
                'Product' => $items
            ];

            $checkRequest = $this->makeRequest($method, $payloadData);

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

            $response = [
                'status' => true,
                'data' => $checkRequest['serviceResponse']
            ];


        } catch (ApiErrorException $e) {
            $response = ['status' => false, 'message' => $e->getMessage()];
        } catch (Exception $e) {
            $response = ['status' => false, 'message' => $e->getMessage()];
            Log::error($response);
        }

        return $response;

    }

    public function checkPaymentStatus($orderId)
    {

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

            $method = 'api/services/ProcessQuery';
            $payloadData = [
                'MERCHANT' => $this->merchant,
                'MERCHANT_KEY' => $this->merchantKey,
                'ORDER_REF_NUMBER' => $orderId,
            ];

            $checkStatusRequest = $this->makeRequest($method, $payloadData);

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

            if ($checkStatusRequest['serviceResponse']['STATUS'] != 'SUCCESS') {
                throw new ApiErrorException($checkStatusRequest['message']);
            }

            $response = [
                'status' => true,
                'data' => $checkStatusRequest['serviceResponse']
            ];

        } catch (ApiErrorException $e) {
            $response = ['status' => false, 'message' => $e->getMessage()];
        } catch (Exception $e) {
            $response = ['status' => false, 'message' => $e->getMessage()];
            Log::error($response);
        }

        if (isset($checkStatusRequest['serviceResponse'])) {
            $response['serviceResponse'] = $checkStatusRequest['serviceResponse'];
        }

        return $response;

    }

}
