<?php

declare(strict_types=1);

require_once \dirname(__DIR__, 3).'/admin/includes/admininclude.php';

/** @var JTL\Backend\AdminAccount $oAccount */
if ( ! $oAccount->permission('PLUGIN_ADMIN_VIEW')) {
  http_response_code(403);
  exit();
}

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

$response          = new stdClass();
$response->message = '';
$response->status  = 'success';
$response->data    = new stdClass();

$languages = Cin\AjaxSearch5\Index::readLanguages();
usort($languages, static fn ($a, $b) => strcmp($a['cStandard'], $b['cStandard']));
$languages  = array_reverse($languages);
$limit      = ceil(50 / \count($languages));
$select_art = 'SELECT kArtikel FROM `xplugin_cin_ajax_search_5_tmp` LIMIT '.$limit;

$stmt = $P->getPDO()->prepare($select_art);
$stmt->execute();
$articles = $stmt->fetchAll(PDO::FETCH_COLUMN);

foreach ($articles as $kArtikel) {
  foreach ($languages as $key => $lang) {
    $index  = new Cin\AjaxSearch5\Index($lang['cISO']);
    $result = $index->upsert((int) $kArtikel);
    if (0 === $key && false === $result) {
      $stmt = $P->getPDO()->prepare('UPDATE `xplugin_cin_ajax_search_5_tmp`  SET `anzahl_versuche` = (anzahl_versuche +1) WHERE kArtikel = :kArtikel');
      $stmt->execute([':kArtikel' => $kArtikel]);

      break;
    }
  }

  if (true === $result) {
    $stmt = $P->getPDO()->prepare('DELETE FROM `xplugin_cin_ajax_search_5_tmp` WHERE kArtikel = :kArtikel');
  } else {
    $stmt = $P->getPDO()->prepare('DELETE FROM `xplugin_cin_ajax_search_5_tmp` WHERE kArtikel = :kArtikel AND anzahl_versuche <> 1');
  }
  $stmt->execute([':kArtikel' => $kArtikel]);
}

$stmt = $P->getPDO()->prepare("SELECT COUNT(*) AS 'count' FROM `xplugin_cin_ajax_search_5_tmp`");
$stmt->execute();
$response->data->tmp = $stmt->fetchColumn();

$sql = "SELECT COUNT(*) AS 'count' FROM tartikel";
if ( ! $P->getConfig('includechildren')) {
  $sql .= ' WHERE kVaterArtikel = 0';
}
$stmt = $P->getPDO()->prepare($sql);
$stmt->execute();
$response->data->articles = $stmt->fetchColumn();

header('Content-Type: application/json');
exit(json_encode($response, 512));
