<?php

namespace Drupal\nodehive_core\Plugin\DashboardBlock;

use Drupal\content_planner\DashboardBlockBase;
use Drupal\Core\Database\Database;
use Drupal\Core\StringTranslation\StringTranslationTrait;

/**
 * Provides a Database Health block for Content Planner Dashboard.
 *
 * @DashboardBlock(
 *   id = "nodehive_database_health_block",
 *   name = @Translation("NodeHive Database Health Widget"),
 *   category = "NodeHive",
 *   id_category = "nodehive"
 * )
 */
class NodeHiveDatabaseHealthBlock extends DashboardBlockBase {
  use StringTranslationTrait;

  /**
   * {@inheritdoc}
   */
  public function build() {
    $header = [['data' => $this->t('Metric')], ['data' => $this->t('Value')]];
    $rows = [];

    // Fetch the total size of the database.
    $totalSize = $this->getDatabaseSize();
    $rows[] = [$this->t('Total Database Size'), $this->formatSize($totalSize)];

    $databaseVersion = $this->getDatabaseVersion();
    $rows[] = [$this->t('Database Version'), $databaseVersion];

    $build['database_health_table'] = [
      '#type' => 'table',
      '#header' => $header,
      '#rows' => $rows,
      '#empty' => $this->t('No database health information available.'),
      '#attributes' => ['class' => ['database-health-class']],
      '#cache' => [
    // Consider caching the block for performance.
        'max-age' => 3600,
      ],
    ];

    return $build;
  }

  /**
   * Returns the total database size in bytes.
   */
  protected function getDatabaseSize() {
    $connection = Database::getConnection();
    $database = $connection->getConnectionOptions()['database'];
    $query = $connection->query("SELECT SUM(data_length + index_length) FROM information_schema.TABLES WHERE table_schema = :database", [':database' => $database]);
    return (float) $query->fetchField();
  }

  /**
   * Returns the database server version string.
   */
  protected function getDatabaseVersion() {
    $connection = Database::getConnection();
    return $connection->query("SELECT version()")->fetchField();
  }

  /**
   * Formats a byte value into a human-readable size string.
   */
  protected function formatSize($bytes, $precision = 2) {
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);
    $bytes /= pow(1024, $pow);

    return round($bytes, $precision) . ' ' . $units[$pow];
  }

}
