<?php
// pages/api_sysinfo.php — 실시간 시스템 정보 API
header('Content-Type: application/json');
require_once __DIR__ . '/../config/database.php';
session_start();
if (empty($_SESSION['user_id'])) { echo json_encode(['error'=>'unauthorized']); exit; }

$isWindows = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN');
$data = ['mem_total'=>0,'mem_free'=>0,'mem_used_pct'=>0,'cpu_usage'=>0,'disk_used_pct'=>0,'disk_total'=>0,'disk_free'=>0,'uptime'=>''];

if ($isWindows) {
    // Memory
    $memTotalBytes = 0;
    $raw = @shell_exec('wmic ComputerSystem get TotalPhysicalMemory /value 2>nul');
    $val = $raw ? preg_replace('/[^0-9]/','',preg_replace('/^TotalPhysicalMemory=/i','',trim($raw))) : '';
    if ($val && is_numeric($val)) $memTotalBytes = (float)$val;
    if (!$memTotalBytes) { $raw=@shell_exec('powershell -NoProfile -command "(Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory" 2>nul'); $val=$raw?trim(preg_replace('/[^0-9]/','',$raw)):''; if($val&&is_numeric($val)) $memTotalBytes=(float)$val; }

    $freeKB = 0;
    $raw = @shell_exec('wmic OS get FreePhysicalMemory /value 2>nul');
    $val = $raw ? preg_replace('/[^0-9]/','',preg_replace('/^FreePhysicalMemory=/i','',trim($raw))) : '';
    if ($val && is_numeric($val)) $freeKB = (float)$val;
    if (!$freeKB) { $raw=@shell_exec('powershell -NoProfile -command "(Get-CimInstance Win32_OperatingSystem).FreePhysicalMemory" 2>nul'); $val=$raw?trim(preg_replace('/[^0-9]/','',$raw)):''; if($val&&is_numeric($val)) $freeKB=(float)$val; }

    $freeBytes = $freeKB * 1024;
    $data['mem_total'] = round($memTotalBytes/1024/1024/1024, 1);
    $data['mem_free'] = round($freeBytes/1024/1024/1024, 1);
    $data['mem_used_pct'] = $memTotalBytes > 0 ? round((1 - $freeBytes/$memTotalBytes)*100, 1) : 0;

    // CPU usage
    $raw = @shell_exec('wmic cpu get LoadPercentage /value 2>nul');
    $val = $raw ? preg_replace('/[^0-9]/','',preg_replace('/^LoadPercentage=/i','',trim($raw))) : '';
    $data['cpu_usage'] = ($val && is_numeric($val)) ? (int)$val : 0;
    if (!$data['cpu_usage']) { $raw=@shell_exec('powershell -NoProfile -command "(Get-CimInstance Win32_Processor).LoadPercentage" 2>nul'); if($raw&&is_numeric(trim($raw))) $data['cpu_usage']=(int)trim($raw); }

    // Uptime
    $raw = @shell_exec('wmic os get LastBootUpTime /value 2>nul');
    $bootStr = $raw ? preg_replace('/[^0-9.]/','',preg_replace('/^LastBootUpTime=/i','',trim($raw))) : '';
    if (strlen($bootStr) >= 14) {
        $bt = substr($bootStr,0,4).'-'.substr($bootStr,4,2).'-'.substr($bootStr,6,2).' '.substr($bootStr,8,2).':'.substr($bootStr,10,2);
        $diff = time()-strtotime($bt);
        if ($diff>0) { $dd=floor($diff/86400); $hh=floor(($diff%86400)/3600); $mm=floor(($diff%3600)/60); $data['uptime']="{$dd}일 {$hh}시간 {$mm}분"; }
    }
} else {
    // Linux
    $memInfo = @file_get_contents('/proc/meminfo');
    if ($memInfo) {
        preg_match('/MemTotal:\s+(\d+)/', $memInfo, $mt);
        preg_match('/MemAvailable:\s+(\d+)/', $memInfo, $ma);
        if ($mt) $data['mem_total'] = round($mt[1]/1024/1024, 1);
        if ($ma && $mt) {
            $data['mem_free'] = round($ma[1]/1024/1024, 1);
            $data['mem_used_pct'] = round((1 - $ma[1]/$mt[1]) * 100, 1);
        }
    }
    // CPU
    $load = @sys_getloadavg();
    $cores = (int)@shell_exec('nproc 2>/dev/null') ?: 1;
    $data['cpu_usage'] = $load ? round($load[0] / $cores * 100, 1) : 0;

    // Uptime
    $uptime = @file_get_contents('/proc/uptime');
    if ($uptime) { $sec=(int)$uptime; $d=floor($sec/86400); $h=floor(($sec%86400)/3600); $m=floor(($sec%3600)/60); $data['uptime']="{$d}일 {$h}시간 {$m}분"; }
}

// Disk
$diskFree = @disk_free_space(__DIR__); $diskTotal = @disk_total_space(__DIR__);
$data['disk_total'] = $diskTotal ? round($diskTotal/1024/1024/1024, 1) : 0;
$data['disk_free'] = $diskFree ? round($diskFree/1024/1024/1024, 1) : 0;
$data['disk_used_pct'] = ($diskTotal && $diskFree) ? round((1 - $diskFree/$diskTotal)*100, 1) : 0;
$data['timestamp'] = date('H:i:s');

echo json_encode($data);
