<?php

namespace App\Classes\Modules\Orders\Processors;

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

use App\Classes\Modules\Schedules\DataTransferObjects\ScheduleObject;
use App\Classes\Modules\Schedules\Services\CreatesSchedule;
use App\Classes\Modules\Transports\DataTransferObjects\TransportObject;
use App\Classes\Modules\Transports\Services\CreatesTransport;
use App\Classes\Modules\Unity\Services\UpdatesContractObligation;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\OrderRoleTypes;
use App\Classes\ValueObjects\Constants\PackingListType;
use App\Classes\ValueObjects\Constants\TransportType;
use App\Models\PackingList;
use App\Models\Transport;
use Carbon\Carbon;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Log;

use Illuminate\Http\Request;

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

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

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

    /**
     * @return array
     */
    public function execute($address) {

        try {
            $order = $address->owner()->orderBy('id', 'desc')->first();
            $packing_list = $order->packingLists()->orderBy('id', 'desc')->first();

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

                $status = 'Release';

                if ($packing_list->status == ApprovalStatus::PENDING_VERIFICATION) {
                    $status = 'Release';
                }
                else if($packing_list->status == ApprovalStatus::SUSPENDED) {
                    $status = 'On Hold';

                }

                $vt_do = $this->fetchesDataFRomVTPortal->clientRequest(
                    'http://portal.vtnation.com.my/Services/DataControllerService.asmx/GetPage', 
                    'POST', 
                    json_decode('{
                        "controller": "Do",
                        "view": "grid1",
                        "request": {
                        "PageIndex": -2,
                        "PageSize": 10,
                        "PageOffset": 0,
                        "SortExpression": "",
                        "GroupExpression": "",
                        "Filter": [
                            "FullMarking:$contains$%js%\"' . $order->reference . '\"\u0000"
                        ],
                        "ContextKey": "view2",
                        "FilterIsExternal": true,
                        "LookupContextFieldName": null,
                        "LookupContextController": null,
                        "LookupContextView": null,
                        "LookupContext": null,
                        "Inserting": false,
                        "LastCommandName": null,
                        
                        "DoesNotRequireData": false,
                        "LastView": "grid1",
                        "Tag": null,
                        "RequiresFirstLetters": false,
                        "ViewType": "Grid",
                        "SupportsCaching": true,
                        "SystemFilter": null,
                        "RequiresRowCount": true,
                        "QuickFindHint": null,
                        "RequiresPivot": false,
                        "PivotDefinitions": null,
                        "RequiresMetaData": true
                        }
                        }'
                    ), '');

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

                if ($vt_do) {
                    foreach ($vt_do->Rows as $key => $row) {

                        $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  . '",
                                    "Modified": true,
                                    "ReadOnly": false,
                                    "Error": null
                                  },
                                  {
                                    "Name": "Attn",
                                    "NewValue": "' . $contact->reference . '",
                                    "Modified": true,
                                    "ReadOnly": false,
                                    "Error": null
                                  },
                                  {
                                    "Name": "Tel",
                                    "NewValue": "' . $contact->phone . '",
                                    "Modified": true,
                                    "ReadOnly": false,
                                    "Error": null
                                  },
                                  {
                                    "Name": "Status",
                                    "NewValue": "' . $status . '",
                                    "Modified": true,
                                    "ReadOnly": false,
                                    "Error": null
                                  },
                                  {
                                    "Name": "Doremarks",
                                    "NewValue": "' . $remark->content . '",
                                    "Modified": true,
                                    "ReadOnly": false,
                                    "Error": null
                                  },
                                  {
                                    "Name": "ModifiedBy",
                                    "OldValue": "CIEF",
                                    "NewValue": "CIEF",
                                    "Modified": false,
                                    "ReadOnly": false,
                                    "Error": null
                                  },
                                  {
                                    "Name": "DoID",
                                    "OldValue": 1471,
                                    "NewValue": ' . $row[0] . ',
                                    "Modified": false,
                                    "ReadOnly": true,
                                    "Error": null
                                  }
                                ],
                                "ContextKey": "do",
                                "Controller": "Do",
                                "View": "editForm1",
                                "LastView": "grid1",
                                "Tag": null,
                                "Filter": [
                                  "DoID:=%js%' . $row[0] . '",
                                  "ContainerID:=%js%' . $row[1] . '"
                                ],
                                "SortExpression": "",
                                "GroupExpression": "",
                                "SelectedValues": []
                              }
                        }'), '');
                    }
                }
            }

        } catch (\Exception $exception){
            Log::error($exception);
        }

        return [];
    }
}
