<?php

namespace Drupal\nodehive_core\Plugin\DashboardBlock;

use Drupal\Component\Datetime\TimeInterface;
use Drupal\content_planner\DashboardBlockBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a User Statistics block for Content Planner Dashboard.
 *
 * @DashboardBlock(
 *   id = "nodehive_user_statistics_block",
 *   name = @Translation("NodeHive User Statistics Widget"),
 *   category = "NodeHive",
 *   id_category = "nodehive"
 * )
 */
class NodeHiveUserStatisticsBlock extends DashboardBlockBase implements ContainerFactoryPluginInterface {

  use StringTranslationTrait;

  /**
   * The time service.
   *
   * @var \Drupal\Component\Datetime\TimeInterface
   */
  protected TimeInterface $time;

  /**
   * {@inheritdoc}
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    EntityTypeManagerInterface $entity_type_manager,
    TimeInterface $time,
  ) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->entityTypeManager = $entity_type_manager;
    $this->time = $time;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('entity_type.manager'),
      $container->get('datetime.time'),
    );
  }

  /**
   * Builds the render array for the dashboard block.
   *
   * @return array
   *   The render array for the dashboard block.
   */
  public function build() {
    // Prepare the statistics.
    $totalUsers = $this->getUserCount();
    $activeUsers = $this->getUserCount(['status' => 1]);
    $blockedUsers = $this->getUserCount(['status' => 0]);
    $onlineLast24Hours = $this->getOnlineUsersCount('-24 hours');
    $onlineLast30Days = $this->getOnlineUsersCount('-30 days');
    $onlineLast90Days = $this->getOnlineUsersCount('-90 days');

    // Define the header for the statistics table.
    $header = [
      ['data' => $this->t('Statistic'), 'class' => [/* Additional classes if needed */]],
      ['data' => $this->t('Count'), 'class' => [/* Additional classes if needed */]],
    ];

    // Prepare the rows for the table.
    $rows = [
      [$this->t('Total Users'), $totalUsers],
      [$this->t('Active Users'), $activeUsers],
      [$this->t('Blocked Users'), $blockedUsers],
      [$this->t('Online in the Last 24 Hours'), $onlineLast24Hours],
      [$this->t('Online in the Last 30 Days'), $onlineLast30Days],
      [$this->t('Online in the Last 90 Days'), $onlineLast90Days],
    ];

    // Prepare the render array for the table.
    $build['user_statistics_table'] = [
      '#type' => 'table',
      '#header' => $header,
      '#rows' => $rows,
      '#empty' => $this->t('No statistics available.'),
    // Add custom table classes if needed.
      '#attributes' => ['class' => ['my-custom-class']],
      '#cache' => [
    // Cache the block for 1 hour.
        'max-age' => 3600,
      ],
    ];

    return $build;
  }

  /**
   * Gets the count of users based on specified conditions.
   *
   * @param array $conditions
   *   Conditions to apply to the query.
   *
   * @return int
   *   The count of users.
   */
  protected function getUserCount(array $conditions = []) {
    $query = $this->entityTypeManager->getStorage('user')->getQuery();
    // Assuming you want to bypass access checks.
    $query->accessCheck(FALSE);
    foreach ($conditions as $field => $condition) {
      if ($field === 'access' && isset($condition['operator']) && $condition['operator'] === 'BETWEEN' && isset($condition['value'])) {
        // Apply the BETWEEN condition correctly.
        $query->condition($field, $condition['value'], 'BETWEEN');
      }
      else {
        // Apply other conditions normally.
        $query->condition($field, $condition);
      }
    }
    return $query->count()->execute();
  }

  /**
   * Gets the count of users who were online within a specified time period.
   *
   * @param string $time_period
   *   A string compatible with strtotime(), defining the time period.
   *
   * @return int
   *   The count of users.
   */
  protected function getOnlineUsersCount($time_period) {
    $current_time = $this->time->getRequestTime();
    $time_threshold = strtotime($time_period, $current_time);
    // Correctly applying the BETWEEN operator with the range.
    return $this->getUserCount([
      'access' => [
        'operator' => 'BETWEEN',
        'value' => [$time_threshold, $current_time],
      ],
      'status' => 1,
    ]);
  }

}
