<?php

declare(strict_types=1);

// 'use Braesident\Logger\Logger;'
use Cin\AjaxSearch5\Index;

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';
// Logger::Debug('in reindex');

if ('GET' === $_SERVER['REQUEST_METHOD']) {
  // $page = file_get_contents(__DIR__.'/template/reindex.tpl');
  $s = new Smarty();
  $s->assign('reindexjs', file_get_contents(__DIR__.'/js/reindex.js'));
  $s->assign('ri_url', $P->getJTlPlugin()->getPaths()->getAdminURL().'cron.php');
  $s->assign('i_start', $P->getJTlPlugin()->getPaths()->getAdminURL().'reindex.php');
  $s->display(__DIR__.'/template/reindex.tpl');
  exit();
}
// Logger::Debug('in reindexq');
if ('POST' === $_SERVER['REQUEST_METHOD']) {
  $response          = new stdClass();
  $response->message = '';
  $response->status  = 'success';

  $languages = Index::readLanguages();

  switch ($_POST['method']) {
    case 'check':
      // Logger::Debug('in case check');
      $stmt = $P->getPDO()->prepare("SELECT COUNT(*) AS 'count' FROM `xplugin_cin_ajax_search_5_tmp`");
      $r    = $stmt->execute();
      // Logger::Debug('r'.print_r($r, true));
      $response->status = $stmt->fetchColumn() > 0 ? 'continue' : 'restart';
      // Logger::Debug('response'.print_r($response, true));

      break;

    case 'cron':
      // Logger::Debug('in case cron');
      $stmt = $P->getPDO()->prepare('TRUNCATE `xplugin_cin_ajax_search_5_tmp`')->execute();
      if (false === $stmt) {
        $response->status = 'error';

        break;
      }

      $sql = 'INSERT INTO `xplugin_cin_ajax_search_5_tmp`(`kArtikel`)
      SELECT kArtikel FROM tartikel';

      $cfg = $P->cfg();
      // Logger::Debug('cfg '.print_r($cfg, true));
      $includeChildren = true === $P->getConfig('includechildren');

      if ( ! $includeChildren) {
        $sql .= ' WHERE kVaterArtikel = 0';
      }

      $sql .= ' ORDER BY kArtikel';

      $stmt = $P->getPDO()
        ->prepare($sql)
        ->execute();

      file_put_contents(__DIR__.'/debug.txt', $stmt);
      Index::dropAll();

      if (false === $stmt) {
        $response->status = 'error';
      }

      $response->status = 'continue';

      break;
  }

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