<?php
declare(strict_types=1);
namespace Module23ImprovedTax\StoreFrontend\SalesChannel;
use Module23ImprovedTax\Extension\Core\System\Country\ImprovedTaxEntity;
use Shopware\Core\Checkout\Customer\CustomerEntity;
use Shopware\Core\Framework\Api\Context\AdminApiSource;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Shopware\Core\System\Country\CountryEntity;
use function array_filter;
use function assert;
class ImprovedCountryTax
{
private ?CustomerEntity $customer = null;
public function __invoke(EntityLoadedEvent $event): void
{
if ($event->getContext()->getSource() instanceof AdminApiSource) {
return;
}
$country = $this->country($event);
$improvedTax = $this->improvedTax($country);
if ($this->isCustomerCompany() && $improvedTax->isCompanyTaxFree()) {
$this->makeCompanyTaxFree($country);
return;
}
if ($this->isCustomerCompany() && $improvedTax->isCustomerTaxFree()) {
return;
}
$this->makeCustomerTaxFree($country);
}
private function makeCompanyTaxFree(CountryEntity $country): void
{
$country->setCompanyTaxFree(true);
$country->getCompanyTax()->setEnabled(true);
$country->setTaxFree(false);
$country->getCustomerTax()->setEnabled(false);
}
private function makeCustomerTaxFree(CountryEntity $country): void
{
$country->setTaxFree(true);
$country->getCustomerTax()->setEnabled(true);
$country->setCompanyTaxFree(false);
$country->getCompanyTax()->setEnabled(false);
}
private function isCustomerCompany(): bool
{
$isCompanyCustomer = false;
if ((null !== $this->customer)
&& (null !== $this->customer->getDefaultBillingAddress())
&& (false === empty($this->customer->getDefaultBillingAddress()->getCompany()))
) {
$isCompanyCustomer = true;
}
return $isCompanyCustomer;
}
private function improvedTax(CountryEntity $country): ImprovedTaxEntity
{
$improvedTax = $country->getExtension('improvedTax');
assert($improvedTax instanceof ImprovedTaxEntity);
return $improvedTax;
}
private function country(EntityLoadedEvent $event): CountryEntity
{
return array_filter($event->getEntities())[0];
}
public function setCustomer(CustomerEntity $customer): void
{
$this->customer = $customer;
}
}