<?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();

$includeChildren = true === $P->getConfig('includechildren');

$languages = Cin\Quickpurchase\Index::readLanguages();
usort($languages, static fn ($a, $b) => strcmp($a['cStandard'], $b['cStandard']));
$languages = array_reverse($languages);
$limit     = ceil(50 / \count($languages));

if ( ! $includeChildren) {
  $stmt = $P->getPDO()->prepare('DELETE t
    FROM `xplugin_cin_quick_purchase_5_tmp` t
    INNER JOIN tartikel ta ON ta.kArtikel = t.kArtikel
    WHERE ta.kVaterArtikel <> 0');
  $stmt->execute();
}

$select_art = 'SELECT t.kArtikel FROM `xplugin_cin_quick_purchase_5_tmp` t';
if ( ! $includeChildren) {
  $select_art .= '
    INNER JOIN tartikel ta ON ta.kArtikel = t.kArtikel
    AND ta.kVaterArtikel = 0';
}
$select_art .= ' ORDER BY t.kArtikel 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\Quickpurchase\Index($lang['cISO']);
    $result = $index->upsert((int) $kArtikel);
    if (0 === $key && false === $result) {
      $stmt = $P->getPDO()->prepare('UPDATE `xplugin_cin_quick_purchase_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_quick_purchase_5_tmp` WHERE kArtikel = :kArtikel');
  } else {
    $stmt = $P->getPDO()->prepare('DELETE FROM `xplugin_cin_quick_purchase_5_tmp` WHERE kArtikel = :kArtikel AND anzahl_versuche <> 1');
  }
  $stmt->execute([':kArtikel' => $kArtikel]);
}

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

$sql = "SELECT COUNT(*) AS 'count' FROM tartikel";
if ( ! $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));

// $languages = Cin\AjaxSearch5\Index::readLanguages();
// usort($languages, static fn ($a, $b) => strcmp($a['cStandard'], $b['cStandard']));
// $languages = array_reverse($languages);

// $indexes = [];
// foreach ($languages as $lang) {
//   $indexes[$lang['cISO']] = new Cin\AjaxSearch5\Index($lang['cISO']);
// }

// if ($useTmp) {
//   $limit     = 100;
//   $sqlSelect = "SELECT kArtikel FROM `xplugin_cin_quick_purchase_5_tmp` LIMIT {$limit}";
//   $articles  = $P->getPDO()->query($sqlSelect)->fetchAll(PDO::FETCH_COLUMN);
// } else {
//   $sqlSelect = 'SELECT kArtikel FROM tartikel';
//   if ( ! $includeChildren) {
//     $sqlSelect .= ' WHERE kVaterArtikel = 0';
//   }
//   $articles = $P->getPDO()->query($sqlSelect)->fetchAll(PDO::FETCH_COLUMN);
// }

// $successArticles = [];
// $failArticles    = [];

// // foreach ($articles as $kArtikel) {
// //   $success = true;

// //   foreach ($languages as $key => $lang) {
// //     $result = $indexes[$lang['cISO']]->upsert((int) $kArtikel);

// //     if (false === $result) {
// //       $success = false;

// //       break;
// //     }
// //   }

// //   if ($success) {
// //     $successArticles[] = $kArtikel;
// //   } else {
// //     $failArticles[] = $kArtikel;
// //   }
// // }

// if ($useTmp && ! empty($successArticles)) {
//   $in   = implode(',', array_map('intval', $successArticles));
//   $stmt = $P->getPDO()->prepare("DELETE FROM `xplugin_cin_quick_purchase_5_tmp` WHERE kArtikel IN ({$in})");
//   $stmt->execute();
// }

// if ($useTmp && ! empty($failArticles)) {
//   $in   = implode(',', array_map('intval', $failArticles));
//   $stmt = $P->getPDO()->prepare("UPDATE `xplugin_cin_quick_purchase_5_tmp` SET anzahl_versuche = anzahl_versuche + 1 WHERE kArtikel IN ({$in})");
//   $stmt->execute();
// }

// if ($useTmp) {
//   $stmt = $P->getPDO()->prepare('SELECT COUNT(*) AS `count` FROM `xplugin_cin_quick_purchase_5_tmp`');
//   $stmt->execute();
//   $response->data->tmp = $stmt->fetchColumn();
// } else {
//   $response->data->tmp = 0;
// }

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

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