<?php

namespace App\Http\Controllers\DHL;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use DHL\Client\Web as WebserviceClient;
use DHL\Datatype\AM\Piece;
use DHL\Datatype\AM\SpecialService;
use DHL\Entity\AM\KnownTrackingRequest as Tracking;
use DHL\Entity\AM\ShipmentResponse;
use DHL\Entity\AM\ShipmentRequest;

class DHLInternacionalController extends Controller
{
    private $shpmentRequest;
    private $dhl;
    private $dhlConfig;

    public function __construct(){
        $this->dhlConfig = config('config_dhl.dhl');
        $this->shpmentRequest = new ShipmentRequest();
    }

    public function getStatusTrackingFormate(string $tracking) 
    {
        return $this->getStatusTracking($tracking, true);
    }

    public function getStatusTracking(string $tracking, $formate = null){
        $request = new Tracking();
        $request->Username = $this->dhlConfig['username'];
        $request->Password = $this->dhlConfig['pass'];
        $request->ShippingSystemPlatform = $this->dhlConfig['ShippingSystemPlatform'];
        $request->ShippingSystemPlatformVersion = $this->dhlConfig['SoftwareVersion'];
                

        $request->MessageReference = $this->generateMsnRef('1234567890123456789012345678901');
        $request->MessageTime = date('Y-m-d\TH:i:s\Z');
        $request->LanguageCode = 'spa';
        $request->AWBNumber->addArrayOfAWBNumberItem($tracking);
        $request->LevelOfDetails = 'ALL_CHECKPOINTS';
        $request->PiecesEnabled = 'S';

        //echo $request->toXML();
        $client = new WebserviceClient('production','tracking');

        $data = $client->call($request, 'ns:TrackingResponse');
        if(is_null($formate)){
            return json_encode($data);
        }else{
            try {
                if(isset($data['trackingResponse']) && isset($data['trackingResponse']['TrackingResponse']) &&  isset($data['trackingResponse']['TrackingResponse']['AWBInfo']) && isset($data['trackingResponse']['TrackingResponse']['AWBInfo']['ArrayOfAWBInfoItem'])){
                
                    $d = $data['trackingResponse']['TrackingResponse']['AWBInfo']['ArrayOfAWBInfoItem']['ShipmentInfo'];
                    $event = $d['ShipmentEvent']['ArrayOfShipmentEventItem'];
                    $fecha_guia = '' ;
                    $estado = '' ;
                    $fecha_estado = '' ;
                    $detalle = [];

                    if(count($event) > 0){
                        
                        $fecha_guia =  "{$event[0]['Date']} {$event[0]['Time']}";    
                        $estado = $event[count($event) - 1]['ServiceEvent']['Description'];
                        $fecha_estado = "{$event[count($event) - 1]['Date']} {$event[count($event) - 1]['Time']}";
                        foreach ($event as $key => $value) {
                            $detalle[] = [
                                "descripcion"=>$value['ServiceEvent']['Description'],
                                "fecha"=>$value['Date'],
                                "hora"=>$value['Time']
                            ];
                        }
                    }
                    
                    $format_data = [
                        "nombre_origen"=> $d['OriginServiceArea']['Description'],
                        "nombre_destino"=> $d['DestinationServiceArea']['Description'],
                        "descripcion_estado" => $estado,
                        "fecha_entrega" => $fecha_estado
                    ];
                  
                    $format_data['detalle_estados'] = $detalle;
                    $format_data['detalle_novedades'] = [];
                    $format_data['all_data'] = $d;
    
                    return json_encode($format_data);
                }
            } catch (\Throwable $th) {}
        }
    }

    public function generateTracking(Request $r)
    {
        $data = json_decode($r->getContent());
        #dd($r->all());
        /*$params =array(
            'recipient' => array(
                'PersonName' => 'Yunjie Wang WUMTJ',
                'CompanyName' => 'Yunjie Wang WUMTJ',
                'AddressLine1'=>'261 Quigley Boulevard', PREGUNTAR
                'AddressLine2'=>'Suite 1 # 525953', PREGUNTAR
                'AddressLine3'=>'.',
                'City' => 'New Castle Delaware',
                'PostalCode' => '19720-4187',
                'CountryCode' => 'US', 
                'CountryName' => 'Usa',  PREGUNTAR
                'PhoneNumber' => '+19123735448',
                'PhoneExtension' => '123',
                'FaxNumber' => '+19123735448', 
                'Telex' => '+19123735448',
                'Email' => 'kidwell.lauren@gmail.com-233500113575b.ct.vtex.com',
            ),
            'item'=> array(
                'descripcion' => 'VESTIDO DE BAÑO ODM'
            ), 
            'content' => '8464-ODM_USA',
            'factura' => '002-0293123',
            'precio' =>'39.20',
            'peso' =>'0.2',
            'Length'=>'30',
            'Width'=>'30',
            'Height'=>'30',
            'Weight' => '0.4'
        );
        */
        
        return($this->generateShipment(json_decode(json_encode($data),true)));
    }
    public function generateShipment(array $params) {

        try {
            $this->shpmentRequest->MessageTime = date('Y-m-d\TH:i:s\Z');
        //$this->shpmentRequest->SiteID = "6045775759623619";
        $this->shpmentRequest->MessageReference = $this->generateMsnRef('1234567890123456789012345678901');
        $this->shpmentRequest->ShippingSystemPlatform = $this->dhlConfig['ShippingSystemPlatform'];
        $this->shpmentRequest->ShippingSystemPlatformVersion = $this->dhlConfig['SoftwareVersion'];
        
        $this->shpmentRequest->Username = $this->dhlConfig['username'];
        $this->shpmentRequest->Password = $this->dhlConfig['pass'];

        $this->shpmentRequest->ShipmentInfo->DropOffType = $this->dhlConfig['DropOffType'];
        $this->shpmentRequest->ShipmentInfo->ServiceType = 'P';
        $this->shpmentRequest->ShipmentInfo->Billing->ShippingPaymentType = $this->dhlConfig['ShippingPaymentType'];//'S'; /* S => Shipper R => Recipient */
        $this->shpmentRequest->ShipmentInfo->Billing->ShipperAccountNumber = $this->dhlConfig['shipperAccountNumber'];
        $this->shpmentRequest->ShipmentInfo->Billing->BillingAccountNumber = $this->dhlConfig['billingAccountNumber'];
        
        $this->shpmentRequest->ShipmentInfo->SpecialServices->Service->ServiceType = $this->dhlConfig['ServiceType'];
        $this->shpmentRequest->ShipmentInfo->Currency = $this->dhlConfig['Currency'];
        $this->shpmentRequest->ShipmentInfo->UnitOfMeasurement = $this->dhlConfig['UnitOfMeasurement'];
        $this->shpmentRequest->ShipmentInfo->LabelType = $this->dhlConfig['LabelType'];
        $this->shpmentRequest->ShipmentInfo->LabelOptions->RequestDHLCustomsInvoice = 'Y';
        $this->shpmentRequest->ShipmentInfo->LabelOptions->DHLCustomsInvoiceLanguageCode = $this->dhlConfig['LanguageCode'];
        $this->shpmentRequest->ShipmentInfo->LabelOptions->DHLCustomsInvoiceType = 'COMMERCIAL_INVOICE';
        
        $this->shpmentRequest->ShipmentInfo->ShipmentReferences->ShipmentReference->ShipmentReference = substr($params['item']['descripcion'],0,20);
        $this->shpmentRequest->ShipTimestamp =  date('Y-m-d\TH:i:s \G\M\T+01:00',strtotime(date('Y-m-d\TH:i:s'). ' + 1 days'));
        
        $this->shpmentRequest->PaymentInfo = $this->dhlConfig['PaymentInfo'];

        $this->shpmentRequest->InternationalDetail->Commodities->Description = substr($params['content'],0,20);
        //$this->shpmentRequest->InternationalDetail->Commodities->CustomsValue = '671';
        $this->shpmentRequest->InternationalDetail->Content = 'NON_DOCUMENTS';
        $this->shpmentRequest->InternationalDetail->ExportDeclaration->InvoiceDate = date('Y-m-d');
        $this->shpmentRequest->InternationalDetail->ExportDeclaration->InvoiceNumber = $params['factura'];
        $this->shpmentRequest->InternationalDetail->ExportDeclaration->ExportReasonType = $this->dhlConfig['ExportReasonType'];
        $this->shpmentRequest->InternationalDetail->ExportDeclaration->ExportReason = $this->dhlConfig['ExportReason'];
        $this->shpmentRequest->InternationalDetail->ExportDeclaration->ShipmentPurpose = $this->dhlConfig['ShipmentPurpose'];
        $this->shpmentRequest->InternationalDetail->ExportDeclaration->DocumentFunction = $this->dhlConfig['DocumentFunction'];
        $this->shpmentRequest->InternationalDetail->ExportDeclaration->ExportLineItems->ExportLineItem->ItemNumber = '1';
        $this->shpmentRequest->InternationalDetail->ExportDeclaration->ExportLineItems->ExportLineItem->Quantity = '1';
        $this->shpmentRequest->InternationalDetail->ExportDeclaration->ExportLineItems->ExportLineItem->QuantityUnitOfMeasurement = 'PCS';
        $this->shpmentRequest->InternationalDetail->ExportDeclaration->ExportLineItems->ExportLineItem->ItemDescription = $params['item']['descripcion'];
        $this->shpmentRequest->InternationalDetail->ExportDeclaration->ExportLineItems->ExportLineItem->UnitPrice = $params['precio'];
        $this->shpmentRequest->InternationalDetail->ExportDeclaration->ExportLineItems->ExportLineItem->NetWeight = $params['peso'];
        $this->shpmentRequest->InternationalDetail->ExportDeclaration->ExportLineItems->ExportLineItem->GrossWeight = $params['peso'];
        $this->shpmentRequest->InternationalDetail->ExportDeclaration->ExportLineItems->ExportLineItem->ExportReasonType = $this->dhlConfig['ExportReasonType'];
        $this->shpmentRequest->InternationalDetail->ExportDeclaration->ExportLineItems->ExportLineItem->ManufacturingCountryCode = $this->dhlConfig['ManufacturingCountryCode'];
        $this->shpmentRequest->InternationalDetail->ExportDeclaration->ExportLineItems->ExportLineItem->TaxesPaid = $this->dhlConfig['TaxesPaid'];
        
        //$this->shpmentRequest->InternationalDetail->ExportDeclaration->CustomsDocuments->CustomsDocument->CustomsDocumentType = 'INV';
        //$this->shpmentRequest->InternationalDetail->ExportDeclaration->CustomsDocuments->CustomsDocument->CustomsDocumentID = 'MyDHLAPI - CUSDOC-001';
        $this->shpmentRequest->InternationalDetail->ExportDeclaration->PackageMarks = ' ';
        //$this->shpmentRequest->InternationalDetail->ExportDeclaration->PayerGSTVAT = 'no';

        $this->shpmentRequest->InternationalDetail->ExportDeclaration->Remarks->Remark->RemarkDescription = $params['content'];
        $this->shpmentRequest->InternationalDetail->ExportDeclaration->TermsOfPayment = '';
        $this->shpmentRequest->InternationalDetail->ExportDeclaration->InvoiceInstructions = 'InvoiceInstructions';
        $this->shpmentRequest->InternationalDetail->ExportDeclaration->InvoiceReferences->InvoiceReference->InvoiceReferenceType = $this->dhlConfig['InvoiceReferenceType'];
        $this->shpmentRequest->InternationalDetail->ExportDeclaration->InvoiceReferences->InvoiceReference->InvoiceReferenceNumber = $params['factura'];
       
        $this->shpmentRequest->Ship->Shipper->Contact->CompanyName = isset($params['CompanyName']) ? $params['CompanyName'] : $this->dhlConfig['CompanyName'];
        $this->shpmentRequest->Ship->Shipper->Contact->PersonName = isset($params['PersonName']) ? $params['PersonName'] : $this->dhlConfig['PersonName'];
        $this->shpmentRequest->Ship->Shipper->Contact->PhoneNumber = $this->dhlConfig['PhoneNumber'];
        
        $this->shpmentRequest->Ship->Shipper->Address->addStreetLines(isset($params['AddressLine1']) ? $params['AddressLine1'] : $this->dhlConfig['AddressLine1']);
        $this->shpmentRequest->Ship->Shipper->Address->City = $this->dhlConfig['City'];
        $this->shpmentRequest->Ship->Shipper->Address->PostalCode = $this->dhlConfig['PostalCode'];
        $this->shpmentRequest->Ship->Shipper->Address->CountryCode = $this->dhlConfig['CountryCode'];
        //$this->shpmentRequest->Ship->Shipper->BusinessPartyTypeCode = 'BU';
        
        $this->shpmentRequest->Ship->Recipient->Contact->PersonName = $params['recipient']['PersonName'];
        $this->shpmentRequest->Ship->Recipient->Contact->CompanyName = $params['recipient']['CompanyName'];
        $this->shpmentRequest->Ship->Recipient->Contact->PhoneNumber = $params['recipient']['PhoneNumber'];
        $this->shpmentRequest->Ship->Recipient->Contact->EmailAddress = $params['recipient']['Email'];
        $this->shpmentRequest->Ship->Recipient->Contact->MobilePhoneNumber = $params['recipient']['PhoneNumber'];
        
        $address = $params['recipient']['AddressLine1'] . " " .$params['recipient']['AddressLine2'] . " " .$params['recipient']['AddressLine3'];

        $address1 = substr($address , 0, 45);
        $address2 = substr($address , 44, 45);
        $address3 = substr($address , 90, 45);
        
        $address2 = strlen($address2) == 0 ? '.' : $address2;
        $address3 = strlen($address3) == 0 ? '.' : $address3;

        $this->shpmentRequest->Ship->Recipient->Address->addStreetLines($address1);
        $this->shpmentRequest->Ship->Recipient->Address->addStreetLines2($address2);
        $this->shpmentRequest->Ship->Recipient->Address->addStreetLines3($address3);
        $this->shpmentRequest->Ship->Recipient->Address->City = $params['recipient']['City'];
        $this->shpmentRequest->Ship->Recipient->Address->PostalCode = $params['recipient']['PostalCode'];
        $this->shpmentRequest->Ship->Recipient->Address->CountryCode = $params['recipient']['CountryCode'];
        $this->shpmentRequest->Packages->RequestedPackages->addAtributte('number','1');
        $this->shpmentRequest->Packages->RequestedPackages->Weight = $params['peso'];
        $this->shpmentRequest->Packages->RequestedPackages->PackageContentDescription = $params['content'] . " " .$params['factura'];
        $this->shpmentRequest->Packages->RequestedPackages->Dimensions->Length = $params['Length'];
        $this->shpmentRequest->Packages->RequestedPackages->Dimensions->Width = $params['Width'];
        $this->shpmentRequest->Packages->RequestedPackages->Dimensions->Height = $params['Height'];
        
        $start = microtime(true);
        
        //$client = new WebserviceClient('staging');
        $client = new WebserviceClient('production');
        $data = $client->call($this->shpmentRequest);
        
            if(isset($data['PackagesResult']['PackageResult']['TrackingNumber']) && isset($data['LabelImage']['GraphicImage'])){
                $trakingCode = $data['PackagesResult']['PackageResult']['TrackingNumber'];
                $trackingPdf = $data['LabelImage']['GraphicImage'];
                $comercialInvoice = $data['Documents']['Document']['DocumentImage'];
                #return response()->json(['codigo_remision' => $trakingCode, 'pdf_guia' => $trackingPdf, 'pdf_rotulo' => $trackingPdf]);
                return response()->json(['codigo_remision' => $trakingCode, 'pdf_guia' => $trackingPdf, 'pdf_rotulo' => $comercialInvoice]);
            }else{
                return json_encode($data);
            }
        
        } catch (\Throwable $th) {
            return json_encode($th);
        }
        
    }

    private function generateMsnRef($text)
    {
        $count = strlen($text);
        $output = null;
            for($i=0; $i < 30 - $count; $i++) {
                $output .= rand(1,9);
            }
        return strtoupper ($text).'-'.$output;        
    }
}
