<?php
include realpath(dirname(__DIR__) . '/include/header.php');

// Set file directory path
$directory = '/var/www/html/';
$excludedDirs = ['.', '..', 'RemoteNetGuard', 'NuxSaas', 'Nux','Alvo','cloudTik_account_createion','index.html'];

// Function to recursively get folder size
function getFolderSize($path) {
  $size = 0;
  foreach (scandir($path) as $file) {
    if (in_array($file, ['.', '..'])) continue;
    $fullPath = $path . '/' . $file;
    if (is_file($fullPath)) {
      $size += filesize($fullPath);
    } elseif (is_dir($fullPath)) {
      $size += getFolderSize($fullPath);
    }
  }
  return $size;
}

// Function to format size dynamically
function formatSize($bytes) {
  if ($bytes >= 1073741824) {
    return number_format($bytes / 1073741824, 2) . ' GB';
  } elseif ($bytes >= 1048576) {
    return number_format($bytes / 1048576, 2) . ' MB';
  } elseif ($bytes >= 1024) {
    return number_format($bytes / 1024, 2) . ' KB';
  } else {
    return $bytes . ' B';
  }
}

// Gather items
$items = array_filter(scandir($directory), function ($file) use ($excludedDirs) {
  return !in_array($file, $excludedDirs);
});

$totalSize = 0;
$itemList = [];

foreach ($items as $item) {
  $path = $directory . '/' . $item;
  $isFile = is_file($path);
  $size = $isFile ? filesize($path) : getFolderSize($path);
  $ext = $isFile ? (strtolower(pathinfo($item, PATHINFO_EXTENSION)) ?: 'unknown') : 'folder';
  $totalSize += $size;
  $itemList[] = [
    'name' => $item,
    'is_file' => $isFile,
    'size' => $size,
    'modified' => date("Y-m-d H:i:s", filemtime($path)),
    'ext' => $ext
  ];
}
?>

<div class="col-xl-12">
  <div class="card">
    <div class="card-body">
      <h4 class="card-title">File Manager</h4>
      <p class="card-title-desc">Displays all files and folders with their sizes (including folders recursively).</p>

      <div class="table-responsive">
        <table class="table table-bordered table-hover">
          <thead class="table-light">
            <tr>
              <th>Type</th>
              <th>Name</th>
              <th>Size</th>
              <th>Last Modified</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($itemList as $item): ?>
              <tr>
                <td>
                  <?= $item['is_file'] ? '<i class="bi bi-file-earmark"></i> File' : '<i class="bi bi-folder"></i> Folder' ?>
                </td>
                <td><?= htmlspecialchars($item['name']) ?></td>
                <td><?= formatSize($item['size']) ?></td>
                <td><?= $item['modified'] ?></td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>

      <hr>
      <p><strong>Total Items:</strong> <?= count($itemList) ?></p>
      <p><strong>Total Size:</strong> <?= formatSize($totalSize) ?></p>
    </div>
  </div>
</div>

<?php include realpath(dirname(__DIR__) . '/include/footer.php'); ?>
