<?php
/**
 * Functions for a Hybrid PHP theme using AUX components.
 * This file includes global variables, shared utilities and php includes for admin and font-end files
 *
 * @see https://developer.wordpress.org/themes/basics/theme-functions/
 * @since 1.0.0
 * @author Texas A&M University Web Team
 */

// Exit if accessed directly
if (!defined("ABSPATH")) {
  exit();
}

use WP_AUX\Services\HeadService;

/**
 * Kint is a PHP debug tool
 * Installation instructions: https://kint-php.github.io/kint/#install
 */
require 'inc/kint.phar';

$auxPluginsDirectories = [];

/**
 * Autoload namespaced code from "inc" directories in parent and child themes
 *
 * If using a child theme, the child theme will be checked first for the file.
 * If the file is found in the child theme, it will be included and the
 * parent theme will not be checked. This allows the child theme to override
 * namespaced files in the parent theme.
 *
 * Developers working locally can experiment and carry on works in progress in a
 * "dev" folder in either the parent or child theme, with the directory structure
 * and namespaces mirroring the theme directory structure. This "dev" folder is
 * ignored in git, allowing works in progress to continue and be tested across branches
 * without creating conflicts or losing work when switching between branches.
 *
 * spl_autoload_register is a built-in PHP function
 * @see https://www.php.net/manual/en/function.spl-autoload-register.php
 * @since 1.0.0
 */
spl_autoload_register(function (string $className) {
  global $auxPluginsDirectories;

  // Create a namespace path as an array. The last item should be the file name.
  $path = explode('\\', ltrim($className, '\\'));

  // If there is only item in the namespace path, add that item to the path.
  // For cases where the file represents the entire namespace (eg: WP_AUX.php in WP_AUX folder)
  if (count($path) === 1) {
    $path[] = $path[0];
  }

  /*
   * Now we put together the list of directories to "try" to locate the requested
   * class. In this way, the child theme can override/replace parent theme code.
   *
   * The order to try will be...
   *
   * 1. The "dev" folder in the child theme, if it exists (for local work in progress or experimentation without conflicts)
   * 2. The "dev" folder in the parent theme, if it exists (for local work in progress or experimentation without conflicts)
   * 3. The child theme directory
   * 4. The parent theme directory
   */
  $tryDirectories = [
    get_template_directory(),
  ];

  /*
   * If using a child theme, tack the child directory onto the top of the list
   * of directories to try
   */
  if (is_child_theme()) {
    array_unshift($tryDirectories, get_stylesheet_directory());
  }

  /*
   * If a "dev" folder exists in the parent theme, tack that directory onto the
   * top of the list of directories to try
   */
  if (is_dir(get_template_directory() . '/dev/')) {
    array_unshift($tryDirectories, get_template_directory() . '/dev');
  }

  /*
   * If using a child them and a "dev" folder exists in the child theme, tack that
   * directory onto the top of the list of directories to try
   */
  if (is_child_theme() && is_dir(get_stylesheet_directory() . '/dev/')) {
    array_unshift($tryDirectories, get_stylesheet_directory() . '/dev');
  }

  /*
   * Add egistered AUX plugin include directories to autoload
   */
  if (!empty($auxPluginsDirectories)) {
    foreach ($auxPluginsDirectories as $namespace => $pluginDir) {
      if (is_dir($pluginDir)) {
        array_unshift($tryDirectories, $pluginDir);
      }
    }
  }

  // Create a path string from the namespace path
  $classPath = join(DIRECTORY_SEPARATOR, $path);

  // Try the directories the file may be found in
  foreach ($tryDirectories as $tryDirectory) {
    if (file_exists($tryDirectory . "/inc/{$classPath}.php")) {
      include $tryDirectory . "/inc/{$classPath}.php";
      break;
    }
  }
});

/**
 * Add an AUX-theme plugin to the AUX autoloader
 * @since 1.0.1
 */
function aux_register_plugin_for_autoload(string $namespace, string $pluginDir): void
{
  global $auxPluginsDirectories;

  if (is_dir($pluginDir) && is_dir($pluginDir . '/inc')) {
    $auxPluginsDirectories[$namespace] = $pluginDir;
  }
}

/**
 * Set up theme feature supports
 *
 * Language is automatically enabled for the theme using the 'text-domain'
 * provided in the effective style.css file (defaults to parent, or child if provided)
 *
 * A primary menu ('menu-1') is registered by default. To remove the primary
 * menu in a child theme, add an 'after_setup_theme' action and call
 * 'aux_theme_remove_menu('menu-1)' in the child theme.
 */
add_action("after_setup_theme", function() {
  // Register all theme supports and nav menus with Wordpress
  \WP_AUX::theme()->setup();

  // Check for theme updates
  \WP_AUX::theme()->checkVersions();
});

/**
 * Load stylesheet for customizing the WP admin interface. aux-wp-admin-style.css is for styling
 * places outside of the editor interface. For example, this could be used to style the wp-admin
 * sidebar, the admin dashboard or admin setting pages.
 *
 * Using get_parent_theme_file_(path/uri) to prevent overriding by a child theme.
 * If a child theme needs to customize the editor, it should load it's own css file after this one.
 *
 * @since 1.0.0
 */
add_action('admin_head', function() {
  $adminStyles = "css/aux-wp-admin-style.css";
  $adminStylesPath = get_parent_theme_file_path($adminStyles);
  $adminStylesUri = get_parent_theme_file_uri($adminStyles);

  wp_enqueue_style(
    "aux-wp-admin-styles",
    $adminStylesUri,
    [],
    filemtime($adminStylesPath),
    "all"
  );
});

/**
 * Enqueue assets for the Gutenberg UI (i.e. the block sidebar or toolbar).
 *
 * Using get_parent_theme_file_(path/uri) to prevent overriding by a child theme.
 * If a child theme needs to customize the editor, it should load it's own css file after this one.
 *
 * @since 1.0.0
 */
add_action('enqueue_block_editor_assets', function() {
  $gutenbergUiStyles = "css/aux-gutenberg-ui-style.css";
  $gutenbergUiStylesPath = get_parent_theme_file_path($gutenbergUiStyles);
  $gutenbergUiStylesUri = get_parent_theme_file_uri($gutenbergUiStyles);

  wp_enqueue_style(
    'aux-gutenberg-ui-styles',
    $gutenbergUiStylesUri,
    [],
    filemtime($gutenbergUiStylesPath),
    'all'
  );

  HeadService::enqueueLocalScript(
    'aux-icons',
    'js/aux-icons.js',
    [],
    [
      'in_footer' => true,
      'strategy' => 'defer'
    ]
  );
});

/**
 * Provide default support for WordPress theme features.
 *
 * This action has a '0' priority, so that it runs first before the child
 * theme's 'after_setup_theme'. Use an 'after_setup_theme' action in the child
 * theme to remove support for any default supports (not recommended),
 * or to add theme support for others.
 *
 * @Dion - I know you will want to move this to HeadService. Let's talk before you do please.
 * @since 1.0.0
 */
add_action("after_setup_theme", function() {
  $theme = \WP_AUX::theme();
  $theme->supportAutomaticFeedLinks();
  $theme->supportCustomizeSelectiveRefreshWidgets();
  $theme->supportHtml5();
  $theme->supportPostThumbnails();
  $theme->supportTitleTag();

  $theme->addMenu('menu-1', 'Primary');

  // Add support for block styles and editor styles.
  add_theme_support('wp-block-styles');

  // Add support for editor styles.
  add_theme_support('editor-styles');
}, 0);

/**
 * Add Aggie UX styles to the admin interface
 * @since 1.0.0
 */
add_action('enqueue_block_editor_assets', function() {
  $auxVersion = \WP_AUX::getAuxVersion();
  $editorStyles = "css/editor-style.css";
  $editorStylesUri = get_parent_theme_file_uri($editorStyles);
  $filemtime = filemtime(get_parent_theme_file_path($editorStyles));

  /*
    Enqueue editor styles. In Gutenberg, add_editor_style() copies the styles from the specified
    stylesheets into .editor-styles-wrapper. These will be inlined before values defined in theme.json.
    As of August 2025, the WP documentation on this is thin. Better docs at: https://gutenberg.10up.com/reference/Themes/styles/
    Gutenberg loves to cache everything, so we add a cache control version to the urls to force a refresh when update the theme or AUX.
  */
  add_editor_style(array(
    "https://aux.tamu.edu/$auxVersion/styles/aux-styles.css?v=" . \WP_AUX::CACHE_CONTROL_VERSION,
    "$editorStylesUri?v=$filemtime"
  ));
});

/**
 * Perform default 'init' actions for AUX themes
 *
 * Theme styles (style.css) for the parent AUX theme and child (if applicable)
 * are automatically enqueued here. If using a child theme, to remove the parent
 * style (not recommended) provide an 'init' action in the child theme
 * and call `aux_theme_ignore_parent_style()`.
 */
add_action('init', function() {
  \WP_AUX::theme()->init();
});

/**
 * AUX theme utility and shorthand functions
 * This file cannot be overridden by a file of the same name in the child theme.
 */
\WP_AUX::requireThemeFile('inc/functions-theme.php', \WP_AUX::CHILD_THEME_IGNORE);

/**
 * Admin functions, filters, and actions
 * This file cannot be overridden by a file of the same name in the child theme.
 */
\WP_AUX::requireThemeFile('inc/functions-admin.php', \WP_AUX::CHILD_THEME_IGNORE);

/**
 * Disable comments everywhere
 * This file cannot be overridden by a file of the same name in the child theme.
 */
\WP_AUX::requireThemeFile('inc/functions-disable-comments.php', \WP_AUX::CHILD_THEME_IGNORE);

/**
 * Functions that modify items in the <head></head>
 * Most modify the output of the WordPress wp_head() function.
 * This file cannot be overridden by a file of the same name in the child theme.
 */
\WP_AUX::requireThemeFile('inc/functions-html-head.php', \WP_AUX::CHILD_THEME_IGNORE);

/**
 * Functions that affect parts of the front-end that aren't included elsewhere.
 * Ex: body class, breadcrumbs, title, plugin customizations
 * If this file exists in the child theme, it will ALSO be included AFTER this file in the parent theme.
 */
\WP_AUX::requireThemeFile('inc/functions-front-end.php', \WP_AUX::CHILD_THEME_APPEND);

/**
 * Custom template tags for this theme.
 * If this file exists in the child theme, it will ALSO be included BEFORE this file in the parent theme.
 */
\WP_AUX::requireThemeFile('inc/template-tags.php', \WP_AUX::CHILD_THEME_PREPEND);

/**
 * Functions which enhance the theme by hooking into WordPress.
 * If this file exists in the child theme, it will ALSO be included BEFORE this file in the parent theme.
 */
\WP_AUX::requireThemeFile('inc/template-functions.php', \WP_AUX::CHILD_THEME_PREPEND);

/**
 * Customizer additions.
 * If this file exists in the child theme, it will be included INSTEAD OF the parent theme file.
 */
\WP_AUX::requireThemeFile('inc/customizer.php', \WP_AUX::CHILD_THEME_OVERRIDE);

/**
 * Register sidebars and widget areas
 * If this file exists in the child theme, it will ALSO be included AFTER this file in the parent theme.
 */
\WP_AUX::requireThemeFile('inc/register-widget-sidebars.php', \WP_AUX::CHILD_THEME_APPEND);

/**
 * Manage available blocks and other Gutenberg customizations
 * If this file exists in the child theme, it will be included INSTEAD OF the parent theme file.
 */
\WP_AUX::requireThemeFile('inc/functions-gutenberg.php', \WP_AUX::CHILD_THEME_OVERRIDE);

/**
 * Load Jetpack compatibility file.
 * If this file exists in the child theme, it will ALSO be included AFTER this file in the parent theme.
 */
if (defined("JETPACK__VERSION")) {
  \WP_AUX::requireThemeFile('inc/jetpack.php', \WP_AUX::CHILD_THEME_APPEND);
}

/**
 * Custom menu walker
 * If this file exists in the child theme, it will be included INSTEAD OF the parent theme file.
 */
\WP_AUX::requireThemeFile('template-parts/walker.php', \WP_AUX::CHILD_THEME_OVERRIDE);

/**
 * Customize sizes and other options for images
 * If this file exists in the child theme, it will ALSO be included AFTER this file in the parent theme.
 */
\WP_AUX::requireThemeFile('inc/functions-images.php', \WP_AUX::CHILD_THEME_APPEND);

/**
 * Customize the WordPress API.
 * If this file exists in the child theme, it will ALSO be included AFTER this file in the parent theme.
 */
\WP_AUX::requireThemeFile('inc/functions-wp-api.php', \WP_AUX::CHILD_THEME_APPEND);

/**
 * Customize the WordPress login screen. Only load on wp-login.php.
 * If this file exists in the child theme, it will ALSO be included AFTER this file in the parent theme.
 */
$is_login_page = (isset($GLOBALS['pagenow']) && $GLOBALS['pagenow'] === 'wp-login.php');
if ($is_login_page) {
  \WP_AUX::requireThemeFile('inc/functions-login-screen.php', \WP_AUX::CHILD_THEME_APPEND);
}

\WP_AUX::registerFiltersAndActions();

// Removes paragraph tags from category description
remove_filter('term_description','wpautop');
