<?php

declare(strict_types=1);

namespace Cin\AjaxSearch5;

use Exception;
use JTL\Shop;
use JTL\Widgets\CiNLicenceView;
use PDO;

final class LicenceWidget
{
  private const WEB = 'https://www.com-ins-netz.de';

  public static function checkRemoveWidget(): void
  {
    $installedPlugin = self::fetchInstalledCinPlugin();

    $widgetable = array_filter($installedPlugin, static function ($object) {
      if (basename(\dirname(__DIR__, 1)) === $object['dir']) {
        return false;
      }

      return file_exists(PFAD_ROOT.'plugins/'.$object['dir'].'/src/LicenceWidget.php');
    });

    if (empty($widgetable)) {
      self::removeWidget();
    }
  }

  public static function initializeWidget(): void
  {
    $installed = ! file_exists(PFAD_ROOT.'admin/templates/bootstrap/tpl_inc/widgets/cin_licence_view.tpl') ? '0' : ( ! file_exists(PFAD_ROOT.'includes/src/Widgets/CiNLicenceView.php') ? '0' : CiNLicenceView::WIDGET_VERSION);
    $payload   = [
      'action' => 'requestInstallFiles',
      'data'   => [
        'installed' => $installed
      ]
    ];

    try {
      $cs = curl_init(self::domain().'/plugins/widgetresponder/');
      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) {
        self::writeErrorLog(curl_error($cs));

        throw new Exception('Error Processing Request', 1);
      }

      $response = json_decode($result, false);
      if (false === $response || null === $response) {
        throw new Exception('Error Decoding Response', 2);
      }
      $data = $response->data;
      if (empty($data)) {
        return;
      }

      if (false === file_put_contents(PFAD_ROOT.'includes/src/Widgets/CiNLicenceView.php', base64_decode($data->files->php, true))) {
        return;
      }
      if (false === file_put_contents(PFAD_ROOT.'admin/templates/bootstrap/tpl_inc/widgets/cin_licence_view.tpl', base64_decode($data->files->tpl, true))) {
        return;
      }

      $widgetlogo = PFAD_ROOT.'mediafiles/cin_licence_widget/images/CiNLogoSquare.svg';
      $cinLogo    = \dirname(__DIR__, 1).'/adminmenu/img/CiNLogoSquare.svg';

      if ( ! is_dir(PFAD_ROOT.'mediafiles/cin_licence_widget/images/')) {
        mkdir(PFAD_ROOT.'mediafiles/cin_licence_widget/images/', 0755, true);
      }
      if ( ! file_exists($widgetlogo)) {
        if (false === copy($cinLogo, $widgetlogo)) {
          return;
        }
      }

      if ( ! self::inDBAlready()) {
        self::writeInDB();
      }
    } catch (Exception $e) {
      self::writeErrorLog($e->getMessage());
    }
  }

  private static function domain(): string
  {
    if (file_exists(PFAD_ROOT.'cindev.json')) {
      $j = json_decode(file_get_contents(PFAD_ROOT.'cindev.json'));
      if (isset($j->licence_widget, $j->licence_widget->widgetresponder_url)) {
        return $j->licence_widget->widgetresponder_url;
      }
    }

    return self::WEB;
  }

  private static function fetchInstalledCinPlugin(): array
  {
    $stmt = "SELECT
      tp.cVerzeichnis dir,
      tp.cName identifier
      FROM tplugin tp
      WHERE tp.cURL LIKE '".self::domain()."%'";

    $db   = Shop::Container()->getDB();
    $prep = $db->getPDO()->prepare($stmt);
    $prep->execute();

    return $prep->fetchAll(PDO::FETCH_ASSOC);
  }

  private static function mkdir(string $targetDir): void
  {
  }

  private static function inDBAlready(): bool
  {
    $stmt = "SELECT
      COUNT(*)
      FROM tadminwidgets taw
      WHERE taw.cClass = 'CiNLicenceView'";

    $db   = Shop::Container()->getDB();
    $prep = $db->getPDO()->prepare($stmt);
    $prep->execute();
    $count = $prep->fetch(PDO::FETCH_COLUMN);

    return (bool) (int) $count;
  }

  private static function removeWidget(): void
  {
    try {
      $pdo = Shop::Container()->getDB()->getPDO();

      if (self::inDBAlready()) {
        $stmt = "DELETE FROM tadminwidgets WHERE cClass = 'CiNLicenceView'";
        $prep = $pdo->prepare($stmt);
        $prep->execute();
      }

      if ( ! self::inDBAlready()) {
        $tpl = PFAD_ROOT.'admin/templates/bootstrap/tpl_inc/widgets/cin_licence_view.tpl';
        if (file_exists($tpl)) {
          unlink($tpl);
        }

        $php = PFAD_ROOT.'includes/src/Widgets/CiNLicenceView.php';
        if (file_exists($php)) {
          unlink($php);
        }

        array_map('unlink', glob(PFAD_ROOT.'mediafiles/cin_licence_widget/images/*.*'));

        $prep = $pdo->prepare("DELETE FROM cin_base_data WHERE identifier = 'pluginRangeData'");
        $prep->execute();

        $prep = $pdo->prepare('SELECT count(*) c FROM cin_base_data');
        $prep->execute();

        if (0 === (int) $prep->fetch(PDO::FETCH_COLUMN)) {
          $prep = $pdo->prepare('DROP TABLE IF EXISTS cin_base_data');
          $prep->execute();
        }
      }
    } catch (Exception $e) {
    }
  }

  private static function writeInDB(): void
  {
    $stmt = "SELECT
      taw.kWidget,
      taw.nPos
      FROM tadminwidgets taw
      WHERE taw.eContainer = 'left'";

    $pdo  = Shop::Container()->getDB()->getPDO();
    $prep = $pdo->prepare($stmt);
    $prep->execute();
    $list = $prep->fetchAll(PDO::FETCH_COLUMN | PDO::FETCH_GROUP);

    foreach ($list as $kWidget => $nPosObject) {
      $stmt = 'UPDATE tadminwidgets SET nPos = :nPos WHERE kWidget = :kWidget';

      $prep = $pdo->prepare($stmt);
      $prep->execute([
        ':nPos'    => $nPosObject[0] + 1,
        ':kWidget' => $kWidget
      ]);
    }

    $stmt = "INSERT INTO tadminwidgets
      (kPlugin, cTitle, cClass, eContainer, cDescription, nPos, bExpanded, bActive)
      VALUES (0, 'CiN Lizenz Übersicht', 'CiNLicenceView', 'left',
      'Lizenzübersicht der installierten Plugins der CIN GmbH', 0, 1, 1)";

    $prep = $pdo->prepare($stmt);
    $prep->execute();
  }

  private static function writeErrorLog(string $message): void
  {
    if ( ! is_dir(\dirname(__DIR__, 1).'/log')) {
      mkdir(\dirname(__DIR__, 1).'/log');
    }

    file_put_contents(\dirname(__DIR__, 1).'/log/licencewidget.log', date('Ymd His ').$message, \FILE_APPEND);
  }
}
