<?php
session_start();

// Pastikan user sudah login (jika Anda menggunakan autentikasi di index.php)
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    header("Location: index.php");
    exit;
}

$dataFile = __DIR__ . '/mikrotik_list.json';

// safety: file must exist
if (!file_exists($dataFile)) {
    $_SESSION['status_msg'] = '<p style="color:#e74c3c;font-weight:bold;padding:10px;border:1px solid #e74c3c;border-radius:5px;background:#442323;">❌ File konfigurasi Mikrotik tidak ditemukan.</p>';
    header("Location: index.php");
    exit;
}

if (!isset($_GET['id']) && !isset($_POST['id'])) {
    header("Location: index.php");
    exit;
}

$id = isset($_GET['id']) ? intval($_GET['id']) : intval($_POST['id']);
$mikrotikList = json_decode(file_get_contents($dataFile), true);
if (!is_array($mikrotikList)) $mikrotikList = [];

if (!isset($mikrotikList[$id])) {
    $_SESSION['toast_error'] = "Data Mikrotik tidak ditemukan.";
    header("Location: index.php");
    exit;
}

// Telegram helper: include telegram.php if exists, otherwise define fallback sendTelegram
if (file_exists(__DIR__ . '/telegram.php')) {
    require_once __DIR__ . '/telegram.php';
} else {
    if (!function_exists('sendTelegram')) {
        function sendTelegram($bot_token, $chat_id, $message) {
            if (empty($bot_token) || empty($chat_id) || empty($message)) return false;
            $url = "https://api.telegram.org/bot" . urlencode($bot_token) . "/sendMessage";
            $payload = [
                'chat_id' => $chat_id,
                'text' => $message,
                'parse_mode' => 'HTML'
            ];
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 5);
            $res = curl_exec($ch);
            if ($res === false) {
                error_log("[sendTelegram] cURL error: " . curl_error($ch));
                curl_close($ch);
                return false;
            }
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);
            $dec = json_decode($res, true);
            if (is_array($dec) && isset($dec['ok']) && $dec['ok'] === true) {
                return true;
            }
            error_log("[sendTelegram] HTTP {$httpCode} Response: " . $res);
            return false;
        }
    }
}

// Ambil item saat ini
$mt = $mikrotikList[$id];

// Proses form submit
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Ambil data lama untuk fallback notifikasi
    $old = $mikrotikList[$id];

    // Sanitasi sederhana
    $name = trim($_POST['name'] ?? '');
    $ip   = trim($_POST['ip'] ?? '');
    $user = trim($_POST['user'] ?? '');
    $pass = $_POST['pass'] ?? '';
    $bot_token = trim($_POST['bot_token'] ?? '');
    $chat_id   = trim($_POST['chat_id'] ?? '');

    // Update
    $mikrotikList[$id]['name']      = $name;
    $mikrotikList[$id]['ip']        = $ip;
    $mikrotikList[$id]['user']      = $user;
    $mikrotikList[$id]['pass']      = $pass;
    $mikrotikList[$id]['bot_token'] = $bot_token;
    $mikrotikList[$id]['chat_id']   = $chat_id;

    $written = @file_put_contents($dataFile, json_encode($mikrotikList, JSON_PRETTY_PRINT), LOCK_EX);
    if ($written === false) {
        error_log("[edit.php] Gagal menulis file " . $dataFile);
        $_SESSION['toast_error'] = "Gagal menyimpan perubahan (cek permission).";
        header("Location: index.php");
        exit;
    }

    // Siapkan token/chat untuk notifikasi: pakai yang baru jika ada, fallback ke yang lama
    $bot = $bot_token !== '' ? $bot_token : ($old['bot_token'] ?? '');
    $chat = $chat_id !== '' ? $chat_id : ($old['chat_id'] ?? '');

    if (!empty($bot) && !empty($chat)) {
        $msg = "✏️ Mikrotik diperbarui:\n";
        $msg .= "Nama: " . htmlspecialchars($name) . "\n";
        $msg .= "IP: " . htmlspecialchars($ip);
        if (!sendTelegram($bot, $chat, $msg)) {
            error_log("[edit.php] Gagal mengirim notifikasi Telegram untuk ID {$id}");
        }
    }

    $_SESSION['status_msg'] = '<p style="color:#2e7d32;font-weight:bold;padding:10px;border:1px solid #2e7d32;border-radius:5px;background:#e8f5e9;">✅ Perubahan berhasil disimpan.</p>';
    header("Location: index.php");
    exit;
}

// Re-load item (in case changed)
$mt = $mikrotikList[$id];
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Edit Mikrotik</title>
<link rel="stylesheet" href="admin.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
</head>
<body class="dashboard">
<main>
    <div class="panel">
        <h3>✏️ Edit Mikrotik</h3>
        <form method="post" style="display:flex;flex-direction:column;gap:15px;">
            <input type="hidden" name="id" value="<?= htmlspecialchars($id) ?>">
            <input type="text" name="name" placeholder="🌐 Nama Mikrotik" value="<?= htmlspecialchars($mt['name'] ?? '') ?>" required>
            <input type="text" name="ip" placeholder="🔗 IP / Host VPN API" value="<?= htmlspecialchars($mt['ip'] ?? '') ?>" required>
            <input type="text" name="user" placeholder="👤 Username" value="<?= htmlspecialchars($mt['user'] ?? '') ?>" required>
            <input type="password" name="pass" placeholder="🔑 Password" value="<?= htmlspecialchars($mt['pass'] ?? '') ?>" required>

            <!-- Telegram fields (opsional) -->
            <input type="text" name="bot_token" placeholder="🤖 Bot Token (Telegram) - optional" value="<?= htmlspecialchars($mt['bot_token'] ?? '') ?>">
            <input type="text" name="chat_id" placeholder="💬 Chat ID (Telegram) - optional" value="<?= htmlspecialchars($mt['chat_id'] ?? '') ?>">

            <div class="actions">
                <button type="submit"><i class="fas fa-save"></i> Simpan</button>
                <a class="batal" href="index.php">⬅️ Kembali</a>
            </div>
        </form>
    </div>
</main>
</body>
</html>