<?php

namespace App\Core\Payment\Sipay;

use App\Exceptions\ApiErrorException;
use App\Exceptions\ApplicationError;
use Auth;
use Carbon\Carbon;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
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 Sipay
{

    private $requestUrl;

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

        $this->requestUrl = 'https://app.sipay.com.tr/ccpayment';
        if ($paymentInitializeParam['env'] == 'test') {
            $this->requestUrl = 'https://provisioning.sipay.com.tr/ccpayment';
        }


        $this->merchantId = $paymentInitializeParam['merchantId'];
        $this->merchantKey = $paymentInitializeParam['merchantKey'];
        $this->appKey = $paymentInitializeParam['appKey'];
        $this->appSecret = $paymentInitializeParam['appSecret'];

        $this->getAccessToken = $this->getAccessToken();

    }

    private function makeRequest($method, $payloadData)
    {

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

        try {

            $requestParams['headers']['Content-Type'] = 'application/json';
            if ($method != 'api/token') {
                $requestParams['headers']['Authorization'] = 'Bearer ' . $this->getAccessToken;
            }


            $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_code'] == 100) {
                $response = [
                    'status' => true,
                    'serviceResponse' => $getResponseData
                ];
            } else {
                $response['message'] = $getResponseData['status_description'];
                $response['serviceResponse'] = $getResponseData;
            }


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

        } catch (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);
        }

        return $response;

    }

    private function getAccessToken()
    {

        $method = 'api/token';
        $payloadData = [
            'app_id' => $this->appKey,
            'app_secret' => $this->appSecret,
        ];

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

        if ($getTokenDataRequest['status']) {
            $getTokenData = $getTokenDataRequest['serviceResponse']['data']['token'];
        }

        return $getTokenData;
    }

    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 generateRefundHashKey($invoice_id, $merchant_key, $app_secret)
    {
        $data = $invoice_id . '|' . $merchant_key;
        $iv = substr(sha1(mt_rand()), 0, 16);
        $password = sha1($app_secret);
        $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";
        $hash_key = str_replace('/', '__', $msg_encrypted_bundle);
        return $hash_key;
    }

    public function paySmart3D($param)
    {

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

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

            $generateHashKey = $this->generateHashKey($param['amount'], $param['creditCard']['installment'], $param['currencyCode'], $param['orderId']);

            $items = [];
            $items[] = [
                'name' => 'Booking',
                'price' => $param['amount'],
                'quantity' => 1,
                'description' => $param['orderCode'],
            ];

            $payment3dFormData['gateway'] = $this->requestUrl . '/api/paySmart3D';

            $payment3dFormData['inputs'] = [
                'currency_code' => $param['currencyCode'],
                'installments_number' => $param['creditCard']['installment'],
                'invoice_id' => $param['orderId'],
                'invoice_description' => $param['orderCode'],
                'total' => $param['amount'],
                'merchant_key' => $this->merchantKey,
                'items' => json_encode($items),
                //'name' => $param['name'],
                //'surname' => $param['surname'],
                'hash_key' => $generateHashKey,
                'return_url' => $param['paymentCheckUrl'],
                'cancel_url' => $param['paymentCheckUrl'],
                'cc_holder_name' => $param['creditCard']['holderName'],
                'cc_no' => $param['creditCard']['number'],
                'expiry_month' => $param['creditCard']['expiryMonth'],
                'expiry_year' => $param['creditCard']['expiryYear'],
                'cvv' => $param['creditCard']['cvv'],
                'transaction_type' => 'Auth',
                'is_comission_from_user' => '2',
                'response_method' => 'GET',
            ];

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

        } 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 {

            $generateHashKey = $this->generateRefundHashKey($orderId, $this->merchantKey, $this->appSecret);

            $method = 'api/checkstatus';
            $payloadData = [
                'invoice_id' => $orderId,
                'merchant_key' => $this->merchantKey,
                'include_pending_status' => true,
                'hash_key' => $generateHashKey
            ];

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

            if (!$checkstatusRequest['status']) {
                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;

    }

}
