<?php

namespace Drupal\pagedesigner_pagetree\Plugin\pagetree\State;

use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\pagetree\Plugin\StatePluginBase;

/**
 * Integrates pagetree actions with the pagedesigner.
 *
 * @StateHandler(
 *   id = "pagedesigner",
 *   name = @Translation("Pagedesigner pagetree state handler"),
 *   weight = 120
 * )
 */
class Pagedesigner extends StatePluginBase {
  use StringTranslationTrait;

  /**
   * Add the pagedesigner state to the pagetree.
   *
   * Annotate the entries of the pagetree
   * with the state depending of the pagedesigner elements.
   *
   * @param array $entries
   *   The entries of the page tree (inout).
   */
  public function annotate(array &$entries) {
    $ids = [];
    foreach ($entries as $key => $entry) {
      $ids[$entry['langcode']][] = $entry['nid'];
      $entries[$key]['#cache']['tags'] = ['pagedesigner:node:' . $entry['nid']];
    }
    foreach ($ids as $langcode => $nodes) {
      $stmt = \Drupal::database()->query(
            "SELECT entity, status FROM pagedesigner_element_field_data WHERE `entity` IN (:nodes[]) AND langcode LIKE :langcode AND status = 0 AND COALESCE(deleted, 0) = 0 GROUP BY entity, status",
            [
              ':nodes[]' => $nodes,
              ':langcode' => $langcode,
            ]
        );
      $results = $stmt->fetchAll(\PDO::FETCH_OBJ);
      foreach ($results as $row) {
        $entries[$row->entity . $langcode]['status'] = 0;
      }
    }
  }

  /**
   * Add the pagedesigner action to the pagetree entries.
   *
   * @param array $entry
   *   An entry of the page tree (inout).
   */
  public function alterEntry(array &$entry) {
    if ($entry['permissions']['update']) {
      $isMultilingual = \Drupal::languageManager()->isMultilingual();
      foreach ($entry['translations'] as $language => &$translation) {
        if ($translation['status'] > -1) {
          $pagedesignerLink = '/node/' . $entry['id'] . '/pagedesigner';
          if ($isMultilingual) {
            $pagedesignerLink = '/' . $language . $pagedesignerLink;
          }
          $translation['actions'][] = [
            'link' => $pagedesignerLink,
            'label' => $this->t(
            'Edit pagedesigner content'
            ),
            'weight' => 100,
          ];
        }
      }
    }
  }

}
