<?php
$currentDir = dirname(__DIR__, 3); // 3 seviye yukarı çıkar

function parseSizeToBytes($sizeStr) {
    $sizeStr = strtolower(trim($sizeStr));
    $value = floatval(preg_replace('/[^0-9.]/', '', $sizeStr));
    if (strpos($sizeStr, 'tb') !== false) return $value * 1024 ** 4;
    if (strpos($sizeStr, 'gb') !== false) return $value * 1024 ** 3;
    if (strpos($sizeStr, 'mb') !== false) return $value * 1024 ** 2;
    if (strpos($sizeStr, 'kb') !== false) return $value * 1024;
    return $value;
}

// 📁 Dizin boyutunu hesapla
function getDirSize($dir) {
    $size = 0;
    if (!is_dir($dir)) return 0;
    try {
        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS)
        );
        foreach ($iterator as $file) {
            if ($file->isFile()) $size += $file->getSize();
        }
    } catch (Exception $e) {
        return 0;
    }
    return $size;
}

function getCpuUsage() {
    $stat1 = file_get_contents("/proc/stat");
    usleep(300000);
    $stat2 = file_get_contents("/proc/stat");
    $cpu1 = explode(" ", preg_replace("!cpu +!", "", explode("\n", $stat1)[0]));
    $cpu2 = explode(" ", preg_replace("!cpu +!", "", explode("\n", $stat2)[0]));
    $dif = array_map(fn($a,$b)=>$b-$a,$cpu1,$cpu2);
    $total = array_sum($dif);
    return round(100 * (1 - $dif[3] / $total), 2);
}

function getRamUsage() {
    $meminfo = file_get_contents("/proc/meminfo");
    preg_match("/MemTotal:\s+(\d+)/", $meminfo, $total);
    preg_match("/MemAvailable:\s+(\d+)/", $meminfo, $avail);
    if (!isset($total[1]) || !isset($avail[1])) return 0;
    $used = $total[1] - $avail[1];
    return round(($used / $total[1]) * 100, 2);
}

// 💾 Disk kullanımı: çalıştığı dizin ve kota üzerinden
function getDiskUsage($path, $limitStr) {
    $limitBytes = parseSizeToBytes($limitStr);
    $usedBytes = getDirSize($path);
    $usedMB = $usedBytes / (1024 ** 2);
    $totalMB = $limitBytes / (1024 ** 2);
    $percent = $limitBytes > 0 ? round(($usedBytes / $limitBytes) * 100, 2) : 0;
    return [ 'percent' => min($percent, 100), 'used_mb' => round($usedMB, 1), 'total_mb' => round($totalMB, 1) ];
}

// 📊 Verileri hazırla
$diskData = getDiskUsage($currentDir, $module["disk_size"]);
$data = [ 'cpu' => ceil(getCpuUsage()), 'ram' => ceil(getRamUsage()), 'disk' => ceil($diskData['percent']), 'disk_used' => $diskData['used_mb'], 'disk_total' => $module["disk_size"] ];
?>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', {'packages':['gauge']});
google.charts.setOnLoadCallback(drawCharts);

function drawCharts() {
    const data = <?php echo json_encode($data); ?>;
    const gaugeOpts = {min:0,max:100,yellowFrom:75,yellowTo:90,redFrom:90,redTo:100,minorTicks:5};

    new google.visualization.Gauge(document.getElementById('cpu-chart'))
        .draw(google.visualization.arrayToDataTable([['Label','Value'],['CPU',data.cpu]]),gaugeOpts);
    new google.visualization.Gauge(document.getElementById('ram-chart'))
        .draw(google.visualization.arrayToDataTable([['Label','Value'],['RAM',data.ram]]),gaugeOpts);
    new google.visualization.Gauge(document.getElementById('disk-chart'))
        .draw(google.visualization.arrayToDataTable([['Label','Value'],['Disk',data.disk]]),gaugeOpts);

    document.getElementById("disk-info").innerHTML = `Kullanım: ${data.disk_used} MB / ${data.disk_total} MB`;
}
</script>

<div class="v3-col-xl-6 v3-col-md-6 v3-col-sm-12 v3-col-xs-12 mb-3" id="server">
	<section class="card card-featured-left card-featured-danger bgt">
		<header class="card-header">
			<h2 class="card-title"><i class="fa fa-server"></i> <?php echo ctranslate("Server Kullanımı")?></h2>
			<p class="card-subtitle"><?php echo ctranslate("Değerler yaklaşık bilgilerdir")?></p>
		</header>
		<div class="card-body dbcb" style="<?php echo ($mobile=="")?'height:275px;':'height:175px;'; ?>overflow:hidden;background:#ffffff08;padding:0;">
			<div class="row text-center">
				<div class="v3-col-md-4 v3-col-xs-4"><div id="cpu-chart" style="width:400px;height:200px;"></div></div>
				<div class="v3-col-md-4 v3-col-xs-4"><div id="ram-chart" style="width:400px;height:200px;"></div></div>
				<div class="v3-col-md-4 v3-col-xs-4">
					<div id="disk-chart" style="width:400px;height:200px;"></div>
					<div id="disk-info" style="font-size:11px;color:#ccc;"></div>
				</div>
			</div>
		</div>
	</section>
</div>