<?php
require __DIR__ . "/koneksi.php";
require __DIR__ . "/helpers/mailer.php";
require __DIR__ . "/helpers/telegram.php";

header('Content-Type: application/json');

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

$MAX_TEMP     = (float)($settings['max_temperature'] ?? 75);
$SEND_EMAIL   = (int)($settings['notify_email'] ?? 0);
$SEND_TG      = (int)($settings['notify_telegram'] ?? 0);
$NOTIFY_SOUND = (int)($settings['notify_sound'] ?? 0);

$ADMIN_EMAIL = $settings['admin_email'] ?? null;

$ADMIN_CC = [];
if (!empty($settings['admin_email_cc'])) {
    $ADMIN_CC = array_filter(array_map('trim', explode(',', $settings['admin_email_cc'])));
}

// ======================
// TELEGRAM
// ======================
$TG_TOKEN = $settings['telegram_bot_token'] ?? null;
$TG_CHAT  = !empty($settings['telegram_chat_id'])
    ? array_filter(array_map('trim', explode(',', $settings['telegram_chat_id'])))
    : [];

// ======================
// DATA PC TERAKHIR
// ======================
$sql = "
SELECT 
    c.id,
    c.hostname,
    c.ip_address,
    c.last_seen,
    m.sensors
FROM pc_clients c
LEFT JOIN pc_monitoring m 
    ON m.id = (
        SELECT id FROM pc_monitoring
        WHERE pc_client_id = c.id
        ORDER BY id DESC
        LIMIT 1
    )
";

$result = $conn->query($sql);
$now = time();
$activeAlertCount = 0;

// ======================
// LOOP PC
// ======================
while ($pc = $result->fetch_assoc()) {

    $pc_id  = (int)$pc['id'];
    $online = strtotime($pc['last_seen']) > ($now - 120);

    $sensors = json_decode($pc['sensors'] ?? '', true);

    $temp = null;
    if (is_array($sensors)) {
        $temp = $sensors['cpu_temp'][0]['value']
            ?? $sensors['temperatures'][0]['value']
            ?? null;
    }

    // ======================
    // 🔥 ALERT AKTIF
    // ======================
    if ($online && $temp !== null && $temp >= $MAX_TEMP) {

        $check = $conn->query("
            SELECT id FROM alert_log
            WHERE pc_id = $pc_id
              AND alert_type = 'temperature'
              AND status = 'active'
            LIMIT 1
        ");

        if ($check->num_rows === 0) {

            $message =
                "🔥 *ALERT SUHU TINGGI*\n\n" .
                "🖥 Host : {$pc['hostname']}\n" .
                "🌐 IP   : {$pc['ip_address']}\n" .
                "🌡 Suhu : {$temp} °C\n" .
                "⏰ Waktu: " . date('Y-m-d H:i:s');

            if ($SEND_EMAIL && $ADMIN_EMAIL) {
                sendAlertEmail(
                    $ADMIN_EMAIL,
                    $ADMIN_CC,
                    "🔥 ALERT SUHU TINGGI",
                    str_replace('*', '', $message)
                );
            }

            if ($SEND_TG && $TG_TOKEN && $TG_CHAT) {
                sendTelegram($TG_TOKEN, $TG_CHAT, $message);
            }

            $conn->query("
                INSERT INTO alert_log (pc_id, alert_type, status)
                VALUES ($pc_id, 'temperature', 'active')
            ");
        }

        $activeAlertCount++;

    } else {

        // ======================
        // ✅ RESOLVED (KIRIM NOTIF)
        // ======================
        $alert = $conn->query("
            SELECT id FROM alert_log
            WHERE pc_id = $pc_id
              AND alert_type = 'temperature'
              AND status = 'active'
            LIMIT 1
        ");

        if ($alert->num_rows === 1) {

            $conn->query("
                UPDATE alert_log
                SET status = 'resolved', updated_at = NOW()
                WHERE pc_id = $pc_id
                  AND alert_type = 'temperature'
                  AND status = 'active'
            ");

            $message =
                "✅ *SUHU KEMBALI NORMAL*\n\n" .
                "🖥 Host : {$pc['hostname']}\n" .
                "🌐 IP   : {$pc['ip_address']}\n" .
                "🌡 Suhu : {$temp} °C\n" .
                "⏰ Waktu: " . date('Y-m-d H:i:s');

            if ($SEND_EMAIL && $ADMIN_EMAIL) {
                sendAlertEmail(
                    $ADMIN_EMAIL,
                    $ADMIN_CC,
                    "✅ ALERT RESOLVED",
                    str_replace('*', '', $message)
                );
            }

            if ($SEND_TG && $TG_TOKEN && $TG_CHAT) {
                sendTelegram($TG_TOKEN, $TG_CHAT, $message);
            }
        }
    }
}

// ======================
// RESPONSE
// ======================
echo json_encode([
    "status"        => "ok",
    "active_alert" => $activeAlertCount,
    "notify_sound" => $NOTIFY_SOUND
]);
