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

// Function to get server memory usage (in MB)
function getServerMemoryUsage() {
    $free = shell_exec('free');
    $free = (string)trim($free);
    $free_arr = explode("\n", $free);
    $mem = explode(" ", $free_arr[1]);
    $mem = array_filter($mem);
    $mem = array_merge($mem);
    $memory_usage = $mem[2] / 1024;
    return $memory_usage;
}

// Function to get server CPU usage (percentage)
function getServerCPUUsage() {
    $load = sys_getloadavg();
    return $load[0] * 20 / exec('nproc');
}

// Database connection
$servername = "localhost";
$username = "wiselie_nanda";
$password = "Clemira123";
$dbname = "wiselie_inventory";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die(json_encode(array('error' => 'Database connection failed: ' . $conn->connect_error)));
}

// Function to get row count from a table
function getTableRowCount($conn, $table) {
    $sql = "SELECT COUNT(*) as count FROM $table";
    $result = $conn->query($sql);
    if ($result) {
        $row = $result->fetch_assoc();
        return $row['count'];
    } else {
        return "Error: " . $conn->error;
    }
}

// Tables to read from
$tables = ['awb', 'bom_level', 'categories', 'incoming_goods', 'sales','products'];

$tableData = [];
foreach ($tables as $table) {
    $tableData[$table] = getTableRowCount($conn, $table);
}

$conn->close();

// Gather all data
$data = array(
    'cpu' => getServerCPUUsage(),
    'memory' => getServerMemoryUsage(),
    'tables' => $tableData
);

echo json_encode($data);
?>
