<?php
namespace WP_AUX\Entities\Admin;

use AuxCF\Entities\FieldGroupEntity;
use WP_AUX\Entities\Admin\AuxComponents\AuxComponentsAuditEntity;
use WP_AUX\Services\HeadService;

class AuxDeprecationsPageEntity {
  public function __construct() {
    add_action( 'admin_menu', array( $this, 'menu' ) );
  }

  /**
   * Add the AUX Components menu under tools.
   * Available to users with the 'install_plugins' capability.
   *
   * @since 1.0.0
   */
  public function menu() {
    $hook = add_management_page(
      'AUX Deprecations',
      'AUX Deprecations',
      'edit_posts',
      'aux-deprecations',
      array( $this, 'adminPage' ),
      null
    );
    add_action( "load-$hook", [ $this, 'adminLoad' ] );
  }

  /**
   * @todo: Dion - after the stories site launch - please document what each of these scripts is used for.
   * @todo: Use a local copy for all scripts and styles. Supply chain attacks have become common. NO REMOTE SCRIPTS ALLOWED (unless it's on one of our servers)
   */
  public function adminLoad() {
    wp_enqueue_style(
      "datatables-css",
      "https://cdn.datatables.net/2.0.8/css/dataTables.dataTables.min.css",
    );

    wp_enqueue_script(
      "datatables-js",
      "https://cdn.datatables.net/2.0.8/js/dataTables.min.js",
    );

    wp_enqueue_script(
      "popper-js",
      "https://unpkg.com/@popperjs/core@2",
    );
    wp_enqueue_script(
      "tippy-js",
      "https://unpkg.com/tippy.js@6",
    );

    add_action('admin_head', function() {
      echo '<style>
      .field-details { display: none; }
      .field-property-source-cell1 { display: none; }
      .field-details.active1 { display: none; }
      </style>';
    }, 100);

    HeadService::enqueueLocalScript('aux-components', 'js/aux-components.js');
    HeadService::enqueueLocalStyle('aux-components-css', 'css/aux-components-audit.css');
  }

  protected static function getDeprecatedFieldPostIds(
    FieldGroupEntity $fieldGroup,
    string $deprecatedFieldName
  ): array {
    global $wpdb;

    $componentName = $fieldGroup->getBlockConfig()->name;
    $like = sprintf('<!-- wp:%s {%%"%s":', $componentName, $deprecatedFieldName);

    $postIds = $wpdb->get_col(
      "SELECT ID FROM $wpdb->posts WHERE post_content LIKE '%{$like}%' AND post_status IN ('publish', 'private', 'pending', 'future', 'draft') "
    );

    if ($postIds) {
      return get_posts(['post__in' => $postIds, 'numberposts' => -1, 'post_type' => 'any']);
    } else {
      return [];
    }
  }

  public function adminPage() {
    $rows = [];

    $fieldGroups = \WP_AUX::instance()->getActiveFieldGroupsEntities();
    foreach ($fieldGroups as $fieldGroup) {
      if ($deprecatedFields = $fieldGroup->getDeprecatedFields()) {
        foreach ($deprecatedFields as $deprecatedFieldName => $deprecatedFieldData) {
          $posts = self::getDeprecatedFieldPostIds($fieldGroup, $deprecatedFieldName);
          $replacedWithEntity = $deprecatedFieldData['replaced_with']::create();

          foreach ($posts as $post) {
            $rows[] = [
              'post_title' => get_the_title($post),
              'post_type' => get_post_type_object(get_post_type($post))->label,
              'post_edit_url' => get_edit_post_link($post),
              'post_view_url' => get_the_permalink($post),
              'component' => $fieldGroup->getTitle(),
              'deprecated_field' => $deprecatedFieldData['label'],
              'replaced_with_field' => $replacedWithEntity->getLabel(),
            ];
          }
        }
      }
    }

    get_template_part('template-parts/admin/aux-deprecations-audit', null, ['rows' => $rows]);
  }
}
