<?php

namespace Drupal\nodehive_core\Plugin\DashboardBlock;

use Drupal\content_planner\DashboardBlockBase;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Link;
use Drupal\Core\Url;

/**
 * Provides a Nodes Statistics block for Content Planner Dashboard.
 *
 * @DashboardBlock(
 *   id = "nodehive_node_statistics_block",
 *   name = @Translation("Content Type Statistics Widget"),
 *   category = "NodeHive",
 *   id_category = "nodehive"
 * )
 */
class NodeHiveNodeStatisticsBlock extends DashboardBlockBase implements ContainerFactoryPluginInterface {
  use StringTranslationTrait;

  /**
   * {@inheritdoc}
   */
  public function build() {
    $contentTypes = $this->getNodeTypes();
    $header = [
          ['data' => $this->t('Type')],
          ['data' => $this->t('Total')],
          ['data' => $this->t('Published')],
          ['data' => $this->t('Unpublished')],
          ['data' => $this->t('Last 24h')],
          ['data' => $this->t('Last 30d')],
          ['data' => $this->t('Last 90d')],
    ];

    $rows = [];
    foreach ($contentTypes as $contentType => $contentTypeName) {
      $totalNodesCount = $this->getNodeCount($contentType);
      $publishedNodesCount = $this->getNodeCount($contentType, 1);
      $unpublishedNodesCount = $this->getNodeCount($contentType, 0);
      $last24HoursCount = $this->getNodeCountByTimePeriod($contentType, '-24 hours');
      $last30DaysCount = $this->getNodeCountByTimePeriod($contentType, '-30 days');
      $last90DaysCount = $this->getNodeCountByTimePeriod($contentType, '-90 days');

      // Create a link to the content overview page filtered by content type.
      $url = Url::fromUri('internal:/nodehive/admin/content', ['query' => ['type' => $contentType]]);
      $link = Link::fromTextAndUrl($totalNodesCount, $url)->toString();

      $rows[] = [
        $contentTypeName,
      // Total Nodes linked to the content filter page.
        $link,
        $publishedNodesCount,
        $unpublishedNodesCount,
        $last24HoursCount,
        $last30DaysCount,
        $last90DaysCount,
      ];
    }

    $build['node_statistics_table'] = [
      '#type' => 'table',
      '#header' => $header,
      '#rows' => $rows,
      '#empty' => $this->t('No node statistics available.'),
      '#attributes' => ['class' => ['node-statistics-table']],
      '#cache' => [
        'max-age' => 3600,
      ],
      '#attached' => [
        'library' => ['nodehive_core/node-statistics'],
      ],
    ];

    return $build;
  }

  /**
   * Returns all node types keyed by machine name.
   */
  protected function getNodeTypes() {
    $nodeTypes = $this->entityTypeManager->getStorage('node_type')->loadMultiple();
    $types = [];
    foreach ($nodeTypes as $nodeType) {
      $types[$nodeType->id()] = $nodeType->label();
    }
    return $types;
  }

  /**
   * Returns the node count for a given content type and optional status.
   */
  protected function getNodeCount($contentType, $status = NULL) {
    $query = $this->entityTypeManager->getStorage('node')->getQuery()
      ->condition('type', $contentType)
      ->accessCheck(FALSE);

    if ($status !== NULL) {
      $query->condition('status', $status);
    }

    return $query->count()->execute();
  }

  /**
   * Returns node count for a content type within a relative time period.
   */
  protected function getNodeCountByTimePeriod($contentType, $timePeriod) {
    $timeThreshold = strtotime($timePeriod);
    $query = $this->entityTypeManager->getStorage('node')->getQuery()
      ->condition('type', $contentType)
      ->condition('created', $timeThreshold, '>=')
      ->accessCheck(FALSE)
      ->count();
    return $query->execute();
  }

}
