<?php
/**
Plugin Name: SEO Settings
Plugin URI: https://wedevs.com/products/plugins/wp-user-frontend-pro/seo-settings/
Thumbnail Name: wpuf-seo.png
Description: SEO settings for user directory and profiles
Version: 1.0.0
Author: weDevs
Author URI: https://wedevs.com
License: GPL2
 */

// don't call the file directly
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * SEO Settings Module for WP User Frontend PRO
 *
 * @author weDevs <info@wedevs.com>
 */
class WPUF_SEO_Settings {

    /**
     * Constructor
     */
    public function __construct() {
        $this->init_hooks();
    }

    /**
     * Initialize hooks
     */
    private function init_hooks() {
        // Add settings tab (always needed for admin)
        add_filter( 'wpuf_settings_sections', [ $this, 'add_settings_section' ] );
        add_filter( 'wpuf_settings_fields', [ $this, 'add_settings_fields' ] );

        // Add noindex meta tag only on frontend
        if ( ! is_admin() ) {
            add_filter( 'wp_robots', [ $this, 'modify_wp_robots' ] );
        }
    }

    /**
     * Add SEO settings section
     *
     * @param array $sections
     * @return array
     */
    public function add_settings_section( $sections ) {
        // Ensure $sections is an array
        if ( ! is_array( $sections ) ) {
            $sections = [];
        }

        $sections[] = [
            'id'    => 'wpuf_seo_settings',
            'title' => __( 'SEO Settings', 'wpuf-pro' ),
            'icon'  => 'dashicons-search'
        ];

        return $sections;
    }

    /**
     * Add SEO settings fields
     *
     * @param array $fields
     * @return array
     */
    public function add_settings_fields( $fields ) {
        // Ensure $fields is an array
        if ( ! is_array( $fields ) ) {
            $fields = [];
        }

        $seo_fields = [
            // User Directory Section Header
            [
                'name'  => 'user_directory_section',
                'label' => __( 'User Directory SEO Settings', 'wpuf-pro' ),
                'type'  => 'html',
                'class' => 'user-directory-seo-settings',
            ],
        ];

        // Check if WordPress has "Discourage search engines" enabled
        if ( get_option( 'blog_public' ) == '0' ) {
            $seo_fields[] = [
                'name'  => 'wordpress_seo_warning',
                'label' => __( '⚠️ WordPress SEO Warning', 'wpuf-pro' ),
                'type'  => 'html',
                'desc'  => '<div style="background: #fff3cd; border-left: 4px solid #ffb900; padding: 12px; margin: 5px 0;">' .
                           '<p><strong>' . __( 'Warning:', 'wpuf-pro' ) . '</strong> ' . __( 'WordPress is set to "Discourage search engines from indexing this site". This adds noindex to your entire website.', 'wpuf-pro' ) . '</p>' .
                           '<p><a href="' . esc_url( admin_url( 'options-reading.php' ) ) . '" class="button button-primary" target="_blank">' . __( 'Go to Settings → Reading', 'wpuf-pro' ) . '</a> ' . __( 'to change this.', 'wpuf-pro' ) . '</p>' .
                           '</div>',
                'class' => 'wordpress-seo-warning',
            ];
        }

        $seo_fields[] = [
            'name'    => 'avoid_indexing_profiles',
            'label'   => __( 'Avoid indexing profile by search engines', 'wpuf-pro' ),
            'desc'    => __( 'Enable this to add a noindex meta tag to all user profile pages across directories. Useful if you want some profiles hidden from search engines.', 'wpuf-pro' ),
            'type'    => 'checkbox',
            'default' => 'off',
            'class'   => 'user-directory-seo-settings-option',
        ];

        $fields['wpuf_seo_settings'] = apply_filters( 'wpuf_seo_settings_fields', $seo_fields );

        return $fields;
    }

    /**
     * Modify WordPress robots meta tag for user profile pages
     *
     * @param array $robots
     * @return array
     */
    public function modify_wp_robots( $robots ) {
        // Get settings
        $seo_settings = get_option( 'wpuf_seo_settings', [] );

        // Check if noindex is enabled
        $is_enabled = isset( $seo_settings['avoid_indexing_profiles'] ) &&
                     in_array( $seo_settings['avoid_indexing_profiles'], ['on', 'yes'], true );

        // Only modify if enabled and on user profile page
        if ( $is_enabled && $this->is_user_profile_page() ) {
            // Override WordPress robots with our noindex
            return [
                'noindex'  => true,
                'nofollow' => true,
            ];
        }

        return $robots;
    }

    /**
     * Check if current page is a user profile page
     *
     * @return bool
     */
    private function is_user_profile_page() {
        // Check URL parameters first - if they exist, we might be on a profile page regardless of page type
        $has_user_params = ! empty( $_GET['user_id'] ) ||
                          ! empty( $_GET['user'] ) ||
                          ! empty( $_GET['username'] ) ||
                          ! empty( $_GET['id'] );

        // If we have user parameters, continue checking even if not singular
        if ( ! is_singular() && ! $has_user_params ) {
            return false;
        }

        global $post;

        // Check if page contains user directory shortcodes
        if ( $post ) {
            $has_shortcode = has_shortcode( $post->post_content, 'wpuf_user_listing' ) ||
                            has_shortcode( $post->post_content, 'wpuf_user_listing_id' );

            if ( $has_shortcode ) {
                // Check if viewing a specific user profile via URL parameters
                if ( ! empty( $_GET['user_id'] ) ) {
                    return true;
                }

                if ( ! empty( $_GET['user'] ) ) {
                    return true;
                }

                if ( ! empty( $_GET['username'] ) ) {
                    return true;
                }

                // Legacy parameter support
                if ( ! empty( $_GET['id'] ) ) {
                    return true;
                }
            }

            // Check for Gutenberg blocks
            if ( function_exists( 'has_block' ) ) {
                $has_block = has_block( 'wpuf/user-listing', $post ) || has_block( 'wpuf/user-directory', $post );

                if ( $has_block ) {
                    // Check same URL parameters for blocks
                    if ( ! empty( $_GET['user_id'] ) ||
                         ! empty( $_GET['user'] ) ||
                         ! empty( $_GET['username'] ) ||
                         ! empty( $_GET['id'] ) ) {
                        return true;
                    }
                }
            }
        }

        // Check for pretty URLs if rewrite module is active
        $wpuf_user_profile = get_query_var( 'wpuf_user_profile' );
        if ( $wpuf_user_profile ) {
            return true;
        }

        // Legacy check for wpuf_user (kept for backward compatibility)
        $wpuf_user = get_query_var( 'wpuf_user' );
        if ( $wpuf_user ) {
            return true;
        }

        // Allow other plugins/themes to filter the result
        return apply_filters( 'wpuf_seo_is_user_profile_page', false );
    }
}

// Initialize the module
new WPUF_SEO_Settings();