<?php
require_once __DIR__ . '/../config/database.php';

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$db = new Database();
$conn = $db->getConnection();

// ================= CONFIG =================
$login_url = "http://10.255.254.21/login";
$data_url  = "http://10.255.254.21/ontinfo_table";

$username = "root"; 
$password = "@lokal234";

$cookie = __DIR__ . "/cookie.txt";

// ================= LOGIN =================
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $login_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
    "username" => $username,
    "password" => $password
]));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

curl_exec($ch);
curl_close($ch);

// ================= AMBIL DATA (JSON) =================
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $data_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

$response = curl_exec($ch);

if ($response === false) {
    die("CURL ERROR: " . curl_error($ch));
}

curl_close($ch);

// simpan debug
file_put_contents("debug_onu.json", $response);

// ================= PARSING JSON =================
$data = json_decode($response, true);

if (!isset($data['data']) || empty($data['data'])) {
    die("DATA KOSONG / LOGIN GAGAL / ENDPOINT SALAH");
}

foreach ($data['data'] as $onu) {

    $sn = $onu['ont_sn'] ?? '';
    $rx = $onu['receive_power'] ?? 0;
    $state = $onu['state'] ?? 0;
    $cause = $onu['last_d_cause'] ?? '';

    // skip kalau SN kosong
    if (empty($sn)) {
        continue;
    }

    // ================= STATUS =================
    $cause = strtolower($cause);

// 🔥 PRIORITAS 1: dari cause
if (strpos($cause, 'laser out') !== false || strpos($cause, 'fiber') !== false) {
    $status = "LASER OUT";
}
elseif (strpos($cause, 'power down') !== false || strpos($cause, 'dying-gasp') !== false) {
    $status = "POWER FAIL";
}

// 🔥 PRIORITAS 2: fallback dari state + RX
else {
    if ($state == 0 && $rx <= -30) {
        $status = "LASER OUT"; // default ke LOS kalau tidak jelas
    } elseif ($rx <= -30) {
        $status = "POWER FAIL";
    } else {
        $status = "ONLINE";
    }
}

    // ================= SIMPAN DB =================
    $conn->query("
        INSERT INTO onu_status (sn, status, rx_power, last_update)
        VALUES ('$sn', '$status', '$rx', NOW())
        ON DUPLICATE KEY UPDATE
            last_status = status,
            status = '$status',
            rx_power = '$rx',
            last_update = NOW()
    ");

    $conn->query("
    INSERT INTO status_onu_histori (sn, status, rx_power, cause, created_at)
    VALUES (
        '$sn',
        '$status',
        '$rx',
        '$cause',
        NOW()
    )
");

    echo "SN: $sn | STATUS: $status | RX: $rx <br>";
}

echo "<br>DONE ✅";
?>