<?php
/**
 * Functions, filters, and actions for the admin side of WordPress.
 *
 * This file is included by the AUX parent theme functions.php. This file
 * cannot be overridden by a file of the same name in a child theme.
 *
 * @since 1.0.0
 */

use WP_AUX\Entities\AuxCF\OptionsFields\Global\SiteOwnerFieldEntity;
use WP_AUX\Entities\AuxCF\OptionsFields\Global\SiteTechnicalContactFieldEntity;
use WP_AUX\Entities\AuxFramework\Partials\AlertEntity;

/**
 * Check if current user is an administrator
 *
 * @since 1.0.0
 */
function is_current_user_admin(): bool
{
  return in_array('administrator',  wp_get_current_user()->roles);
}

/**
 * Remove WP emoji code
 *
 * @since 1.0.0
 */
remove_action("admin_print_scripts", "print_emoji_detection_script");
remove_action("admin_print_styles", "print_emoji_styles");

/**
 * Disable editing for theme and plugin files under Appearance > Theme File Editor (wp-admin/theme-editor.php)
 *
 * @since 1.0.0
 */
function aux_disable_wp_file_editor(): void
{
  if (!defined('DISALLOW_FILE_EDIT')) {
    define('DISALLOW_FILE_EDIT', TRUE);
  }
}
add_action('admin_init', 'aux_disable_wp_file_editor');

/**
 * Check for plugins for the AUX parent theme and issue admin notices
 *
 * @since 1.0.0
 */
function aux_required_plugins_notices(): void
{
  $acf_pro = is_plugin_active( 'advanced-custom-fields-pro/acf.php' );
  $acf_free = is_plugin_active( 'advanced-custom-fields/acf.php' );

  $notices = [];

  if (!$acf_pro) {
    $notices[] = [
      'type' => 'error',
      'title' => 'Missing Required Plugin',
      'message' => 'Advanced Custom Fields Pro needs to be installed and enabled to use AUX Components.',
    ];
  }

  if ($acf_free) {
    $notices[] = [
      'type' => 'warning',
      'title' => 'Wrong Plugin Version',
      'message' => 'Please deactivate the free version of Advanced Custom Fields. Only the Pro version should be installed and active.',
    ];
  }

  foreach ($notices as $notice) {
    $content = <<<HTML
        <div class="notice notice-%s">
          <p>
          <strong>%s:</strong>
          %s
          </p>
        </div>
    HTML;

    echo sprintf(
      $content,
      $notice['type'],
      $notice['title'],
      $notice['message'],
    );
  }
}
add_action( 'admin_notices', 'aux_required_plugins_notices' );

add_action('all_admin_notices', function() {
  $siteSettingsUrl = admin_url('options-general.php?page=aux-global-settings');

  $checkFields = [
    SiteOwnerFieldEntity::class => 'Site Owner',
    SiteTechnicalContactFieldEntity::class => 'Site Technical Contact',
  ];

  $missingFields = [];

  foreach ($checkFields as $fieldClass => $fieldLabel) {
    $value = aux_get_field($fieldClass::$name, [], 'option');

    if (empty($value)) {
      $missingFields[] = sprintf(
        '<a href="%s#acf-%s"><strong>%s</strong></a>',
        $siteSettingsUrl,
        $fieldClass::$name,
        $fieldLabel
      );
    }
  }

  if (!empty($missingFields)) {
    $content = <<<HTML
        <div class="notice notice-warning">
          <p>
          Please provide a %s in the <a href="%s">Global Options</a> page.
          This information will facilitate site maintenance, upgrades, and support.
          </p>
        </div>
    HTML;

    echo sprintf(
      $content,
      implode(' and ', $missingFields),
      $siteSettingsUrl
    );
  }
});

/**
 * Disable ACF free edition if ACF Pro is already active
 *
 * @since 1.0.0
 */
function aux_disable_acf_with_pro(): void
{
  $acf_pro = is_plugin_active( 'advanced-custom-fields-pro/acf.php' );
  $acf_free = is_plugin_active( 'advanced-custom-fields/acf.php' );

  if ($acf_pro && $acf_free) {
    deactivate_plugins( 'advanced-custom-fields/acf.php' );
  }
}
add_action( 'admin_init', 'aux_disable_acf_with_pro' );

/**
 * Remove WordPress 'W' icon and menu in the admin bar.
 * Add TAMU logo in the Gutenberg editor in CSS.
 *
 * @since 1.0.0
 */
function aux_replace_admin_bar_w_icon(): void
{
  global $wp_admin_bar;
  $menu_id = 'wp-logo'; // the menu id to remove
  $wp_admin_bar->remove_menu($menu_id);

  $tamu_logo = get_template_directory_uri() . '/images/tamu-icons/TAM-white.svg';

  // Using an !important tag to override one that is built-in to WordPress core
  $output = <<<HTML
    <style>
      /* Position the TAMU logo in the Admin bar */
      #wpadminbar #wp-admin-bar-tamu-logo {
        width: 45px;
        height: 45px;
        padding-top: 2px;
      }

      /*
        Set the TAMU logo in the Gutenberg editor
        There isn't a WP hook to do this in PHP yet so we have to use CSS to replace the image.
      */
      body.block-editor-page .edit-post-fullscreen-mode-close > svg {
        display: none;
      }
      body.block-editor-page .editor-header a.edit-post-fullscreen-mode-close:before {
        background-image: url('$tamu_logo');
        background-size: cover;
        top: 10px;
        right: 10px;
        bottom: 10px;
        left: 10px;
      }
    </style>
  HTML;

  echo $output;
}
add_action('wp_before_admin_bar_render', 'aux_replace_admin_bar_w_icon');

/**
 * Add the TAMU logo in the admin bar to replace the WordPress 'W' icon and menu.
 *
 * @since 1.0.0
 */
function aux_add_tamu_logo_in_admin_bar(): void
{
  global $wp_admin_bar;

  $tamu_logo = get_template_directory_uri() . '/images/tamu-icons/TAM-white.svg';
  $logo_img_tag = sprintf('<img src="%s" alt="Texas A&amp;M logo" height="28" width="28" />', $tamu_logo);

  $wp_admin_bar->add_menu( array(
    'id'    => 'tamu-logo',
    'title' => $logo_img_tag,
    'href'  => __(site_url().'/wp-admin/'),
    'meta'  => array(
    'title' => get_bloginfo('name'),
  ),));
}
add_action('admin_bar_menu', 'aux_add_tamu_logo_in_admin_bar', 10);

/**
 * Rearrange the WordPress Admin Menu
 * @since 1.0.0
 * @return  bool or array   Returns true if menu order isn't set or an array of links to menu items.
 */
function aux_custom_menu_order($menu_order): bool|array
{
  if (!$menu_order) return true;
  return array(
    'index.php', // Dashboard
    'admin.php?page=wpengine-common', // WPEngine Menu
    'separator1', // First separator
    'nestedpages',  // Pages menu item if Nested Pages plugin is active
    'edit.php?post_type=page',
    'edit.php?post_type=news',
    'upload.php' // Media
  );
}
add_filter('custom_menu_order', 'aux_custom_menu_order', 10, 1);
add_filter('menu_order', 'aux_custom_menu_order', 10, 1);

AuxCF::prepareHooks();
