<?php
// update_bandwidth.php — VPS bandwidth logger
error_reporting(0);
date_default_timezone_set('Asia/Manila');

// --- Database connection ---
$servername = "185.61.137.174";
$username   = "firenetv_kopiko";
$password   = "firenetv_kopiko";
$dbname     = "firenetv_kopiko";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("DB Connection failed: " . $conn->connect_error);
}

// --- Get list of servers from server_list table ---
$result = $conn->query("SELECT server_ip FROM server_list WHERE status = 'online'");

while ($row = $result->fetch_assoc()) {
    $server_ip = trim($row['server_ip']);

    // Use vnstat to get current TX/RX bytes (install with: sudo apt install vnstat)
    $output = shell_exec("vnstat -i eth0 --json | grep -Eo '[0-9]+' | head -n 4");
    preg_match_all('/[0-9]+/', $output, $matches);
    
    $bytes_received = isset($matches[0][1]) ? (int)$matches[0][1] * 1024 : 0;
    $bytes_sent     = isset($matches[0][2]) ? (int)$matches[0][2] * 1024 : 0;

    // Insert record
    $stmt = $conn->prepare("INSERT INTO bandwidth_logs (server_ip, bytes_received, bytes_sent, username, time) VALUES (?, ?, ?, ?, NOW())");
    $user = 'system'; // placeholder user for system log
    $stmt->bind_param("siis", $server_ip, $bytes_received, $bytes_sent, $user);
    $stmt->execute();
    $stmt->close();
}

$conn->close();
echo "Bandwidth updated at " . date("Y-m-d H:i:s") . "\n";
?>
