<?php

namespace App\Classes\Modules\Orders\Processors;

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

use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\PackingListType;
use App\Models\PackingList;
use Illuminate\Support\Facades\Log;

class UpdateDoFromYDPortalProcessor
{
    /** @var FetchesDataFromYDPortal */
    private $fetchesDataFRomYDPortal;

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

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

    /**
     * @param PackingList $packingList
     * @return void
     * @throws InternalServerErrorException
     */
    public function execute(PackingList $packingList) {
        if(!app()->environment(['production'])){
            return;
        }

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

            if (!in_array($packingList->status, [ApprovalStatus::APPROVED, ApprovalStatus::COMPLETED])) {
                return;
            }

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

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

            if(!$phone || !$reference) throw new MalformedRequestException('Can\'t release this packing list because it doesn\'t have the person in charge contact information');
            $this->fetchesDataFRomYDPortal->clientRequest(
                'http://www.yd-wl.com/api/UpdateOrderAddress.ashx',
                'POST',
                [
                    'expressno' => $packingList->reference,
                    'customers_name' => $reference,
                    'cellphone' => $phone,
                    'postcode' => $address->postcode,
                    'streetAddress' => $address->street_one . ' ' . $address->street_two  . ' '. $address->district->name.' '. $address->post_code.' '.$address->state->name.' '.$address->country->name.' '.$address->postcode.' || '.$remark

                ]);


        } catch (\Exception $exception){
            throw new InternalServerErrorException('failed to approve address due to an error related to YD portal');
        }
    }
}
