<?php

declare(strict_types=1);

namespace Plugin\cin_ajax_search_5;

require_once __DIR__.'/vendor/autoload.php';

use Cin\AjaxSearch5\CronJob;
use Cin\AjaxSearch5\Index;
use Cin\AjaxSearch5\Licence;
use Cin\AjaxSearch5\LicenceWidget;
use Cin\AjaxSearch5\Plugin;
use Exception;
use JTL\Backend\NotificationEntry;
use JTL\Cron\JobHydrator;
use JTL\Events\Dispatcher;
use JTL\Plugin\Bootstrapper;
use JTL\Shop;
use PDO;

final class Bootstrap extends Bootstrapper
{
  private const TPL_TEXTAREA = PFAD_ROOT.'admin/opc/tpl/config/config.textarea.tpl';

  private $P;

  public function boot(Dispatcher $dispatcher): void
  {
    parent::boot($dispatcher);
    // listen for admin calls
    if (0 === Shop::getPageType() && str_starts_with($_SERVER['REQUEST_URI'], URL_SHOP.'/admin/')) {
      $L = new Licence();
      if ( ! $L->canRun()) {
        $this->licenceNotification();
      }
    }

    $gettext = Shop::Container()->getGetText();

    $language = $gettext->setLanguage();

    $pluginDir = $this->P()->getJtlPlugin()->getPaths()->getBasePath();

    if (method_exists($language, 'loadAdminLocale')) {      // Shop 5.6+
      // Shop::Container()->getGetText()->setLanguage()->loadTranslations($this->P()->getJTlPlugin()->getPaths()->getBasePath(), 'custom');
      $language->loadAdminLocale($pluginDir, 'custom');
    } else {
      // Shop 5.4 / 5.5
      $language->loadTranslations($pluginDir, 'custom');
    }

    // Shop::Container()->getGetText()->setLanguage()->loadTranslations($this->P()->getJTlPlugin()->getPaths()->getBasePath(), 'custom');

    if ( ! file_exists(self::TPL_TEXTAREA)) {
      try {
        file_put_contents(self::TPL_TEXTAREA, file_get_contents(__DIR__.'/common/textarea.tpl'));
      } catch (Exception $e) {
      }
    }
  }

  public function enabled(): void
  {
    LicenceWidget::initializeWidget();
  }

  public function installed(): void
  {
    LicenceWidget::initializeWidget();
  //   parent::installed();

  //   $cronJob = new CronJob(
  //     Shop::Container()->getDB(),
  //     Shop::Container()->getLogService(),
  //     new JobHydrator(),
  //     Shop::Container()->getCache()
  //   );
  //   $cronJob->installCron(3, '01:30');
  }

  public function uninstalled(bool $deleteData = true): void
  {
    Index::dropAll(false);
    LicenceWidget::checkRemoveWidget();
    $this->unsetSession();
    // $cronJob = new CronJob(
    //   Shop::Container()->getDB(),
    //   Shop::Container()->getLogService(),
    //   new JobHydrator(),
    //   Shop::Container()->getCache()
    // );
    // $cronJob->uninstallCron(3, '01:30');
  }

  public function updated($oldVersion, $newVersion): void
  {
    LicenceWidget::initializeWidget();
    $this->unsetSession();
  }

  private function getSettingsTabID(string $identifier): string
  {
    $pdo  = $this->P()->getPDO();
    $prep = $pdo->prepare('SELECT kPluginAdminMenu FROM tpluginadminmenu WHERE kPlugin = :kPlugin AND cName = :cName');

    $prep->execute([
      'kPlugin' => $this->getPlugin()->getID(),
      'cName'   => $identifier
    ]);

    return (string) $prep->fetch(PDO::FETCH_COLUMN) ?: 0;
  }

  private function licenceNotification(): void
  {
    $this->addNotify(
      NotificationEntry::TYPE_DANGER,
      $this->getPlugin()->getMeta()->getName(),
      '<a href="https://www.com-ins-netz.de/Support-Hilfecenter">Es gibt Probleme mit der Lizenz. Wenden Sie sich an com-ins-netz.de</a>'
    );
  }

  private function P(): Plugin
  {
    return $this->P ?? ($this->P = new Plugin());
  }

  private function unsetSession(): void
  {
    unset(
      $_SESSION["{$this->getPlugin()->getPluginID()}_versionResponse"],
      $_SESSION["{$this->getPlugin()->getPluginID()}_productHomepage"]
    );
  }
}
