<?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 configuration
$servername = "localhost";
$username = "wiselie_nanda"; // Ganti dengan username database Anda
$password = "Clemira123"; // Ganti dengan password database Anda
$dbname = "wiselie_inventory"; // Ganti dengan nama database Anda

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

// Check connection
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']; // Ganti dengan tabel-tabel yang Anda ingin hitung jumlah barisnya

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

// Get server CPU and memory usage
$cpuUsage = getServerCPUUsage();
$memoryUsage = getServerMemoryUsage();

$conn->close();

// Prepare data to send as JSON response
$data = array(
    'cpu' => $cpuUsage,
    'memory' => $memoryUsage,
    'tables' => $tableData
);

echo json_encode($data);
?>
