<?php
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(0);
include("mintsoftOrder.class.php");
include("mintsoftOrderItems.class.php");

class MintsoftApi {

    /**
     * retreives the api
     * @var $apiKey string
     */
    protected $apiKey;

    // Config
    protected $InitialOrderStatusId = 1;//'P';

    protected $ConfirmedStatusId = 'Z';

    protected $PickingStatusId = 'Y';

    protected $action = null;

    public $orderLines = [];

    protected $orderDetails = [];

    protected $courierService = '';
    protected $courierId = 0;

    function __construct() {

    }

    /**
     * makes an authenticaion to retreive the api key to be used in creating the order
     * @param $username
     * @param $password
     * @return string
     */
    public function getApiKey() {

        return $this;

    }

    public function closeConnection($connection) {
        curl_close($connection);
    }

    /**
     * @param $countryCode
     * @author Matt Haselip
     * Sets the Courier data $courierService and $courierId
     * @return properties
     * these codes are the ID name from mintsoft
     * use https://api.mintsoft.co.uk/swagger/ui/index#/Courier identify couriers
     */
    public function setCourierServices($countryCode) {

        $couriers = [
            ['local' => [
                'courierServiceName' => 'RM 24 (LL)',
                'courierId' => 7
            ]],
            ['international' => [
                'courierServiceName' => 'International Standard - Large Letter',
                'courierId' => 24
            ]],
            ['euro' => [
                'courierServiceName' => 'International Standard - Large Letter',
                'courierId' => 24
            ]]
        ];
        $use = '';
        switch(strtoupper($countryCode)) {

            case 'GB':
                $use = 'local';
                break;
            case 'NL':
            case 'DE':
            case 'IE':
                $use = 'euro';
                break;
            default:
                $use = 'international';
                break;
        }
        $key = array_filter($couriers, function($value) use ($use) {
            if(isset($value[$use])) {
                return $value;
            }
        });

            $this->courierService = $key[0][$use]['courierServiceName'];
            $this->courierId = $key[0][$use]['courierId'];


        return true;
    }

    /**
     * @param $data
     * @param $testkitId
     * @param $customerData
     *  see https://api.mintsoft.co.uk/swagger/ui/index#!/Order/Order_CreateOrder
     */
    public function setOrderDetails($data) {
        $order = new MintSoftOrder();
        if(count($data) > 0) {

            // delivery - identify which key to use to select the courier service and courier service id
            $this->setCourierServices($data['wpml_language']);

            $order->OrderNumber = (isset($data['testkit_order_number']))?$data['testkit_order_number']:'';
            $order->Title = (isset($data['testkit_title']))?$data['testkit_title']:''; // currently not using this
            $order->CompanyName = (isset($data['testkit_delivery_company_name']))?$data['testkit_delivery_company_name']:'';
            $order->FirstName = (isset($data['customer_first_name']))?$data['customer_first_name']:'';
            $order->LastName = (isset($data['customer_last_name']))?$data['customer_last_name']:'';
            $order->Address1 = (isset($data['testkit_delivery_address_1']))?$data['testkit_delivery_address_1']:'';
            $order->Address2 = (isset($data['testkit_delivery_address_2']))?$data['testkit_delivery_address_2']:'';
            if($order->Address1 == $order->Address2) {
                $order->Address2 = '';
            }
            $order->Address3 = (isset($data['testkit_delivery_address_3']))?$data['testkit_delivery_address_3']:'';
            if($order->Address2 == $order->Address3) {
                $order->Address3 = '';
            }
            $order->Town = (isset($data['testkit_delivery_town']))?$data['testkit_delivery_town']:'';
            $order->County = (isset($data['testkit_delivery_county']))?$data['testkit_delivery_county']:'';
            $order->PostCode = (isset($data['testkit_delivery_postcode']))?$data['testkit_delivery_postcode']:'';
            $order->Country = (isset($data['testkit_delivery_country']))?(strpos($data['testkit_delivery_country'],'('))?rtrim(substr($data['testkit_delivery_country'],0,strpos($data['testkit_delivery_country'],'('))):$data['testkit_delivery_country']:'';
            $order->Email = (isset($data['customer_email_address']))?$data['customer_email_address']:'';
            $order->Phone = (isset($data['testkit_delivery_contact_number']))?$data['testkit_delivery_contact_number']:'';
            $order->Mobile = (isset($data['testkit_delivery_contact_mobile']))?data['testkit_delivery_contact_mobile']:''; // note: we are not currently using this!
            $order->WarehouseId = (isset($data['warehouse_id']))?$data['warehouse_id']:3;  // not using this, only specifying a default
            $order->CourierService = (isset($this->courierService))?$this->courierService:'';
            $order->CourierServiceId = (isset($this->courierId))?$this->courierId:0;
            $order->DeliveryDate = ''; // not using
            $order->Comments = ''; //not using
            $order->OrderValue = (isset($data['order_total']))?$data['order_total']:0;
            $order->DeliveryNotes = ''; // not using
        }
            $this->orderDetails = $order;
        return $this;
    }

    public function getOrderDetails() {

        return $this->orderDetails;

    }

    public function setOrderLines($lines) {
        foreach ($lines AS $line) {
            $this->orderLines[] = [
                'SKU' => $line['sku'],
                'ProductId' => $line['id'],
                'Quantity' => $line['quantity'],
                'Details' => $line['name'],
                'UnitPrice' => $line['unit_total'],
                'OrderItemNameValues' => [
                    'Name' => $line['name'],
                    'Value' => $line['Value']
                ]
            ];
        }
        return $this;
    }

    public function formatData() {
        $data = (array)$this->orderDetails;
        $data['OrderItems'] = (array)$this->orderLines;
        return $data;
    }

    public function compileJsonArray($data) {

        // $this->orderDetails
        // $this->orderLines

        return json_encode($data);

    }

    public function executeApi(){



    }
}


/**
 *
 * curl -X PUT --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{ \
"OrderItems": [ \
{ \
"SKU": "string", \
"ProductId": 0, \
"Quantity": 0, \
"Details": "string", \
"UnitPrice": 0, \
"UnitPriceVat": 0, \
"OrderItemNameValues": [ \
{ \
"Name": "string", \
"Value": "string" \
} \
], \
"WarehouseId": 0 \
} \
], \
"OrderNumber": "string", \
"ExternalOrderReference": "string", \
"Title": "string", \
"CompanyName": "string", \
"FirstName": "string", \
"LastName": "string", \
"Address1": "string", \
"Address2": "string", \
"Address3": "string", \
"Town": "string", \
"County": "string", \
"PostCode": "string", \
"Country": "string", \
"Email": "string", \
"Phone": "string", \
"Mobile": "string", \
"CourierService": "string", \
"CourierServiceId": 0, \
"Channel": "string", \
"ChannelId": 0, \
"Warehouse": "string", \
"WarehouseId": 0, \
"Currency": "string", \
"DeliveryDate": "2018-07-31T11:11:13.117Z", \
"DespatchDate": "2018-07-31T11:11:13.117Z", \
"RequiredDeliveryDate": "2018-07-31T11:11:13.117Z", \
"RequiredDespatchDate": "2018-07-31T11:11:13.117Z", \
"Comments": "string", \
"DeliveryNotes": "string", \
"GiftMessages": "string", \
"OrderValue": 0, \
"OrderNameValues": [ \
{ \
"Name": "string", \
"Value": "string" \
} \
] \
}' 'https://api.mintsoft.co.uk/api/Order?APIKey=7de8ec4d-0e58-4f72-8f8e-81f9a79e52c9'
 *
 *
 */