<?php

declare(strict_types=1);

use Cin\Quickpurchase\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';

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

if ('POST' === $_SERVER['REQUEST_METHOD']) {
  $response          = new stdClass();
  $response->message = '';
  $response->status  = 'success';

  $languages = Index::readLanguages();

  switch ($_POST['method']) {
    case 'check':

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

      $response->status = $stmt->fetchColumn() > 0 ? 'continue' : 'restart';

      break;

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

        break;
      }

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

      $cfg = $P->cfg();

      $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);
