<?php

namespace App\ShippingMethods;

use Carbon\Carbon;
use App\Models\OrderAddress;
use App\Models\OrderProduct;
use App\Interfaces\ShippingMethodInterface;

class AjexShippingMethod implements ShippingMethodInterface
{
    private $username;
    private $password;
    
    public function __construct()
    {
        $this->username = config('services.shipping.ajex.username');
        $this->password = config('services.shipping.ajex.password');
        $this->product_code = config('services.shipping.ajex.product_code');
    }
    private function CreateAuth()
    {
        $curl = curl_init();
        
        curl_setopt_array($curl, array(
          CURLOPT_URL => 'https://apps-sit.aj-ex.com/authentication-service/api/auth/login',
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => '',
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 0,
          CURLOPT_FOLLOWLOCATION => true,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => 'POST',
          CURLOPT_POSTFIELDS =>'{
            "username":"'.$this->username.'",
            "password":"'.$this->password.'"
        }',
          CURLOPT_HTTPHEADER => array(
            'Content-Type: application/json'
          ),
        ));
        
        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }
    public function processShipping(array $params=[])
    {
        $response = $this->CreateAuth();
        $auth = json_decode($response);
        if(!isset($auth->error))
        {
            $curl = curl_init();
            $order = $params['order'];
            $order_address = OrderAddress::where('order_id',$order->id)->first();

            $products = '';
            $order_products = OrderProduct::where('order_id',$order->id)->get();
            foreach($order_products as $key=>$row)
            {
                $products .=  '{
                                    "weight": 1,
                                    "quantity": '.$row->count.',
                                    "cargoInfo": 
                                        [
                                            {
                                                "name": "'.$row->product->currentDescription->name.'",
                                                "count": '.$row->count.',"totalValue": "'.$row->total.'",
                                                "hsCode": "'.$row->product->code.'",
                                                "countryOfOrigin": "Saudi Arabia"
                                            }
                                        ]
                }';
                if(count($order_products) != $key+1)
                {
                    $products .=',';
                }
            }
            $username = $order->user->role == 'company' ? $order->user->descriptions()->name : $order->user->name;
            $role = $order->user->role == 'company' ? 'ENTERPRISE' : 'INDIVIDUAL';
            $expressType = $order_address->address->country_id == 1 ? 'AJEX DCE' : 'AJEX IRX';
            $latlng = explode(',',settings('latlng'));
            $lat = $latlng[0];
            $lan = substr($latlng[1], 1);
            $dateTime = date('Y-m-d',strtotime($order->updated_at)).'T'.date('H:i:s').'.000+03:00';
            // $dateTime = Carbon::now()->addDay()->setTimezone('GMT+03:00')->format('Y-m-d\TH:i:s \G\M\TP');

            curl_setopt_array($curl, array(
              CURLOPT_URL => 'https://apps-sit.aj-ex.com/order-management/api/v2/order',
              CURLOPT_RETURNTRANSFER => true,
              CURLOPT_ENCODING => '',
              CURLOPT_MAXREDIRS => 10,
              CURLOPT_TIMEOUT => 0,
              CURLOPT_FOLLOWLOCATION => true,
              CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
              CURLOPT_CUSTOMREQUEST => 'POST',
              CURLOPT_POSTFIELDS =>'{
                "orderId": "'.rand(1111,9999).'",
                "orderTime": "'.$dateTime.'",
                "productCode": "'.$this->product_code.'",
                "expressType": "'.$expressType.'",
                "totalDeclaredValue": "'.$order->payment->total.'",
                "declaredCurrency": "SAR",
                "parcelTotalWeight": 1,
                "parcelTotalVolume": "1",
                "pickupMethod": "PICKUP",
                "paymentMethod": "SENDER_INSTALLMENT",
                "customerAccount": "AJS630151000162",
                "buyerName": "'.$username.'",
                "incoterms": "DDP",
                "senderInfo": 
                {
                    "name": "City Bike",
                    "phone": "'.settings('site_phone').'",
                    "email": "'.settings('site_email').'",
                    "contactType": "ENTERPRISE",
                    "addressType": "COORDINATES",
                    "latitude": "'.$lat.'",
                    "longitude": "'.$lan.'"
                },
                "receiverInfo": 
                {
                    "name": "'.$username.'",
                    "phone": "'.$order->user->phone.'",
                    "email": "'.$order->user->email.'",
                    "contactType": "'.$role.'",
                    "addressType": "FREE_TEXT",
                    "country": "'.$order_address->address->country->descriptions(2)->name.'",
                    "countryCode": "'.$order_address->address->country->iso.'",
                    "province": "'.$order_address->address->city->descriptions(2)->name.'",
                    "city": "'.$order_address->address->city->descriptions(2)->name.'",
                    "cityCode": "'.$order_address->address->country->iso.'",
                    "district": "'.$order_address->address->address.'",
                    "detailedAddress": "'.$order_address->address->address.'"
                },
                "parcels": 
                [
                    '.$products.'
                ],
                "additionalInfo": null,
                "customAddress": 
                {
                    "city": "'.$order_address->address->city->descriptions(2)->name.'",
                    "country": "'.$order_address->address->country->descriptions(2)->name.'",
                    "countryCode": "'.$order_address->address->country->iso.'",
                    "detailAddress": "'.$order_address->address->address.'"
                }
            }
            ',
              CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                'Authorization: '.$auth->tokenType.' '.$auth->accessToken.''
              ),
            ));
            
            $response = curl_exec($curl);
            $json_res = $response;
            $response = json_decode($response);
            if($response->responseCode != 100)
            {
                return [__('web.failed')];
            }
            curl_close($curl);
            
            $order->update([
                'ajex_response'=> $json_res,
                'ajex_file' => $response->waybillFileUrl,
                'ajex_number_tracking'=> $response->waybillNumber
                ]);
            return [__('web.success')];
        }
        return [__('web.failed')];
    }

}
