<?php

namespace WPUF\UserDirectory;

/**
 * Pretty URLs handler for User Directory
 * Supports pretty URLs on any page containing a directory block
 *
 * @since 4.2.0
 * @package WPUF_Pro
 */
class PrettyUrls {

    /**
     * Constructor
     *
     * @since 4.2.0
     */
    public function __construct() {
        // Use high priority (5) to ensure WPUF rewrite rules are added before other plugins
        add_action( 'init', [ $this, 'add_rewrite_rules' ], 5 );
        add_action( 'init', [ $this, 'add_shortcode_rewrite_rules' ], 5 );
        add_filter( 'query_vars', [ $this, 'add_query_vars' ] );
        add_action( 'template_redirect', [ $this, 'handle_pretty_urls' ] );
        add_action( 'save_post', [ $this, 'flush_rewrite_rules_on_save' ] );
    }

    /**
     * Add rewrite rules for user profiles on any page with directory block
     *
     * @since 4.2.0
     */
    public function add_rewrite_rules() {
        // Get all pages that contain directory blocks
        $directory_pages = $this->get_pages_with_directory_blocks();

        foreach ( $directory_pages as $page ) {
            $page_slug = $page->post_name;

            // Add rewrite rule for user profiles: /page-slug/username/
            // Use 'top' priority to ensure WPUF rules take precedence over other plugins
            add_rewrite_rule(
                '^' . $page_slug . '/([^/]+)/?$',
                'index.php?pagename=' . $page_slug . '&wpuf_user_profile=$matches[1]',
                'top'
            );
        }
    }

    /**
     * Add rewrite rules for shortcode-based directory pages
     *
     * @since 4.2.0
     */
    public function add_shortcode_rewrite_rules() {
        // Get all pages that contain directory shortcodes
        $args = [
            'post_type'      => 'page',
            'post_status'    => 'publish',
            'posts_per_page' => -1,
        ];

        $all_pages = get_posts( $args );

        foreach ( $all_pages as $page ) {
            // Check if page has directory shortcode
            if ( has_shortcode( $page->post_content, 'wpuf_user_listing' ) ||
                 has_shortcode( $page->post_content, 'wpuf_user_listing_id' ) ) {

                $page_slug = $page->post_name;

                // Add rewrite rule for user profiles: /page-slug/username/ or /page-slug/123/
                // Use 'top' priority to ensure WPUF rules take precedence over other plugins
                add_rewrite_rule(
                    '^' . $page_slug . '/([^/]+)/?$',
                    'index.php?pagename=' . $page_slug . '&wpuf_user_profile=$matches[1]',
                    'top'
                );
            }
        }
    }

    /**
     * Get all pages that contain directory blocks
     *
     * @since 4.2.0
     *
     * @return array Array of post objects
     */
    private function get_pages_with_directory_blocks() {
        $args = [
            'post_type'      => 'page',
            'post_status'    => 'publish',
            'posts_per_page' => -1,
            'meta_query'     => [
                [
                    'key'     => '_wpuf_has_directory_block',
                    'value'   => '1',
                    'compare' => '='
                ]
            ]
        ];

        $pages = get_posts( $args );

        // Fallback: if no meta query results, check post content directly
        if ( empty( $pages ) ) {
            $args = [
                'post_type'      => 'page',
                'post_status'    => 'publish',
                'posts_per_page' => -1,
            ];

            $all_pages = get_posts( $args );
            $pages = [];

            foreach ( $all_pages as $page ) {
                if ( strpos( $page->post_content, 'wp:wpuf-ud/directory' ) !== false ) {
                    $pages[] = $page;
                }
            }
        }

        return $pages;
    }

    /**
     * Add custom query vars
     *
     * @since 4.2.0
     *
     * @param array $vars Existing query vars
     * @return array Modified query vars
     */
    public function add_query_vars( $vars ) {
        $vars[] = 'wpuf_user_profile';
        return $vars;
    }

    /**
     * Handle pretty URL requests
     *
     * @since 4.2.0
     */
    public function handle_pretty_urls() {
        $user_identifier = get_query_var( 'wpuf_user_profile' );

        if ( $user_identifier ) {
            // Decode URL-encoded characters (like %20 for spaces)
            $user_identifier = urldecode( $user_identifier );

            // Set the user parameter for existing profile detection logic
            $_GET['user'] = $user_identifier;
        }
    }

    /**
     * Flush rewrite rules when a page is saved
     * This ensures new pages with directory blocks get proper rewrite rules
     *
     * @since 4.2.0
     *
     * @param int $post_id Post ID
     */
    public function flush_rewrite_rules_on_save( $post_id ) {
        // Only process pages
        if ( get_post_type( $post_id ) !== 'page' ) {
            return;
        }

        $post = get_post( $post_id );
        if ( ! $post ) {
            return;
        }

        // Check if this page has a directory block
        $has_directory_block = strpos( $post->post_content, 'wp:wpuf-ud/directory' ) !== false;

        // Update meta to track pages with directory blocks
        if ( $has_directory_block ) {
            update_post_meta( $post_id, '_wpuf_has_directory_block', '1' );
        } else {
            delete_post_meta( $post_id, '_wpuf_has_directory_block' );
        }

        // Flush rewrite rules to update the rules
        flush_rewrite_rules();
    }

    /**
     * Generate pretty URL for user profile
     *
     * @since 4.2.0
     *
     * @param string $username Username
     * @param string $base_url Base URL (optional)
     * @return string Pretty URL
     */
    public static function generate_profile_url( $username, $base_url = '' ) {
        if ( empty( $base_url ) ) {
            global $post;
            if ( $post ) {
                $base_url = get_permalink( $post->ID );
            } else {
                $base_url = home_url();
            }
        }

        // Clean up the base URL: remove trailing slash and any query parameters
        $base_url = rtrim( $base_url, '/' );
        if ( strpos( $base_url, '?' ) !== false ) {
            $base_url = strtok( $base_url, '?' );
        }

        // URL encode the username to handle special characters and spaces
        $username = rawurlencode( $username );

        return trailingslashit( $base_url ) . $username . '/';
    }

    /**
     * Check if current request is a pretty URL profile request
     *
     * @since 4.2.0
     *
     * @return bool
     */
    public static function is_pretty_profile_url() {
        return ! empty( get_query_var( 'wpuf_user_profile' ) );
    }

    /**
     * Check if current page supports pretty URLs (has directory block)
     *
     * @since 4.2.0
     *
     * @return bool
     */
    public static function current_page_supports_pretty_urls() {
        global $post;

        if ( ! $post ) {
            return false;
        }

        return strpos( $post->post_content, 'wp:wpuf-ud/directory' ) !== false;
    }
}
