<?php

declare(strict_types=1);

require \dirname(__DIR__, 1).'/src/warmup.php';

use Cin\Quickpurchase\classes\PurchaseArticle;
use Cin\Quickpurchase\Licence;
use Cin\Quickpurchase\service\ConditionService;
use Cin\Quickpurchase\service\PurchaseService;
use Cin\Quickpurchase\service\PurchaseStorageService;
use JTL\Helpers\Text;
use JTL\Shop;
use Laminas\Diactoros\ServerRequestFactory;

/** @var Licence $L */
if ( ! $L->canRun()) {
  $smarty
    ->assign('purchaseportal_licence', 0);

  return;
}
/** @var Cin\Purchaseportal\Plugin $P */
$_plugin = $P->getJTlPlugin();

date_default_timezone_set('Europe/Berlin');

PurchaseService::ensureStorage();

$getText = Shop::Container()->getGetText();
$oldLang = $getText->getLanguage();
$getText->setLanguage(Text::convertISO2ISO639(Shop::getLanguageCode()));

/** @var JTL\Smarty\JTLSmarty $smarty */
$conditions = ConditionService::buildConditionArray();
$total      = PurchaseStorageService::total($cfg);
$storage    = PurchaseArticle::storage();

// if ( ! isset($smarty->registered_plugins[Smarty::PLUGIN_MODIFIER]['cin_quick_purchase_translate'])) {
//   $smarty->registerPlugin(
//     Smarty::PLUGIN_MODIFIER,
//     'cin_quick_purchase_translate',
//     [$P, 'translate']
//   );
// }

$request = ServerRequestFactory::fromGlobals($_SERVER, $_GET, null, $_COOKIE, $_FILES);

$smarty
  ->assign('purchaseportal_licence', 1)
  ->assign('info', $request->getUri()->getPath())
  ->assign('Artikel', PurchaseStorageService::load($_GET['kArtikel'] ?? 0))
  // static vars
  ->assign('cin_ankauf_config', $cfg)
  ->assign('cin_ankauf_url', URL_SHOP.$request->getUri()->getPath())
  ->assign('conditions', $conditions)
  ->assign('cFrontendPfadURL', $_plugin->getPaths()->getFrontendURL())
  // ->assign('we_buy_n_article', PurchaseService::weBuyNthArticles())
  ->assign('trans', $P->lang())
  ->assign('alternateformlink', $P->cfg()['alternate_page_link_id'] > 0 ? Shop::Container()->getLinkService()->getLinkByID((int) $P->cfg()['alternate_page_link_id'])->getURL() : '')
  // dynamic vars (ajax)
  ->assign('cin_ankauf_access', (isset($_SESSION['Kunde']) && true === (bool) $_SESSION['Kunde']->nRegistriert))
  ->assign('cin_ankauf_paymentselection', (isset($_SESSION['Kunde']) && true === (bool) $_SESSION['Kunde']->nRegistriert && isset($_SESSION['cin_ankauf_paymentselection'])) ? $_SESSION['cin_ankauf_paymentselection'] : null)
  ->assign('cin_ankauf_minsumreached', $total >= $cfg['cin_ankauf_min_sum'])
  ->assign('cin_ankauf_storage', $storage)
  ->assign('cin_ankauf_storageContainsOnlyQueueItems', PurchaseStorageService::hasOnlyQueueItems());
