<?php
/**
 *
 * NOTICE OF LICENSE
 *
 * @author     Artneo
 * @copyright  InPost
 * @license   http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
 *
 *
 */

if (!defined('_PS_VERSION_')) {
    exit;
}
require_once(dirname(__FILE__) . '/InpostModel.php'); //AR
//require_once(dirname(__FILE__) . '/InpostExtends.php'); //AR

class InpostConnector
{
    public $login       = '';
    public $password    = '';
    public $country     = '';
    public $api_url     = '';
    public $error       = 0;
    public $msg         = '';
    const FILE          = 'inpostconnector';
    const INPOST_COUNTRY_1 = 'PL';
    const INPOST_COUNTRY_2 = 'FR';
    const INPOST_COUNTRY_3 = 'IT';
    public function __construct()
    {

        if (Configuration::get('INPOST_LOGIN')) {
            $this->getData();
//            $this->getCustomer();
        }
    }
    private function makeCurl($path, $fields = [], $method = 'GET')
    {
        $path = str_replace(' ', '', $path);
        $headers = array(
            "Authorization: Bearer $this->password"
        );
        $ch = curl_init($this->api_url.$path);


        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        if ($fields || $method === 'POST') {
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, Tools::jsonEncode($fields));
            $headers[] = "Content-Type: application/json";
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        if (strpos($path, 'sticker') !== false) {
            curl_setopt($ch, CURLOPT_TIMEOUT, 20);
            $response =  curl_exec($ch);
        } else
        {
            curl_setopt($ch, CURLOPT_TIMEOUT, 5);
            $response = Tools::jsonDecode(curl_exec($ch));
        }

        curl_close($ch);
        return $response;
    }


    private function getData()
    {
        $this->login =  Configuration::get('INPOST_LOGIN');
        $this->password = Configuration::get('INPOST_PASSWORD');
        $this->country =  Configuration::get('INPOST_COUNTRY');
        $this->api_url = Configuration::get('INPOST_EEIAU');

    }

    public function getMachine($id)
    {
        if (!$id) {
            return false;
        }
        $path = "/machines/{$id}";
        return $this->makeCurl($path, [], 'GET');
    }
    public function getCustomer()
    {
        if (!Configuration::get('INPOST_LOGIN')) {
            return false;
        }
        $path = "/customers/{$this->login}";

        $response =  $this->makeCurl($path);
        if (!$response) {
            $this->error = 1;
            $this->msg = 'Unexpected Error';
            return false;
        }
        if (property_exists($response, 'status_code')) {
            $this->error = 1;
            $this->msg = $response->message;
            return false;
        }
        return $response;
    }
    public function getFormattedCustomerData()
    {
        $response = $this->getCustomer();

        if (!$response || property_exists($response, 'status_code')) {
            return false;
        }
        $flat = '';
        if (property_exists($response, 'address')) {
			if (property_exists($response->address, 'flat_no')) {
				$flat = $response->address->flat_no;
			}
        }

        $company_name = '';
        if (property_exists($response, 'company_name')) {
            $company_name = $response->company_name;
        }
        return [
            'INPOST_SENDER_STREET'      => (property_exists($response,'address'))?$response->address->street:'',
            'INPOST_SENDER_BUILDING_NO' => (property_exists($response,'address'))?$response->address->building_no:'',
            'INPOST_SENDER_FLAT_NO'     => $flat,
            'INPOST_SENDER_POSTCODE'    => (property_exists($response,'address'))?$response->address->post_code:'',
            'INPOST_SENDER_CITY'        => (property_exists($response,'address'))?$response->address->city:'',
            'INPOST_SENDER_PHONE'       => (property_exists($response,'phone'))?$response->phone:'',
            'INPOST_SENDER_EMAIL'       => (property_exists($response,'email'))?$response->email:'',
            'INPOST_SENDER_FIRSTNAME' => (property_exists($response,'first_name'))?$response->first_name:'',
            'INPOST_SENDER_LASTNAME' => (property_exists($response,'last_name'))?$response->last_name:'',
            'INPOST_SENDER_COMPANY_NAME'              => $company_name
        ];
    }
    public function getPriceList()
    {
        $path = "/customers/{$this->login}/pricelists";
        $response = $this->makeCurl($path);
        return $response;
    }
    public function testMethod()
    {

        $path = "v4/parcels/INP000000001262/sticker";

        return $this->makeCurl($path);
    }

    public function createParcelAndPrintManifest()
    {

        $package = $this->createParcel();

        if (is_array($package)) {
            return $package;
        }

        if (property_exists($package, 'id')) {
            $package = $this->payForParcel($package->id);
			
			
			
            if (property_exists($package, 'status_code')) {
                return ['error' => 1, 0 => $package->message];
            }
            $createSticker = $this->createSticker($package->id);
            if (is_array($createSticker)) {
                $inpost = Module::getInstanceByName('inpost');
                $createSticker[1] = $inpost->l('Package generated successfully without a label');

                return $createSticker;
            }
            $package = $this->getParcel($package->id);
            InpostPackages::changeParcelStatus($package->id, $package->status);
            InpostModel::saveSticker($package, Tools::getValue('id_order'), 1);
        }


        return $package;
    }

    public function createAndDownloadManifest()
    {
        $parcel_id = Tools::getValue('parcel_id');
        $package = $this->getParcel($parcel_id);
        if (!property_exists($package, 'status') || $package->status == 'created') {
            $package = $this->payForParcel($parcel_id);

            if (property_exists($package, 'status_code')) {
                return ['error' => 1, 0 => $package->message];
            }

        }

        $createSticker = $this->createSticker($parcel_id);
        if (is_array($createSticker)) {
            return $createSticker;
        }
        InpostModel::saveSticker($package, Tools::getValue('id_order'), 1);

        return $package;
    }
    /**
     * a) receiver_email – string value, email format,
     * b) receiver_phone (required) – string value, phone number format,
     * c) source_machine_id – string value, existing easyPack machine id (used only in Sending from
     * PM scenario; leave empty for regular address2box parcels)
     * d) target_machine_id (required) – string value, existing easyPack machine id,
     * e) size (required) – string value, one of: “A”, “B” or “C”,
     * f) cod_amount – numeric value (CoD stays for “Cash on Delivery”),
     * g) customer_reference – string value, up to 255 characters,
     * h) sender_address (building_no, flat_no, street, post_code, city, province) – sender address data.
     * Pass it while sending a parcel if you want to overwrite an address assigned to your easyPack
     * account. Validates as an address when updating customer,
     * i) weight – weight in grams, integer value greater than 0,
     * j) additional1 (required) – Customer COD reference number (sent to Bank), string value, up to
     * 255 characters,
     * k) additional2 – Parcel reference number (sent to Bank), string value, up to 255 characters.
     * @todo-damian UBEZPIECZENIE, UWAGI DO ZAMOWIENIA, POBRANIE
     */
    public function createParcel()
    {
        $inpost = Module::getInstanceByName('inpost');
        $dispatch_points_id = 0;
        $method_giving = Tools::getValue('method_giving');
        $sender = Tools::getValue('sender');
        if ((int)$this->country === 1) {
            if ($method_giving !== 'parcel_locker' && $method_giving !== 'dispatch_point') {
                return array(
                    'error' => 1,
                    0 => $inpost->l('Select the method of giving', self::FILE)
                );
            }
            if ($method_giving === 'dispatch_point') {
                $dispatch_points_id = Tools::getValue('dispatch_points_sender');

                if ($dispatch_points_id && (int)$dispatch_points_id !== -1) {
                    $dispatch_point = InpostModel::getDispatchPointFieldsToEditValues($dispatch_points_id);

                }
                if (!isset($dispatch_point) || (int)$dispatch_points_id === -1) {
                    return array(
                    'error' => 1,
                    0 => $inpost->l('Dispatch point is not available', self::FILE)
                    );
                }
            }

            if ($method_giving === 'parcel_locker') {
                if (!$sender['source_machine_id']) {
                    return array(
                        'error' => 1,
                        0 => $inpost->l('Select available source machine or change method of giving', self::FILE)
                    );
                }
            }
        }

        $receiver = Tools::getValue('receiver');

        if ($receiver['country']) {
            $country = constant('InpostConnector::INPOST_COUNTRY_'.Configuration::get('INPOST_COUNTRY'));
            $receiverCountry = InpostModel::getCountryIsoCodeById($receiver['country']);
            if ($receiverCountry !== $country) {
                return array(
                    'error' => 1,
                    0 => $inpost->l('Receiver country is not available', self::FILE)
                );
            }
        }

        $parcel_size = Tools::getValue('parcel_size');
        $parcel_insurance = Tools::getValue('parcel_insurance_amount');
        $parcel_insurance_checked = Tools::getValue('parcel_insurance');
        $cod = Tools::getValue('shipping_cod');
        $cod_amount = false;
        if ($cod == 'PARCELS_LOCKERS_COD') {
            $order = new Order(Tools::getValue('id_order'));
            $cod_amount = $order->total_paid_tax_incl;
        }
        $phone = null;
        if ($receiver['phone']) {
            $phone = $receiver['phone'];
        }
        if ($receiver['phone_mobile']) {
            $phone = $receiver['phone_mobile'];
        }

        if (!$phone) {
            $this->returnError('Brak numeru telefonu');
        }

        if ((int)Configuration::get('INPOST_COUNTRY') === 2) {
            $phone = ltrim($phone, '0');
            if (isSet($sender['phone']))
                $sender['phone'] = ltrim($sender['phone'], '0');
        }

        $path = "/customers/$this->login/parcels";

        $fields = [
            'receiver_email' => $receiver['email'],
            'receiver_phone' => $phone,
            'source_machine_id' => (isset($sender['source_machine_id']) ? $sender['source_machine_id'] : ''),
            'target_machine_id' => $receiver['parcel_locker'],
            'size' => $parcel_size ? $parcel_size : Configuration::get('INPOST_DEFAULT_PARCEL_SIZE'),  //required
            'cod_amount' => $cod_amount ? $cod_amount : '',
            'customer_reference' => $sender['customer_reference'],
            'sender_address' => [
                'building_no' => $sender['building_no'],
                'flat_no' => $sender['flat_no'],
                'street' => $sender['street'],
                'post_code' => $sender['postcode'],
                'city' => $sender['city'],
                'province' => '',
                'first_name' =>$sender['firstname'],
                'last_name' =>$sender['lastname'],
                'company_name' => $sender['company_name'],
                'email' => $sender['email'],
                'phone' => $sender['phone'],

            ],
            'receiver' => [
                'address' => [
                    'building_no' => $receiver['building_no'],
                    'city' => $receiver['city'],
                    'flat_no' => $receiver['flat_no'],
                    'post_code' => $receiver['postcode'],
                    'province' => '',
                    'street' => $receiver['street'],

                ],
                'company_name' => $receiver['company_name'],
                'email' => $receiver['email'],
                'first_name' =>$receiver['firstname'],
                'last_name' => $receiver['lastname'],
                'phone' => $phone
            ],
            'weight' => '',
            'additional1' => Tools::getValue('order_comments'),
            'additional2' => '',
            'insurance_amount' => $parcel_insurance_checked ? $parcel_insurance : false
        ];

        $response = $this->makeCurl($path, $fields, 'POST');
		
        if (property_exists($response, 'status_code')) {
            if (property_exists($response, 'errors')) {
                return $this->validateErrors($response->errors);
            }

			if (property_exists($response, 'error_code')) {
                return ['error' => 1, 0 => $response->message];
            }
        }

        $database = InpostModel::savePackage(
            $response,
            Tools::getValue('id_order'),
            $receiver['country'],
            $receiver['id_customer'],
            $dispatch_points_id
        );
        if (!$database) {
            return ['error' => 1, 0 => 'Save to database error'];
        }
        return $response;
    }
    public function updateParcel()
    {

        $parcel_id = Tools::getValue('parcel_id');
        $sender = Tools::getValue('sender');
        $fields = array(
            'customer_reference' => $sender['customer_reference'],
            'size' => Tools::getValue('parcel_size'),
        );
        $path ="/parcels/{$parcel_id}";
        $response = $this->makeCurl($path, $fields, 'PUT');

        if (property_exists($response, 'status_code')) {
            if (property_exists($response, 'error_code') && $response->errors == new stdClass()) {
                return ['error' => 1, 0 => $response->message];
            }

            if (property_exists($response, 'errors')) {
                return $this->validateErrors($response->errors);
            }

        }

        InpostModel::updatePackage($response);

        return $response;

    }

    public function createSticker($parcel_id)
    {
        $path = "/parcels/{$parcel_id}/sticker?type=A6P";

        $response =  $this->makeCurl($path);
        if (!$response) {
            return ['error' => 1,0 => "Unexpected error. Creating a Label"];
        }
		
		
        $responseDecode =json_decode($response);

        if ($responseDecode !== NULL && !is_string($responseDecode) && property_exists($responseDecode, 'status_code')) {
            $re = $responseDecode;
            if ($re->message == '-') {
                $re->message = 'Unexpected Error '.$re->error_code;
            }

            return ['error' => 1,0 => $re->message];
        }
        $filename = _PS_MODULE_DIR_.'inpost/pdf/'.$parcel_id.'.pdf';

        return file_put_contents($filename, $response);
    }

    public function getParcel($parcel_id)
    {

        $path = "/parcels/{$parcel_id}";

        return $this->makeCurl($path);
    }

    public function payForParcel($parcel_id)
    {
        $path = "/parcels/{$parcel_id}/pay";

        return $this->makeCurl($path, [], 'POST');
    }

    public function cancelParcel($parcel_id)
    {
        $path = "/parcels/{$parcel_id}/cancel";
        return $this->makeCurl($path, [], 'POST');
    }

    private function returnError($msg)
    {

        return ['error' => 1, 'message' => $msg];
    }

    public function getAllMachines()
    {
        $path = '/machines';
        return $this->makeCurl($path);
    }

    public function updateCustomer($fields)
    {
        $path = "/customers/{$this->login}";
        $response =  $this->makeCurl($path, $fields, 'PUT');

        if (property_exists($response, 'status_code')) {
            if (property_exists($response, 'error_code') && $response->errors == new stdClass()) {
                return ['error' => 1, 0 => $response->message];
            }

            if (property_exists($response, 'errors')) {
                return $this->validateErrors($response->errors);
            }

        }
        return $response;
    }

    private function validateErrors($errorsR)
    {

        $inpost = Module::getInstanceByName('inpost');

        $errors = ['error' => 1];
		
		if (property_exists($errorsR, 'receiver_phone')) {
            if ($errorsR->receiver_phone[0] == 'required') {
                $errors[] = $inpost->l('Reciever phone number is required', self::FILE);
            }
			if ($errorsR->receiver_phone[0] == 'invalid') {
                $errors[] = $inpost->l('Reciever phone number is invalid', self::FILE);
            }
        }
		
		if (property_exists($errorsR, 'name')) {
            if ($errorsR->name[0] == 'invalid') {
                $errors[] = $inpost->l('Name invalid', self::FILE);
            }
        }

        if (property_exists($errorsR, 'target_machine_id')) {
            if ($errorsR->target_machine_id[0] == 'not_found') {
                $errors[] = $inpost->l('Target machine not found', self::FILE);
            }
            if ($errorsR->target_machine_id[0] == 'required') {
                $errors[] = $inpost->l('Target machine is required', self::FILE);
            }

            if (!isset($errors[0])) {
                $errors[] = $inpost->l('Target machine error', self::FILE);
            }

        }

        if (property_exists($errorsR, 'iban')) {
            if ($errorsR->iban[0] == 'invalid') {
                $errors[] = $inpost->l('IBAN Invalid', self::FILE);
            }
            if ($errorsR->iban[0] == 'too_long') {
                $errors[] = $inpost->l('IBAN too long', self::FILE);
            }
        }

        if (property_exists($errorsR, 'receiver')) {
            if (isset($errorsR->receiver[0])) {
                if (property_exists($errorsR->receiver[0], 'address')) {
                    if (property_exists($errorsR->receiver[0]->address[0], 'building_no')) {
                        foreach ($errorsR->receiver[0]->address[0]->building_no as $receiverBuildingErrors) {
                            if ($receiverBuildingErrors == 'required') {
                                $errors[] = $inpost->l('Receiver Building number is required', self::FILE);
                            }
                            if ($receiverBuildingErrors == 'to_longs') {
                                $errors[] = $inpost->l('Receiver Building is too long', self::FILE);
                            }
                        }

                    }
                    if (property_exists($errorsR->receiver[0]->address[0], 'street')) {
                        foreach ($errorsR->receiver[0]->address[0]->street as $receiverStreetErrors) {
                            if ($receiverStreetErrors == 'required') {
                                $errors[] = $inpost->l('Receiver Street number is required', self::FILE);
                            }
                            if ($receiverStreetErrors == 'too_long') {
                                $errors[] = $inpost->l('Receiver Street is to loong', self::FILE);
                            }
                        }
                    }
                    if (property_exists($errorsR->receiver[0]->address[0], 'flat_no')) {
                        foreach ($errorsR->receiver[0]->address[0]->flat_no as $receiverStreetErrors) {
                            if ($receiverStreetErrors == 'too_long') {
                                $errors[] = $inpost->l('Flat number is to long', self::FILE);
                            }
                            if ($receiverStreetErrors == 'required') {
                                $errors[] = $inpost->l('Flat number is required', self::FILE);
                            }
                        }
                    }
                    if (property_exists($errorsR->receiver[0]->address[0], 'post_code')) {
                        foreach ($errorsR->receiver[0]->address[0]->post_code as $receiverPostCodeErrors) {
                            if ($receiverPostCodeErrors == 'invalid') {
                                $errors[] = $inpost->l('Postal code is invalid', self::FILE);
                            }
                            if ($receiverPostCodeErrors == 'required') {
                                $errors[] = $inpost->l('Postal code is required', self::FILE);
                            }
                        }
                    }

                }
                if (property_exists($errorsR->receiver[0], 'phone')) {
                    foreach ($errorsR->receiver[0]->phone as $receiverPhoneErrors) {
                        if ($receiverPhoneErrors == 'invalid') {
                            $errors[] = $inpost->l('Phone is invalid', self::FILE);
                        }
                        if ($receiverPhoneErrors == 'required') {
                            $errors[] = $inpost->l('Phone number is required', self::FILE);
                        }
                    }
                }
            }
            if (!isset($errors[0])) {
                $errors[] = $inpost->l('Receiver error', self::FILE);
            }
        }
        if (property_exists($errorsR, 'receiver_phone')) {
            if ($errorsR->receiver_phone[0] == 'invalid') {
                $errors[] = $inpost->l('Phone is invalid', self::FILE);
            }
        }


        if (property_exists($errorsR, 'phone')) {
            foreach ($errorsR->phone as $phoneE) {
                if ($phoneE === 'required') {
                    $errors[] = $inpost->l('Phone number is required', self::FILE);
                } elseif ($phoneE == 'invalid') {
                    $errors[] = $inpost->l('Wrong phone number', self::FILE);
                }
            }
        }
        if (property_exists($errorsR, 'email')) {
            foreach ($errorsR->email as $emailE) {
                if ($emailE == 'not_an_email') {
                    $errors[] = $inpost->l('Wrong email', self::FILE);
                }
            }
        }
        if (property_exists($errorsR, 'address')) {
            if (property_exists($errorsR->address[0], 'post_code')) {
                foreach ($errorsR->address[0]->post_code as $postCode) {
                    if ($postCode == 'required') {
                        $errors[] = $inpost->l('Postal code is required', self::FILE);
                    }
                    if ($postCode == 'invalid') {
                        $errors[] = $inpost->l('Postal code is invalid', self::FILE);
                    }
                }

            }

            if (property_exists($errorsR->address[0], 'building_no')) {
                foreach ($errorsR->address[0]->building_no as $building_no) {
                    if ($building_no == 'required') {
                        $errors[] = $inpost->l('Building number is required', self::FILE);
                    }
                }
            }

            if (property_exists($errorsR->address[0], 'street')) {
                foreach ($errorsR->address[0]->street as $street) {
                    if ($street == 'required') {
                        $errors[] = $inpost->l('Building number is required', self::FILE);
                    }
                }
            }
        }

        if (property_exists($errorsR, 'sender_address')) {
            if (property_exists($errorsR->sender_address[0], 'phone')) {
                foreach ($errorsR->sender_address[0]->phone as $phone) {
                    if ($phone == 'required') {
                        $errors[] = $inpost->l('Sender phone number is required', self::FILE);
                    }
                    if ($phone == 'invalid') {
                        $errors[] = $inpost->l('Sender phone number is invalid', self::FILE);
                    }
                }
            }
            if (property_exists($errorsR->sender_address[0], 'post_code')) {
                foreach ($errorsR->sender_address[0]->post_code as $code) {
                    if ($code == 'required') {
                        $errors[] = $inpost->l('Sender postcode is required', self::FILE);
                    }
                    if ($code == 'invalid') {
                        $errors[] = $inpost->l('Sender postcode is invalid', self::FILE);
                    }
                }
            }
        }
        if (property_exists($errorsR, 'source_machine_id')) {
            foreach ($errorsR->source_machine_id as $sourceMachineId) {
                if ($sourceMachineId == 'not_found') {
                    $errors[] = $inpost->l('Source machine not found', self::FILE);
                }
            }
        }
        if (property_exists($errorsR, 'dispatch_date')) {
            if (property_exists($errorsR->dispatch_date[0], 'from')) {
                foreach ($errorsR->dispatch_date[0]->from as $singleFrom) {
                    if ($singleFrom == 'invalid') {
                        $errors[] = $inpost->l('Date from is invalid', self::FILE);
                    }
                }

            }
            if (property_exists($errorsR->dispatch_date[0], 'to')) {
                foreach ($errorsR->dispatch_date[0]->to as $singleTo) {
                    if ($singleTo == 'invalid') {
                        $errors[] = $inpost->l('Date to is invalid', self::FILE);
                    }
                }
            }

        }

        if (property_exists($errorsR, 'insurance_amount')) {
            foreach ($errorsR->insurance_amount as $insuranceErr) {
                if ($insuranceErr == 'invalid') {
                    $errors[] = $inpost->l('Insurance amount is invalid', self::FILE);
                }
            }
        }

        if (!isset($errors[0])) {
            $errors[] = $inpost->l('Unexpected errors', self::FILE);
        }

        return $errors;
    }
    public function getDispatchPoint($href)
    {
        $path = $href;
        return $this->makeCurl($path, [], 'GET');
    }

    public function getUserDispatchPoints()
    {
        $path = "/customers/{$this->login}/dispatch_points";
        return $this->makeCurl($path, [], 'GET');
    }
    public function updateUserDispatchPoint()
    {
        $fields = [
            'name' => Tools::getValue('DISPATCH_NAME'),
            'phone' => Tools::getValue('DISPATCH_PHONE_NO'),
            'email' => Tools::getValue('DISPATCH_EMAIL'),
            'comments' => Tools::getValue('DISPATCH_COMMENTS'),
            'office_hours' => Tools::getValue('DISPATCH_OFFICE_HOURS'),
            'address' => [
                'building_no' => Tools::getValue('DISPATCH_BUILDING_NO'),
                'flat_no' => Tools::getValue('DISPATCH_FLAT_NO'),
                'street' => Tools::getValue('DISPATCH_STREET'),
                'post_code' => Tools::getValue('DISPATCH_POSTCODE'),
                'country' => Tools::getValue('DISPATCH_COUNTRY'),
                'city' => Tools::getValue('DISPATCH_CITY'),
            ]
        ];
        $href = Tools::getValue('DISPATCH_HREF');

        $response =  $this->makeCurl($href, $fields, 'PUT');


        if (property_exists($response, 'status_code')) {
            $arr =  (array)$response->errors;
            if (property_exists($response, 'error_code') && empty($arr)) {
                return ['error' => 1, 0 => $response->message];
            }

            if (property_exists($response, 'errors')) {
                return $this->validateErrors($response->errors);
            }

        }
        return $response;
    }
    public function createNewUserDispatchPoint()
    {
        $country = InpostModel::getCountryNameByIsoCode(
            constant('InpostConnector::INPOST_COUNTRY_'.Configuration::get('INPOST_COUNTRY'))
        );

        $fields = [
            'name' => Tools::getValue('DISPATCH_NAME'),
            'phone' => Tools::getValue('DISPATCH_PHONE_NO'),
            'email' => Tools::getValue('DISPATCH_EMAIL'),
            'comments' => Tools::getValue('DISPATCH_COMMENTS'),
            'office_hours' => Tools::getValue('DISPATCH_OFFICE_HOURS'),
            'address' => [
                'building_no' => Tools::getValue('DISPATCH_BUILDING_NO'),
                'flat_no' => Tools::getValue('DISPATCH_FLAT_NO'),
                'street' => Tools::getValue('DISPATCH_STREET'),
                'post_code' => Tools::getValue('DISPATCH_POSTCODE'),
                'country' => $country,
                'city' => Tools::getValue('DISPATCH_CITY'),
            ]
        ];

        $path = "/customers/{$this->login}/dispatch_points";

        $response =  $this->makeCurl($path, $fields, 'POST');

        if (property_exists($response, 'status_code')) {
            $arr =  (array)$response->errors;
            if (property_exists($response, 'error_code') && empty($arr)) {
                return ['error' => 1, 0 => $response->message];
            }

            if (property_exists($response, 'errors')) {
                return $this->validateErrors($response->errors);
            }

        }
        return $response;
    }

    public function deleteDispatchPoint($href)
    {
        $path = $href;
        $response = $this->makeCurl($path, [], 'DELETE');
        if ($response) {
            if (property_exists($response, 'status_code')) {
                $arr =  (array)$response->errors;
                if (property_exists($response, 'error_code') && empty($arr)) {
                    return ['error' => 1, 0 => $response->message];
                }

                if (property_exists($response, 'errors')) {
                    return $this->validateErrors($response->errors);
                }

            }
        }
        return $response;
    }

    public function dispatchOrders($dispatch_point_id, $parcelsIds)
    {

        if (Tools::getValue('date_from')) {
            $date_from = date(DATE_ATOM, strtotime(Tools::getValue('date_from').' '.Tools::getValue('hour_from')));
            $date_to = date(DATE_ATOM, strtotime(Tools::getValue('date_from').' '.Tools::getValue('hours_to')));
        }
        $path = "{$dispatch_point_id}/dispatch_orders/";

        $fields = [
            'parcel_ids' => $parcelsIds,
            'comment' => Tools::getValue('comments'),
            'reference' => Tools::getValue('reference'),
            'dispatch_date' => [
                'from' => isset($date_from) ? $date_from : '',
                'to' => isset($date_to) ? $date_to : ''
            ]
        ];

         $response = $this->makeCurl($path, $fields, 'POST');

        if (property_exists($response, 'status_code')) {
            $arr =  (array)$response->errors;
            if (property_exists($response, 'error_code') && empty($arr)) {
                return ['error' => 1, 0 => $response->message];
            }
            if (property_exists($response, 'errors')) {
                return $this->validateErrors($response->errors);
            }
        }

        return $response;

    }
}
