<?php

namespace App\EventListener;


use Contao\CoreBundle\ServiceAnnotation\Hook;
use Contao\FrontendTemplate;
use Contao\Module;
use App\ExactApi\ApiExact;
use Isotope\Model\Address;
use Isotope\Model\Product;
use Isotope\Model\ProductCollection\Order;
use Isotope\Model\ProductCollectionItem;

class PostCheckoutListener
{
    const WAREHOUSE_ID = 'd8a6a9b8-d0ac-4d36-8d00-bd420d0d81f5';

    /**
     * @Hook("postCheckout")
     */
	//	public function __invoke(int $userId, array $userData, Module $module): void
  	public function __invoke(Order $order, $item): void
    {
        $apiExact = new ApiExact();

        //ob_start();
        $salesOrderItems = [];
        /** @var ProductCollectionItem $orderItem */
        foreach($order->getItems() as $orderItem) {
            $salesOrderItems[] = $this->createOrderItem($orderItem);
//            /** @var Product $orderItem */
//            $product = $orderItem->getProduct();
//            var_dump($orderItem->id);
//            var_dump($orderItem->sku);
//            var_dump($orderItem->quantity);
//            var_dump($orderItem->tax_free_price);
//
//            var_dump($product->id);
//            var_dump($product->name);
//            var_dump($product->is_set);

        }
        //var_dump($apiExact->test());
//        file_put_contents('dan.txt', ob_get_contents());
//        ob_end_clean();



        $shippingCustomer = null;
//        if ($this->compareAddresses() === false) {
//            $shippingCustomer = $apiExact->createCustomer(
//                $this->createCustomerApiData($order->getShippingAddress())
//            );
//        }
//
        $billingCustomer = $apiExact->createCustomer(
            $this->createCustomerApiData($order->getBillingAddress())
        );
        $apiExact->createSalesOrder($this->createSalesOrderData($order, $billingCustomer, $shippingCustomer));

    }

    private function compareAddresses(Order $order)
    {
        return
            $order->getBillingAddress()->firstname === $order->getShippingAddress()->firstname &&
            $order->getBillingAddress()->lastname === $order->getShippingAddress()->lastname &&
            $order->getBillingAddress()->street_1 === $order->getShippingAddress()->street_1 &&
            $order->getBillingAddress()->postal === $order->getShippingAddress()->postal &&
            $order->getBillingAddress()->city === $order->getShippingAddress()->city &&
            $order->getBillingAddress()->company === $order->getShippingAddress()->company &&
            $order->getBillingAddress()->phone === $order->getShippingAddress()->phone &&
            $order->getBillingAddress()->email === $order->getShippingAddress()->email;
    }

    private function createCustomerApiData(Address $address)
    {
        return [
            'Name' => $address->firstname . ' ' . $address->lastname,
            'AddressLine1' => $address->street_1,
            'AddressLine2' => $address->company,
            'City' => $address->city,
            'Postcode' => $address->postal,
            'Email' => $address->email,
            'Country' => 'DE',
            'Phone' => $address->phone,
            'Status' => 'C',
        ];
    }

    private function createOrderItem(ProductCollectionItem $orderItem)
    {
        /** @var Product $orderItem */
        $product = $orderItem->getProduct();
        return [
            'Description' => $product->name,
            'Item' => $product->exact_id,
            'UnitPrice' => (float) $orderItem->tax_free_price / (int) $orderItem->quantity,
            'Quantity' => $orderItem->quantity
        ];
    }

    private function createSalesOrderData(Order $order, $billingCustomer, $salesOrderItems, $shippingCustomer = null)
    {
        $date = new \DateTime('now');
        $res = [
            'Description' => $billingCustomer['Name'],
            'OrderDate' => $date->format('m/d/Y H:i:s'),
            'OrderedBy' => $billingCustomer['ID'],
            'WarehouseID' => self::WAREHOUSE_ID,
            'SalesOrderLines' => [
                $salesOrderItems
            ]
        ];
        if ($shippingCustomer !== null) {
            $res['DeliverTo'] = $shippingCustomer['ID'];
        }

        return $res;
    }
}