<?php

namespace Leadlion\Web2Sms\Helper;

use \Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\Framework\App\State;
use Magento\Framework\App\Area;
use Magento\Sales\Model\Order;

class Data extends AbstractHelper
{

	const ORDER_SMS_MESSAGE_KEY  = 'sendsms_settings/sendsms/sendsms_settings_messages';

	const SHIPMENT_SMS_MESSAGE_KEY  = 'sendsms_settings/sendsms/sendsms_settings_shipment_messages';

	protected $scopeConfig;
    protected $storeDate;
	protected $helper;
	protected $pricingHelper;
	protected $serializer;
	protected $state;
	protected $orderRepository;

    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Framework\Stdlib\DateTime\DateTime $date,
		\Leadlion\Web2Sms\Helper\Web2Sms $helper,
		\Magento\Framework\Pricing\Helper\Data $pricingHelper,
		SerializerInterface $serializer,
		State $state,
		\Magento\Sales\Api\OrderRepositoryInterface $orderRepository
    ) {
        $this->scopeConfig = $scopeConfig;
        $this->storeDate = $date;
		$this->helper = $helper;
		$this->pricingHelper = $pricingHelper;
		$this->serializer = $serializer;
		$this->state = $state;
		$this->orderRepository = $orderRepository;
    }

    public function callAfterOrderPlace($order){
		$status = $order->getStatus();
		$sendOrderSms = $order->getSendOrderSms();
		if($sendOrderSms != 1){
			$text = $this->serializer->unserialize($this->scopeConfig->getValue(
				self::ORDER_SMS_MESSAGE_KEY,
				\Magento\Store\Model\ScopeInterface::SCOPE_STORE
			));

			foreach ($text as $config) {
				if ($status == $config['status']) {
					$message = $config['message'];
				}
			}
            $origStatusData = $order->getOrigData('status');

			if (!empty($message) && $origStatusData !=$status) {
				$message = $this->replaceOrderVariables($message, $order);
				$this->helper->sendSMS($order->getBillingAddress()->getTelephone(), $message, 'order');
				$order->setSendOrderSms(1);
				$order->addStatusToHistory($order->getStatus(), 'S-a trimis SMS cu textul : '. $message);
				//$order->save();
			}
		}
	}

	/**
     * @param $message
     * @param $order
     * @return string
     */
    public function replaceOrderVariables($message, $order)
    {
        $billingAddress = $order->getBillingAddress()->getData();
        $shippingAddress = $order->getShippingAddress()->getData();
        $formattedPrice = $this->pricingHelper->currency($order->getGrandTotal(), true, false);
         $trackCollection = $order->getTracksCollection();
        $lastAwb=false;
        if (count($trackCollection)) {
             $lastAwb=$trackCollection->getLastItem();
        }
		$carrierName = $order->getData('carrier_name');
        $replace = array(
            '{billing_first_name}' => $this->helper->cleanDiacritice($billingAddress['firstname']),
            '{billing_last_name}' => $this->helper->cleanDiacritice($billingAddress['lastname']),
            '{shipping_first_name}' => $this->helper->cleanDiacritice($shippingAddress['firstname']),
            '{shipping_last_name}' => $this->helper->cleanDiacritice($shippingAddress['lastname']),
            '{order_number}' => $order->getRealOrderId(),
            '{order_date}' => date('d.m.Y', strtotime($order->getCreatedAt())),
            '{order_total}' => $formattedPrice,
             '{awb}'=>$lastAwb ? ($lastAwb->getTitle().' '.$lastAwb->getNumber()):'',
			 '{carrier_name}' => $carrierName
        );
        foreach ($replace as $key => $value) {
            $message = str_replace($key, $value, $message);
        }

        return $message;
    }

	public function callAfterShipmentSaveFromAdmin($shipment){
		try {
            $areaCode = $this->state->getAreaCode();
        } catch (LocalizedException $exception) {
            $areaCode = null;
        }
		if ($areaCode == Area::AREA_ADMINHTML) {

			$order = $shipment->getOrder();
			$status = $order->getStatus();
			$text = $this->serializer->unserialize($this->scopeConfig->getValue(
				self::SHIPMENT_SMS_MESSAGE_KEY,
				\Magento\Store\Model\ScopeInterface::SCOPE_STORE
			));

			foreach ($text as $config) {
				if ($status == $config['status']) {
					$message = $config['message'];
				}
			}

			if (!empty($message)) {
				$message = $this->replaceShipmentVariables($message, $order, $shipment);
				$this->helper->sendSMS($order->getBillingAddress()->getTelephone(), $message, 'order');
			}
		}
	}

	/**
     * @param $message
     * @param $order
     * @return string
     */
    public function replaceShipmentVariables($message, $order, $shipment)
    {
		$blankMessage = '';
        $billingAddress = $order->getBillingAddress()->getData();
        $shippingAddress = $order->getShippingAddress()->getData();
        $formattedPrice = $this->pricingHelper->currency($order->getGrandTotal(), true, false);
        $tracksCollection = $shipment->getTracksCollection();
        $lastAwb=false;
        if (count($tracksCollection)) {
             $lastAwb=$tracksCollection->getLastItem();
        }
		if($lastAwb) {
			$awbnumber = $lastAwb->getTrackNumber();
			if($awbnumber != '' || $lastAwb->getTitle() != '' || $lastAwb->getCarrierCode() != '') {
				$replace = array(
					'{billing_first_name}' => $this->helper->cleanDiacritice($billingAddress['firstname']),
					'{billing_last_name}' => $this->helper->cleanDiacritice($billingAddress['lastname']),
					'{shipping_first_name}' => $this->helper->cleanDiacritice($shippingAddress['firstname']),
					'{shipping_last_name}' => $this->helper->cleanDiacritice($shippingAddress['lastname']),
					'{order_number}' => $order->getRealOrderId(),
					'{order_date}' => date('d.m.Y', strtotime($order->getCreatedAt())),
					'{order_total}' => $formattedPrice,
					'{awb}'=>$lastAwb ? ($lastAwb->getTitle().' '.$awbnumber):'',
					'{carrier_name}' => $lastAwb ? $lastAwb->getCarrierCode():'',
				);
				foreach ($replace as $key => $value) {
					$message = str_replace($key, $value, $message);
				}
				return $message;
			} else {
				return $blankMessage;
			}
		} else {
			return $blankMessage;
		}
    }

	public function callAfterShipmentSaveByCron($shipment, $awbNumber, $carrierCode, $carrierTitle){
		$order = $shipment->getOrder();
		$status = $order->getStatus();
		$text = $this->serializer->unserialize($this->scopeConfig->getValue(
			self::SHIPMENT_SMS_MESSAGE_KEY,
			\Magento\Store\Model\ScopeInterface::SCOPE_STORE
		));

		foreach ($text as $config) {
			if ($status == $config['status']) {
				$message = $config['message'];
			}
		}

		if (!empty($message)) {
			$message = $this->replaceShipmentCronVariables($message, $order, $awbNumber, $carrierCode, $carrierTitle);
			$this->helper->sendSMS($order->getBillingAddress()->getTelephone(), $message, 'order');
		}
	}

	/**
     * @param $message
     * @param $order
     * @return string
     */
    public function replaceShipmentCronVariables($message, $order, $awbNumber, $carrierCode, $carrierTitle)
    {
		$blankMessage = '';
        $billingAddress = $order->getBillingAddress()->getData();
        $shippingAddress = $order->getShippingAddress()->getData();
        $formattedPrice = $this->pricingHelper->currency($order->getGrandTotal(), true, false);
		if($awbNumber != '' || $carrierTitle != '' || $carrierCode != '') {
			$replace = array(
				'{billing_first_name}' => $this->helper->cleanDiacritice($billingAddress['firstname']),
				'{billing_last_name}' => $this->helper->cleanDiacritice($billingAddress['lastname']),
				'{shipping_first_name}' => $this->helper->cleanDiacritice($shippingAddress['firstname']),
				'{shipping_last_name}' => $this->helper->cleanDiacritice($shippingAddress['lastname']),
				'{order_number}' => $order->getRealOrderId(),
				'{order_date}' => date('d.m.Y', strtotime($order->getCreatedAt())),
				'{order_total}' => $formattedPrice,
				'{awb}'=>$awbNumber ? ($carrierTitle.' '.$awbNumber):'',
				'{carrier_name}' => $carrierCode ? $carrierCode:'',
			);
			foreach ($replace as $key => $value) {
				$message = str_replace($key, $value, $message);
			}
			return $message;
		} else {
			return $blankMessage;
		}
    }

	public function callAfterShipmentSaveByGenerateAwb($orderId, $awbNumber, $carrierCode, $carrierTitle){
		$order = $this->orderRepository->get($orderId);
		$status = $order->getStatus();
		$text = $this->serializer->unserialize($this->scopeConfig->getValue(
			self::SHIPMENT_SMS_MESSAGE_KEY,
			\Magento\Store\Model\ScopeInterface::SCOPE_STORE
		));

		foreach ($text as $config) {
			if ($status == $config['status']) {
				$message = $config['message'];
			}
		}

		if (!empty($message)) {
			$message = $this->replaceShipmentCronVariables($message, $order, $awbNumber, $carrierCode, $carrierTitle);
			$this->helper->sendSMS($order->getBillingAddress()->getTelephone(), $message, 'order');
		}
	}
}
