<?php

declare(strict_types=1);

namespace Cin\Quickpurchase\service;

use Cin\Quickpurchase\classes\HistoryCondition;
use PDO;
use stdClass;

final class ConditionService
{
  public static function buildConditionArray(): array
  {
    $P          = PurchaseService::Plugin();
    $conditions = [];

    foreach ($P->cfg() as $cKey => $cValue) {
      if (str_starts_with($cKey, 'cin_ankauf_activate_condition__')) {
        $idx          = explode('__', $cKey)[1];
        $obj          = new stdClass();
        $obj->formula = $P->cfg()['cin_ankauf_condition_'.$idx];
        $obj->name    = $P->lang()['cin_ankauf_name_condition_'.$idx];
        $obj->enabled = $P->cfg()['cin_ankauf_activate_condition__'.$idx];

        $conditions['condition_'.$idx] = $obj;
      }
    }

    return $conditions;
  }

  /**
   * Get a conditon from condition_history by there id.
   */
  public static function getConditionFromHistoryByID(int $id): ?HistoryCondition
  {
    $prep = PurchaseService::Plugin()->getPDO()->prepare('SELECT
      id,
      `key`,
      `name`,
      FROM_BASE64(formula) as formula
      FROM xplugin_cin_purchaseportal_condition_history
      WHERE `id`=:id');

    $prep->execute([':id' => $id]);
    $condition = $prep->fetch();

    return $condition ? new HistoryCondition($condition) : null;
  }

  public static function getConditionHistory(array $columns): array
  {
    array_walk($columns, static function (&$item): void {
      if (false === mb_strpos($item, '`')) {
        $item = '`'.$item.'`';
      }
    });
    $colQuery = implode(',', $columns);

    $prep = PurchaseService::Plugin()->getPDO()->prepare('SELECT '.$colQuery.'
    FROM `xplugin_cin_purchaseportal_condition_history`');

    $prep->execute();

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

  /**
   * Get the id of condition_history by condition key and there data (name and formula).
   */
  public static function getConditionIdFromHistory(string $condition, object $conditionData): int
  {
    $pdo  = PurchaseService::Plugin()->getPDO();
    $data = [
      ':cKey'     => $condition,
      ':cName'    => $conditionData->name,
      ':cFormula' => base64_encode($conditionData->formula)
    ];

    $prep = $pdo->prepare('SELECT id
      FROM xplugin_cin_purchaseportal_condition_history
      WHERE `key`=:cKey AND `name`=:cName AND `formula`=:cFormula');

    $prep->execute($data);

    $id = $prep->fetchColumn();

    if ($id) {
      return $id;
    }

    $prep = $pdo->prepare('INSERT INTO `xplugin_cin_purchaseportal_condition_history`
        (`key`, `name`, `formula`)
        VALUES (:cKey, :cName, :cFormula)');

    $prep->execute($data);

    return (int) $pdo->lastInsertId();
  }
}
