<?php

declare(strict_types=1);

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

$licence         = json_decode($L->getContent(), false);
$lang            = $P->getJTlPlugin()->getLocalization()->getTranslations();
$hosting         = preg_replace('(^https?://)', '', URL_SHOP);
$versionResponse = (static function () use ($licence, $P): object {
  if ( ! isset($_SESSION["{$licence->productidentifier}_versionResponse"])) {
    $versionresponderURL = 'https://www.com-ins-netz.de/plugins/versionresponder/';

    try {
      $payload = [
        'productidentifier' => $licence->productidentifier,
        'productversion'    => $P->getJTlPlugin()->getMeta()->getVersion(),
        'phpversion'        => \PHP_VERSION
      ];
      $cs = curl_init($versionresponderURL);
      curl_setopt($cs, \CURLOPT_RETURNTRANSFER, true);
      curl_setopt($cs, \CURLOPT_CUSTOMREQUEST, 'POST');
      curl_setopt($cs, \CURLOPT_POSTFIELDS, json_encode($payload));
      curl_setopt($cs, \CURLOPT_HTTPHEADER, ['Content-Type:application/json']);
      $result = curl_exec($cs);
      curl_close($cs);
      if (false === $result) {
        throw new Exception('Error Processing Request', 1);
      }
      $response = json_decode($result, false);
      if (false === $response || null === $response) {
        throw new Exception('Error Decoding Response', 2);
      }
      if ('success' === $response->status) {
        $_SESSION["{$licence->productidentifier}_versionResponse"] = $response->data->update;
        $_SESSION["{$licence->productidentifier}_productHomepage"] = $response->data->homepage;
      } else {
        exit(var_dump($response));
      }
    } catch (\Throwable $th) {
      $_SESSION["{$licence->productidentifier}_versionResponse"]            = new stdClass();
      $_SESSION["{$licence->productidentifier}_versionResponse"]->available = false;
      $_SESSION["{$licence->productidentifier}_productHomepage"]            = '';
    }
  }

  return $_SESSION["{$licence->productidentifier}_versionResponse"];
})();

$smarty->assign('licence', (array) $licence);
$smarty->assign('assetURL', $P->getJTlPlugin()->getPaths()->getAdminURL());
$smarty->assign('commonURL', $P->getJTlPlugin()->getPaths()->getBaseURL().'common/');
$smarty->assign('pluginMeta', $P->getJTlPlugin()->getMeta());
$smarty->assign('update', $versionResponse);
$smarty->assign('productHomepage', $_SESSION["{$licence->productidentifier}_productHomepage"]);
$smarty->assign('I18N', json_encode($lang, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_UNICODE | \JSON_UNESCAPED_SLASHES));
$smarty->assign('exsLicenced', $P->getJTlPlugin()->getLicense()->getExsLicense() !== null);

$smarty->assign('files_css', ['admin']);
$smarty->assign('files_js', []);

$smarty->display($P->getJTlPlugin()->getPaths()->getAdminPath().'template/dashboard.tpl');
