<?php
namespace Modules\Order\Repositories\Payment;

use Illuminate\Support\Facades\Config;
use Modules\Order\Interfaces\PaymentInterface;
use Modules\User\Services\AccountService;

class MyFatoorahPayment implements PaymentInterface
{
    public function payment($requestContent)
    {
        $status = 400;
        $message = [__('web.checkinputs')];
        $RedirectUrl = route('web.checkout.order');

        $username= Config::get('app.username');
        $password=Config::get('app.password');
        $tokenApi=Config::get('app.tokenApi');
        $createPay=Config::get('app.createPay');

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $tokenApi);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query(array('grant_type' => 'password', 'username' => $username, 'password' => $password)));
        $result = curl_exec($curl);

        $info = curl_getinfo($curl);

        curl_close($curl);
        $json = json_decode($result, true);


        // var_dump($json);
        if (isset($json['access_token']) && !empty($json['access_token'])) {
            $access_token = $json['access_token'];
        } else {
            $access_token = '';
        }
        if (isset($json['token_type']) && !empty($json['token_type'])) {
            $token_type = $json['token_type'];
        } else {
            $token_type = '';
        }


        $user = (new AccountService())->getAccount();
        $user = $user['user'];
        $name = $user->name;
        $email = is_null($user->email) ? settings('site_email') : $user->email;
        $expire = date('Y-m-d',strtotime('+1 months')).'T13:30:17.812Z';
        if (isset($json['access_token']) && !empty($json['access_token'])) {
            //echo "Token Generated Successfully.<br>";

            $t = time();
            $post_string = '{
                "InvoiceValue": "' . $requestContent['total'] . '",
                "CustomerName": "' . $name . '",
                "CustomerBlock": "Block",
                "CustomerStreet": "Street",
                "CustomerHouseBuildingNo": "Building no",
                "CustomerCivilId": "123456789124",
                "CustomerAddress": "Payment Address",
                "CustomerReference": "' . $t . '",
                "DisplayCurrencyIsoAlpha": "SAR",
                "CountryCodeId": "+966",
                "CustomerMobile": "0000000000",
                "CustomerEmail": "' . $email . '",
                "DisplayCurrencyId": 3,
                "SendInvoiceOption": 1,
                "InvoiceItemsCreate": [
                    {
                        "ProductId":null,
                        "ProductName": " العمولة ",
                        "Quantity": 1,
                        "UnitPrice": "' . intval($requestContent['total']) . '"
                    }
                ],
                "CallBackUrl":  "' . route('web.checkout.payment') . '",
                "Language": 2,
                "ExpireDate": "'.$expire.'",
                "ApiCustomFileds":"token=' . $requestContent['token'] . '&lang=' . getCurrentLocale() . '",
                "ErrorUrl": "' . route('web.checkout.payment') . '"
            }';
            //   var_dump($post_string);exit;
            $soap_do = curl_init();
            curl_setopt($soap_do, CURLOPT_URL, $createPay);
            curl_setopt($soap_do, CURLOPT_CONNECTTIMEOUT, 10);
            curl_setopt($soap_do, CURLOPT_TIMEOUT, 10);
            curl_setopt($soap_do, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($soap_do, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($soap_do, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($soap_do, CURLOPT_POST, true);
            curl_setopt($soap_do, CURLOPT_POSTFIELDS, $post_string);
            curl_setopt($soap_do, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8', 'Content-Length: ' . strlen($post_string), 'Accept: application/json', 'Authorization: Bearer ' . $access_token));
            $result1 = curl_exec($soap_do);

            $err = curl_error($soap_do);
            $json1 = json_decode($result1, true);

            // echo "<pre>";print_r($json1);die;
            // echo json_encode($json1['IsSuccess']);exit;

            if ($json1['IsSuccess']) {
                $RedirectUrl = $json1['RedirectUrl'];

            } else {
                $RedirectUrl =  route('web.checkout.order');
            }
        } else {
            $RedirectUrl = route('web.checkout.order');

            // print_r("Error: " . $json['error'] . "<br>Description: " . $json['error_description']);
        }

        return $RedirectUrl;
    }
}
