<?php
/**
 * Helpers for determining translation scan targets.
 *
 * @package WPR_Translate
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Determine paths to scan for gettext files.
 *
 * @return array
 */
function wpr_translate_admin_get_scan_targets() {
    // Start with an empty target list.
    $targets = array();

    // Add the active theme (and parent) to scan targets.
    $theme = wp_get_theme();

    if ( $theme instanceof WP_Theme ) {
        $child_path = $theme->get_stylesheet_directory();
        $template   = $theme->get_template_directory();
        $child_slug = $theme->get_stylesheet();

        // Locate the child theme languages directory.
        $child_languages = wpr_translate_admin_locate_languages_directory( $child_path );

        if ( is_string( $child_path ) && is_dir( $child_path ) && '' !== $child_languages ) {
            $targets[] = array(
                'context' => 'theme:' . sanitize_title( $child_slug ),
                'path'    => $child_path,
                'languages_path' => $child_languages,
                'domain'  => wpr_translate_admin_get_theme_domain( $theme ),
            );
        }

        // Include the parent theme when available.
        if ( method_exists( $theme, 'parent' ) ) {
            $parent = $theme->parent();

            if ( $parent instanceof WP_Theme ) {
                $parent_path = $parent->get_template_directory();

                $parent_languages = wpr_translate_admin_locate_languages_directory( $parent_path );

                if ( is_string( $parent_path ) && is_dir( $parent_path ) && '' !== $parent_languages ) {
                    $normalized_parent = realpath( $parent_path );
                    $normalized_child  = is_string( $child_path ) ? realpath( $child_path ) : false;

                    // Avoid duplicating child and parent paths.
                    if ( $normalized_parent && $normalized_parent !== $normalized_child ) {
                        $targets[] = array(
                            'context' => 'theme:' . sanitize_title( $parent->get_template() ),
                            'path'    => $parent_path,
                            'languages_path' => $parent_languages,
                            'domain'  => wpr_translate_admin_get_theme_domain( $parent ),
                        );
                    }
                }
            }
        } elseif ( is_string( $template ) && is_dir( $template ) && $template !== $child_path ) {
            // Fallback for classic theme setups without a parent theme.
            $template_languages = wpr_translate_admin_locate_languages_directory( $template );

            if ( '' !== $template_languages ) {
                $targets[] = array(
                    'context' => 'theme:' . sanitize_title( basename( $template ) ),
                    'path'    => $template,
                    'languages_path' => $template_languages,
                    'domain'  => wpr_translate_admin_get_theme_domain( $theme ),
                );
            }
        }
    }

    // Collect active plugin directories to scan.
    $active_plugins = (array) get_option( 'active_plugins', array() );

    if ( is_multisite() ) {
        // Merge network-activated plugins for multisite installs.
        $network_plugins = (array) get_site_option( 'active_sitewide_plugins', array() );
        $active_plugins  = array_unique( array_merge( $active_plugins, array_keys( $network_plugins ) ) );
    }

    foreach ( $active_plugins as $plugin_file ) {
        $plugin_file = (string) $plugin_file;

        if ( '' === $plugin_file ) {
            continue;
        }

        // Resolve the plugin file path for validation.
        $plugin_path = trailingslashit( WP_PLUGIN_DIR ) . $plugin_file;

        if ( ! file_exists( $plugin_path ) ) {
            continue;
        }

        $plugin_dir = dirname( $plugin_file );

        if ( '' === $plugin_dir || '.' === $plugin_dir ) {
            // Skip single-file plugins to avoid scanning unrelated language directories.
            continue;
        }

        $scan_path = trailingslashit( WP_PLUGIN_DIR ) . trailingslashit( $plugin_dir );

        if ( ! is_dir( $scan_path ) ) {
            continue;
        }

        $slug = basename( $plugin_dir );

        if ( '' === $slug ) {
            $slug = $plugin_dir;
        }

        // Locate the plugin languages directory.
        $plugin_languages = wpr_translate_admin_locate_languages_directory( $scan_path );

        if ( '' === $plugin_languages ) {
            continue;
        }

        $targets[] = array(
            'context' => 'plugin:' . sanitize_title( $slug ),
            'path'    => untrailingslashit( $scan_path ),
            'languages_path' => $plugin_languages,
            'domain'  => wpr_translate_admin_get_plugin_domain( $plugin_file, $slug ),
        );
    }

    return $targets;
}

/**
 * Determine the text domain for a theme.
 *
 * @param WP_Theme $theme Theme instance.
 *
 * @return string
 */
function wpr_translate_admin_get_theme_domain( $theme ) {
    // Ensure the theme object is valid.
    if ( ! $theme instanceof WP_Theme ) {
        return '';
    }

    // Prefer the explicit theme text domain.
    $domain = trim( (string) $theme->get( 'TextDomain' ) );

    if ( '' !== $domain ) {
        return $domain;
    }

    // Fallback to the parent theme when present.
    if ( method_exists( $theme, 'parent' ) ) {
        $parent = $theme->parent();

        if ( $parent instanceof WP_Theme ) {
            $parent_domain = trim( (string) $parent->get( 'TextDomain' ) );

            if ( '' !== $parent_domain ) {
                return $parent_domain;
            }

            $parent_stylesheet = trim( (string) $parent->get_stylesheet() );

            if ( '' !== $parent_stylesheet ) {
                return $parent_stylesheet;
            }

            $parent_template = trim( (string) $parent->get_template() );

            if ( '' !== $parent_template ) {
                return $parent_template;
            }
        }
    }

    $stylesheet = trim( (string) $theme->get_stylesheet() );

    if ( '' !== $stylesheet ) {
        return $stylesheet;
    }

    $template = trim( (string) $theme->get_template() );

    if ( '' !== $template ) {
        return $template;
    }

    return '';
}

/**
 * Determine the text domain for a plugin directory.
 *
 * @param string $plugin_file Plugin file relative to WP_PLUGIN_DIR.
 * @param string $fallback    Fallback slug when the header has no text domain.
 *
 * @return string
 */
function wpr_translate_admin_get_plugin_domain( $plugin_file, $fallback ) {
    // Resolve the plugin's absolute path for header inspection.
    $plugin_path = trailingslashit( WP_PLUGIN_DIR ) . $plugin_file;

    if ( file_exists( $plugin_path ) ) {
        if ( ! function_exists( 'get_plugin_data' ) ) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }

        $data = get_plugin_data( $plugin_path, false, false );

        if ( isset( $data['TextDomain'] ) && '' !== trim( $data['TextDomain'] ) ) {
            return trim( $data['TextDomain'] );
        }
    }

    // Fallback to the plugin directory slug.
    $slug = basename( dirname( $plugin_file ) );

    if ( '' !== $slug && '.' !== $slug ) {
        return $slug;
    }

    // Fallback to the provided slug or file name.
    $fallback = trim( (string) $fallback );

    if ( '' !== $fallback ) {
        return $fallback;
    }

    return basename( $plugin_file, '.php' );
}

/**
 * Locate a readable languages directory for a scan target.
 *
 * @param string $path Base directory for the target.
 *
 * @return string
 */
function wpr_translate_admin_locate_languages_directory( $path ) {
    // Validate the base path before resolving /languages.
    if ( '' === $path || ! is_string( $path ) || ! is_dir( $path ) ) {
        return '';
    }

    // Use the standard /languages directory path.
    $languages_path = trailingslashit( $path ) . 'languages';

    if ( ! is_dir( $languages_path ) || ! is_readable( $languages_path ) ) {
        return '';
    }

    return $languages_path;
}
