<?php

namespace App\Classes\Modules\PackingLists\Processors;

use App\Classes\Modules\Orders\Services\FetchesDataFromVTPortal;
use App\Classes\Modules\PackingLists\DataTransferObjects\PackageObject;
use App\Classes\Modules\PackingLists\Services\ListsPackingLists;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\PackageType;
use App\Classes\ValueObjects\Constants\PackingListType;
use App\Models\PackingList;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class FetchPackingListFromVTPortalProcessor
{

    /** @var FetchesDataFromVTPortal */
    private $fetchesDataFRomVTPortal;

    /** @var ListsPackingLists */
    private $listsPackingLists;

    /** @var CreatePackageProcessor */
    private $createPackageProcessor;

    /**
     * FetchPackingListFromVTPortalProcessor constructor.
     * @param FetchesDataFromVTPortal $fetchesDataFRomVTPortal
     * @param ListsPackingLists $listsPackingLists
     * @param CreatePackageProcessor $createPackageProcessor
     */
    public function __construct(FetchesDataFromVTPortal $fetchesDataFRomVTPortal, ListsPackingLists $listsPackingLists, CreatePackageProcessor $createPackageProcessor)
    {
        $this->fetchesDataFRomVTPortal = $fetchesDataFRomVTPortal;
        $this->listsPackingLists = $listsPackingLists;
        $this->createPackageProcessor = $createPackageProcessor;
    }


    /**
     * @return array
     * @throws \App\Classes\Exceptions\AccessForbiddenException
     * @throws \App\Classes\Exceptions\RequestValidationException
     */
    public function execute(){

        $packingLists = PackingList::where('type', '=', PackingListType::SHIPPING_PACKING_LIST)->where('reference', 'not like', '%PO%')->whereIn('claimant_id', [2])->whereIn('status', [ApprovalStatus::PENDING_VERIFICATION, ApprovalStatus::SUSPENDED])->whereDoesntHave('containers', function($query){
            $query->where('status', '=', ApprovalStatus::COMPLETED);
        })->limit(10)->get();

        foreach($packingLists as $packingList){
            try {

                $filter = '["PoID:=%js%'.$packingList->reference.'"]';

                $shippingPackingListsRequest = $this->fetchesDataFRomVTPortal->clientRequest('http://portal.vtnation.com.my/Services/DataControllerService.asmx/GetPage', 'POST', json_decode('{"controller":"Po","view":"grid1","request":{"PageIndex":-1,"PageSize":1000,"Filter":'.$filter.'}}'), '');

                $shippingPackingLists = $this->fetchesDataFRomVTPortal->getResponseBody($shippingPackingListsRequest);

                if(count($shippingPackingLists->Rows)) {

                } else {
                    dump($packingList->reference);
                }

            } catch (GuzzleException $exception) {
                Log::error($exception);
                continue;
            }

        }

        return [];

    }


}
