<?php
namespace App\Services\Payment;

use App\Services\Payment\PaymentInterface;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use App\Models\Order;
use App\Models\OrderPayment;
use App\Models\ReservationPayment;
use Carbon\Carbon;

class MyFatoorahPayment implements PaymentInterface
{
    public function payment($content) :array
    {
        $status = 400;
        $message = __('web.failed');
        $redirect = $content['url'];
        $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 = Auth::user();
        // if (isset($json['access_token']) && !empty($json['access_token'])) {
        //     //echo "Token Generated Successfully.<br>";

        //     $expire = date('Y-m-d',strtotime('+1 months')).'T13:30:17.812Z';
        //     $t = time();
        //     $post_string = '{
        //         "InvoiceValue": "' . $content['total'] . '",
        //         "CustomerName": "' . settings('website_name') . '",
        //         "CustomerBlock": "Block",
        //         "CustomerStreet": "Street",
        //         "CustomerHouseBuildingNo": "Building no",
        //         "CustomerCivilId": "123456789124",
        //         "CustomerAddress": "Payment Address",
        //         "CustomerReference": "' . $t . '",
        //         "DisplayCurrencyIsoAlpha": "SAR",
        //         "CountryCodeId": "+966",
        //         "CustomerMobile": "'.$user->phone.'",
        //         "CustomerEmail": "' . settings('site_email') . '",
        //         "DisplayCurrencyId": 3,
        //         "SendInvoiceOption": 1,
        //         "InvoiceItemsCreate": [
        //             {
        //                 "ProductId":null,
        //                 "ProductName": " '.$content['status'].' ",
        //                 "Quantity": 1,
        //                 "UnitPrice": "' . intval($content['total']) . '"
        //             }
        //         ],
        //         "CallBackUrl":  "' . $content['payment_status'] . '",
        //         "Language": 2,
        //         "ExpireDate": "'.$expire.'",
        //         "ApiCustomFileds":"token=' . $content['token'] . '&failed_url=' . $content['url'] . '&lang=' . getCurrentLocale() . '",
        //         "ErrorUrl": "' . $content['payment_status'] . '"
        //     }';

        //     //   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);

        //     if ($json1['IsSuccess']) {

        //         $status = 200;
        //         $message = __('web.success');

        //         $redirect = $json1['RedirectUrl'];
        //     }
        // }
        
        
        $user = Auth::user();
        if($content['type'] == 'order')
        {
            $expire = date('Y-m-d',strtotime('+1 months')).'T13:30:17.812Z';
        }
        else
        {
            $now = Carbon::now();
            
            $now->addMinutes(10);
            
            $expire_time = $now->format('Y-m-d H:i:s');
            $expire = date('Y-m-d\TH:i:s.v\Z',strtotime('+10 minutes'));
        }
        $access_token = config('app.accessToken');
        
        if ($access_token) {

            $t = time();
            $post_string = '{
                "InvoiceValue": "' . $content['total'] . '",
                "NotificationOption" : "LNK",
                "CustomerName": "' . settings('website_name') . ' '. $user->phone . '",
                "CustomerBlock": "Block",
                "CustomerStreet": "Street",
                "CustomerHouseBuildingNo": "Building no",
                "CustomerCivilId": "123456789124",
                "CustomerAddress": {
                "Block": "string",
                "Street": "string",
                "HouseBuildingNo": "string",
                "Address": "address",
                "AddressInstructions": "string"
                },
                "ExpiryDate": "'.$expire.'",
                "CustomerReference": "' . $t . '",
                "DisplayCurrencyIso": "SAR",
                "CountryCodeId": "+966",
                "CustomerMobile": "'. $user->phone .'",
                "CustomerEmail": "' . settings('site_email') . '",
                "DisplayCurrencyId": 3,
                "SendInvoiceOption": 1,
                "InvoiceItemsCreate": [
                    {
                        "ProductId":null,
                        "ProductName": " طلب ",
                        "Quantity": 1,
                        "UnitPrice": "' . intval($content['total']) . '"
                    }
                ],
                "CallBackUrl":  "' . $content['payment_status'] . '",
                "Language": "EN",
                "ApiCustomFileds":"token=' . $content['token'] . '&lang=' . getCurrentLocale() . '",
                "ErrorUrl": "' . $content['payment_status'] . '"
            }';

            $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);
            // dd($content);
            // echo "<pre>";print_r($json1);die;
            // echo json_encode($json1['IsSuccess']);exit;

            if ($json1['IsSuccess']) {
                $redirect = $json1['Data']['InvoiceURL'];
                if($content['type'] == 'order')
                {
                    $pay= OrderPayment::where('order_id',$content['id'])->first();
                }
                else
                {
                    $pay= ReservationPayment::where('reservation_id',$content['id'])->first();
                }
                
                if($pay) {
                    $pay->update(['payment_id' => $json1['Data']['InvoiceId']]);
                    if($content['type'] == 'reservation')
                    {
                        $pay->reservation->update(['link_expire_at' => $expire_time]);
                    }
                }
                $status = 200;
                $message = __('web.success');

            } else {
                $redirect =  $content['url'];
            }
        } else {
            $redirect = $content['url'];
        }
        
        $response =
            [
                'status' => $status,
                'data'=> $redirect,
                'message' => $message,
            ];
        return $response;
    }
}
