<?php

namespace Leadlion\AutogedalOrderFlow\Observer;

use Magento\Framework\App\State;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Exception\LocalizedException;

class ReplaceDiacriticsFromName implements ObserverInterface
{
    /**
     * @param Observer $observer
     */
    public function execute(Observer $observer)
    {
        $quote = $observer->getEvent()->getQuote();
        
        $quoteFirtname = $this->replaceDiacritics($quote->getCustomerFirstname());
        $quoteLastname = $this->replaceDiacritics($quote->getCustomerLastname());
        $quote->setCustomerFirstname($quoteFirtname);
        $quote->setCustomerLastname($quoteLastname);

        $billingFirtname = $this->replaceDiacritics($quote->getBillingAddress()->getFirstname());
        $billingLastname = $this->replaceDiacritics($quote->getBillingAddress()->getLastname());
        $quote->getBillingAddress()->setFirstname($billingFirtname);
        $quote->getBillingAddress()->setLastname($billingLastname);

        $shippingFirtname = $this->replaceDiacritics($quote->getShippingAddress()->getFirstname());
        $shippingLastname = $this->replaceDiacritics($quote->getShippingAddress()->getLastname());
        $quote->getShippingAddress()->setFirstname($shippingFirtname);
        $quote->getShippingAddress()->setLastname($shippingLastname);
    }

    protected function replaceDiacritics($string)
    {
        if ($string) {
            $keywords = [
                'Ă' => 'A', 'ă' => 'a', 'Â' => 'A', 'â' => 'a', 'Î' => 'I', 'î' => 'i', 'Ș' => 'S', 'ş' => 's', 'ș' => 's', 'Ț' => 'T', 'ț' => 't',
                'Š' => 'S', 'š' => 's', 'Ž' => 'Z', 'ž' => 'z', 'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'A', 'Å' => 'A', 'Æ' => 'A', 'Ç' => 'C', 'È' => 'E', 'É' => 'E',
                'Ê' => 'E', 'Ë' => 'E', 'Ì' => 'I', 'Í' => 'I', 'Î' => 'I', 'Ï' => 'I', 'Ñ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O', 'Ö' => 'O', 'Ø' => 'O', 'Ù' => 'U',
                'Ú' => 'U', 'Û' => 'U', 'Ü' => 'U', 'Ý' => 'Y', 'Þ' => 'B', 'ß' => 'Ss', 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => 'a', 'å' => 'a', 'æ' => 'a', 'ç' => 'c',
                'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'ð' => 'o', 'ñ' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o',
                'ö' => 'o', 'ø' => 'o', 'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ý' => 'y', 'þ' => 'b', 'ÿ' => 'y'
            ];
            $string = strtr($string, $keywords);
            $string = trim($string);
        }
        return $string;
    }
}
