<?php
include_once __DIR__ . '/_common.php';

if ($is_admin != 'super') {
  alert_close('최고관리자만 접근 가능합니다.');
}



if (!isset($_POST['addon']) || empty($_POST['addon'])) {
  alert('애드온 이름이 지정되지 않았습니다.');
}

$addon_name = $_POST['addon'];
$filter = [
  "addon",
  "token"
];

if (array_key_exists($addon_name, AddonLoader::$addons)) {
  $addon = AddonLoader::$addons[$addon_name];

  $config_data = [];
  foreach ($_POST as $key => $value) {
    if (!in_array($key, $filter)) {
      $config_data[$key] = $value;
    }
  }

  $config_data["saved_date"] = (new DateTime())->getTimestamp();

  $config_json = addslashes(json_encode($config_data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));

  $sql = " SELECT COUNT(*) as cnt FROM {$g5['addons_config_table']} WHERE addon_name = '{$addon_name}' ";
  $row = sql_fetch($sql);

  if ($row['cnt'] > 0) {
    $sql = " UPDATE {$g5['addons_config_table']}
                SET addon_config = '{$config_json}',
                    addon_version = '{$addon->version}'
              WHERE addon_name = '{$addon_name}' ";
  } else {
    $sql = " INSERT INTO {$g5['addons_config_table']}
                SET addon_name = '{$addon_name}',
                    addon_config = '{$config_json}',
                    addon_version = '{$addon->version}' ";
  }

  sql_query($sql);
} else {
  alert("애드온이 설정되지 않았습니다.");
}

goto_url('./addon_config.php?addon=' . $addon_name);
