<?php
require __DIR__ . '/../helpers/auth.php';
auth_check();
$user = auth_user();
?>
<?php
$menu  = 'settings';
$title = 'Pengaturan Notifikasi';

// ======================
// AUTH & DB
// ======================
require __DIR__ . '/../api/monitoring/koneksi.php';

// ======================
// Ambil setting
// ======================
$settings = [
    'max_temperature'    => 75,
    'notify_email'       => 0,
    'notify_sound'       => 0,
    'notify_telegram'    => 0,
    'admin_email'        => '',
    'admin_email_cc'     => '',
    'telegram_bot_token' => '',
    'telegram_chat_id'   => ''
];

$res = $conn->query("SELECT key_name, value FROM settings");
while ($row = $res->fetch_assoc()) {
    $settings[$row['key_name']] = $row['value'];
}

// ======================
// Simpan setting
// ======================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $max_temp        = (int)($_POST['max_temperature'] ?? 75);
    $notify_email    = isset($_POST['notify_email']) ? 1 : 0;
    $notify_sound    = isset($_POST['notify_sound']) ? 1 : 0;
    $notify_telegram = isset($_POST['notify_telegram']) ? 1 : 0;

    $admin_email     = trim($_POST['admin_email'] ?? '');
    $admin_email_cc  = trim($_POST['admin_email_cc'] ?? '');
    $telegram_token  = trim($_POST['telegram_bot_token'] ?? '');
    $telegram_chat   = trim($_POST['telegram_chat_id'] ?? '');

    // Validasi ringan
    if ($max_temp < 40)  $max_temp = 40;
    if ($max_temp > 120) $max_temp = 120;

    if ($notify_email && empty($admin_email)) {
        $error = "Email admin wajib diisi jika notifikasi email diaktifkan.";
    } elseif ($notify_telegram && (empty($telegram_token) || empty($telegram_chat))) {
        $error = "Token dan Chat ID Telegram wajib diisi jika notifikasi Telegram aktif.";
    } else {

        $stmt = $conn->prepare("
            INSERT INTO settings (key_name, value)
            VALUES (?, ?)
            ON DUPLICATE KEY UPDATE value=VALUES(value)
        ");

        $stmt->bind_param("ss", $key, $value);

        $key='max_temperature';     $value=$max_temp;       $stmt->execute();
        $key='notify_email';        $value=$notify_email;   $stmt->execute();
        $key='notify_sound';        $value=$notify_sound;   $stmt->execute();
        $key='admin_email';         $value=$admin_email;    $stmt->execute();
        $key='admin_email_cc';      $value=$admin_email_cc; $stmt->execute();
        $key='notify_telegram';     $value=$notify_telegram;$stmt->execute();
        $key='telegram_bot_token';  $value=$telegram_token; $stmt->execute();
        $key='telegram_chat_id';    $value=$telegram_chat;  $stmt->execute();

        // update array settings
        $settings['max_temperature']    = $max_temp;
        $settings['notify_email']       = $notify_email;
        $settings['notify_sound']       = $notify_sound;
        $settings['admin_email']        = $admin_email;
        $settings['admin_email_cc']     = $admin_email_cc;
        $settings['notify_telegram']    = $notify_telegram;
        $settings['telegram_bot_token'] = $telegram_token;
        $settings['telegram_chat_id']   = $telegram_chat;

        $success = "✅ Pengaturan berhasil disimpan";
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title><?= $title ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../assets/css/dashboard.css">

<style>
.settings-form {
    max-width: 500px;
    background: #fff;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 2px 6px rgba(0,0,0,.08);
}
.settings-form label {
    display: block;
    margin: 14px 0;
    font-weight: 500;
}
.settings-form input[type=text],
.settings-form input[type=number],
.settings-form input[type=email] {
    width: 100%;
    padding: 8px;
    margin-top: 6px;
}
.settings-form button {
    margin-top: 16px;
    padding: 10px 18px;
    border: none;
    background: #2b7cff;
    color: #fff;
    border-radius: 6px;
    cursor: pointer;
}
.settings-form button:hover { opacity: .9; }
.alert-success { color: green; }
.alert-error   { color: red; }
</style>
</head>

<body>
<div class="app">

    <?php include __DIR__ . '/../layout/sidebar.php'; ?>
    <main class="main">
        <?php include __DIR__ . '/../layout/header.php'; ?>

        <h2><?= $title ?></h2>

        <?php if (!empty($success)): ?>
            <p class="alert-success"><?= $success ?></p>
        <?php endif; ?>

        <?php if (!empty($error)): ?>
            <p class="alert-error"><?= $error ?></p>
        <?php endif; ?>

        <form method="POST" class="settings-form">

            <label>
                🌡️ Batas Suhu Maksimal (°C)
                <input type="number"
                       name="max_temperature"
                       min="40"
                       max="120"
                       required
                       value="<?= htmlspecialchars($settings['max_temperature']) ?>">
            </label>

            <label>
                📧 Email Penerima Alert
                <input type="email"
                       name="admin_email"
                       placeholder="admin@example.com"
                       value="<?= htmlspecialchars($settings['admin_email']) ?>">
            </label>

            <label>
                📧 CC Email Penerima Alert
                <input type="text"
                       name="admin_email_cc"
                       placeholder="admin1@example.com, admin2@example.com"
                       value="<?= htmlspecialchars($settings['admin_email_cc']) ?>">
            </label>

            <label>
                <input type="checkbox" name="notify_email"
                    <?= $settings['notify_email'] ? 'checked' : '' ?>>
                Aktifkan Notifikasi Email
            </label>

            <label>
                <input type="checkbox" name="notify_sound"
                    <?= $settings['notify_sound'] ? 'checked' : '' ?>>
                Aktifkan Sound Alert
            </label>

            <hr>

            <label>
                🤖 Telegram Bot Token
                <input type="text"
                       name="telegram_bot_token"
                       placeholder="8466xxxx:AAExxxxx"
                       value="<?= htmlspecialchars($settings['telegram_bot_token']) ?>">
            </label>

            <label>
                💬 Telegram Chat ID (pisahkan dengan koma)
                <input type="text"
                       name="telegram_chat_id"
                       placeholder="5731368613,987654321"
                       value="<?= htmlspecialchars($settings['telegram_chat_id']) ?>">
            </label>

            <label>
                <input type="checkbox" name="notify_telegram"
                    <?= $settings['notify_telegram'] ? 'checked' : '' ?>>
                Aktifkan Notifikasi Telegram
            </label>

            <button type="submit">💾 Simpan Pengaturan</button>

        </form>

    </main>
</div>
</body>
</html>
