<?php

namespace App\Classes\Modules\Orders\Processors;

use App\Classes\Exceptions\InternalServerErrorException;
use App\Classes\Modules\Orders\Services\FetchesDataFromVTPortal;
use App\Classes\Modules\Addresses\Services\FetchesAddress;

use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Models\PackingList;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Log;

class UpdateDoFromVTPortalProcessor
{
    /** @var FetchesDataFromVTPortal */
    private $fetchesDataFRomVTPortal;

    /** @var FetchesAddress */
    private $fetchesAddress;

    /**
     * FetchDeliveryListFromVTPortalProcessor constructor.
     * @param FetchesDataFromVTPortal $fetchesDataFRomVTPortal
     * @param FetchesAddress $fetchesAddress
     */
    public function __construct(FetchesDataFromVTPortal $fetchesDataFRomVTPortal, FetchesAddress $fetchesAddress)
    {
        $this->fetchesDataFRomVTPortal = $fetchesDataFRomVTPortal;
        $this->fetchesAddress = $fetchesAddress;
    }

    /**
     * @param PackingList $packing_list
     * @return array
     * @throws GuzzleException
     * @throws InternalServerErrorException
     */
    public function execute(PackingList $packing_list) {

        Log::info('Trying to Call UpdateDoFromVTPortalProcessor');

        if(!app()->environment(['production'])){
            return [];
        }

        try {
            $address= $packing_list->owner->addresses()->where('status', ApprovalStatus::APPROVED)->first();
            $order = $packing_list->owner;

            if ($packing_list) {
                $contact = $address->contacts()->first();
                $remark = $address->remarks()->first();

                $remark = $remark ? $remark->content : 'URGENT!!! PLEASE CALL BEFORE ONE DAY DELIVERY.';
                $phone = $contact ? $contact->phone : null;
                $reference = $contact ? $contact->reference : null;

                $status = 'On Hold';

                if (in_array($packing_list->status, [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])) {
                    $status = 'Release';
                }

                $vt_do = $this->fetchesDataFRomVTPortal->clientRequest('http://portal.vtnation.com.my/Services/DataControllerService.asmx/GetPage', 'POST', json_decode('{"controller":"Do","view":"grid1","request":{"PageIndex":-1,"PageSize":10000,"Filter": ["FullMarking:$contains$%js%\"' . $order->reference . '\"\u0000"]}}'), '');

                $vt_do = $this->fetchesDataFRomVTPortal->getResponseBody($vt_do);

                if ($vt_do) {
                    foreach ($vt_do->Rows as $key => $row) {
                        if($row[4] !== $packing_list->containers()->first()->reference) continue;
                        $vt_do_update = $this->fetchesDataFRomVTPortal->clientRequest(
                        'http://portal.vtnation.com.my/Services/DataControllerService.asmx/Execute', 
                        'POST', 
                        json_decode('{
                            "controller": "Do",
                            "view": "editForm1",
                            "args": {
                                "CommandName": "Update",
                                "CommandArgument": "Save",
                                "Path": "ag2/a4",
                                "LastCommandName": "Edit",
                                "Values": [
                                    {
                                        "Name": "ShippingAddress",
                                        "NewValue": "' . $address->street_one . ' ' . $address->street_two  . ' '. $address->district->name.' '. $address->postcode.' '.$address->state->name.' '.$address->country->name.'",
                                        "Modified": true,
                                        "ReadOnly": false,
                                        "Error": null
                                    },
                                    {
                                        "Name": "Attn",
                                        "NewValue": "'.$reference.'",
                                        "Modified": true,
                                        "ReadOnly": false,
                                        "Error": null
                                    },
                                    {
                                        "Name": "Tel",
                                        "NewValue": "'.$phone.'",
                                        "Modified": true,
                                        "ReadOnly": false,
                                        "Error": null
                                    },
                                    {
                                        "Name": "Status",
                                        "NewValue": "' . $status . '",
                                        "Modified": true,
                                        "ReadOnly": false,
                                        "Error": null
                                    },
                                    {
                                        "Name": "Doremarks",
                                        "NewValue": "'. $remark .'",
                                        "Modified": true,
                                        "ReadOnly": false,
                                        "Error": null
                                    },
                                    {
                                        "Name": "DoID",
                                        "OldValue": '.$row[0].',
                                        "NewValue": '.$row[0].',
                                        "Modified": false,
                                        "ReadOnly": true,
                                        "Error": null
                                    }
                                ],
                                "Controller": "Do"
                            }
                        }'), '');
                    }
                }
            }

        } catch (\Exception $exception){
            throw new InternalServerErrorException('failed to approve address due to an error related to VT portal: '.$exception->getMessage());
        }

    }
}
