<?php

namespace Drupal\nodehive_core\Plugin\DashboardBlock;

use Drupal\content_planner\DashboardBlockBase;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\State\StateInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Url;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a Security Alerts Widget for Content Planner Dashboard.
 *
 * @DashboardBlock(
 *   id = "nodehive_security_alerts_widget",
 *   name = @Translation("Security Alerts Widget"),
 *   category = "NodeHive",
 *   id_category = "nodehive"
 * )
 */
class SecurityAlertsWidget extends DashboardBlockBase implements ContainerFactoryPluginInterface {

  use StringTranslationTrait;

  /**
   * The state service.
   *
   * @var \Drupal\Core\State\StateInterface
   */
  protected StateInterface $state;

  /**
   * The date formatter service.
   *
   * @var \Drupal\Core\Datetime\DateFormatterInterface
   */
  protected DateFormatterInterface $dateFormatter;

  /**
   * The module handler.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected ModuleHandlerInterface $moduleHandler;

  /**
   * {@inheritdoc}
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    StateInterface $state,
    DateFormatterInterface $date_formatter,
    ModuleHandlerInterface $module_handler,
  ) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->state = $state;
    $this->dateFormatter = $date_formatter;
    $this->moduleHandler = $module_handler;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('state'),
      $container->get('date.formatter'),
      $container->get('module_handler'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    $alerts = $this->fetchSecurityAlerts();

    // Always display the "Check for Updates" link.
    $update_status_link = [
      '#type' => 'link',
      '#title' => $this->t('Check for updates'),
      '#url' => Url::fromRoute('update.status'),
      '#attributes' => ['class' => ['button', 'button--primary']],
    ];

    // Fetch the last checked timestamp.
    $last_checked = $this->state->get('update_last_check', NULL);
    $last_checked_formatted = $last_checked ? $this->dateFormatter->format($last_checked, 'custom', 'Y-m-d H:i:s') : $this->t('Never');

    $last_checked_markup = [
      '#markup' => $this->t('Last checked for updates: @last_checked', ['@last_checked' => $last_checked_formatted]),
    ];

    // Determine content based on presence of security alerts.
    if (empty($alerts) || (count($alerts) == 1 && isset($alerts[0]['advisory']) && $alerts[0]['advisory'] == $this->t('The Update module is not enabled.'))) {
      $content = $this->renderNoAlertsContent($alerts);
    }
    else {
      $content = $this->renderAlertsTable($alerts);
    }

    $build = [
      'update_status_link' => $update_status_link,
      'content' => $content,
      'last_checked' => $last_checked_markup,
      '#cache' => [
    // Cache for performance.
        'max-age' => 3600,
      ],
    ];

    return $build;
  }

  /**
   * Fetches security alerts from the update module.
   */
  protected function fetchSecurityAlerts() {
    // Check if the Update module is enabled.
    if ($this->moduleHandler->moduleExists('update')) {
      $security_alerts = [];

      // Fetch available update data.
      $available_updates = $this->state->get('update_fetch_task_result', []);

      foreach ($available_updates as $project_name => $project_info) {
        if (isset($project_info['security updates'])) {
          foreach ($project_info['security updates'] as $update) {
            $security_alerts[] = [
              'project' => $project_name,
              'advisory' => $update['title'] . ' - ' . $update['link'],
            ];
          }
        }
      }

      return $security_alerts;
    }
    else {
      // If the Update module is not enabled, return a message indicating this.
      return [['project' => $this->t('Error'), 'advisory' => $this->t('The Update module is not enabled.')]];
    }
  }

  /**
   * Renders the no-alerts state content.
   */
  protected function renderNoAlertsContent($alerts) {
    return [
      '#markup' => '<div class="security-updates-up-to-date">🤘 ' . $this->t('Your site is up to date!') . '</div>',
    ];
  }

  /**
   * Renders security alerts as a table.
   */
  protected function renderAlertsTable($alerts) {
    $header = [
      $this->t('Project'),
      $this->t('Security Advisory'),
    ];

    $rows = [];
    foreach ($alerts as $alert) {
      $rows[] = [$alert['project'], $alert['advisory']];
    }

    return [
      '#type' => 'table',
      '#header' => $header,
      '#rows' => $rows,
      '#empty' => $this->t('No security alerts found.'),
      '#attributes' => ['class' => ['security-alerts-table']],
    ];
  }

}
