<?php

/*
 * Plugin Name:       RefineURL
 * Plugin URI:        https://wordpress.org/plugins/refineurl
 * Description:       Allows you to change and redirect different URLs of your WordPress website.
 * Version:           1.1.10
 * Requires at least: 5.2
 * Requires PHP:      7.2
 * Author:            Asadullah Galib
 * License:           GPL v2 or later
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain:       refineurl
 * Domain Path:       /languages
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
if ( function_exists( 'refine_fs' ) ) {
    refine_fs()->set_basename( false, __FILE__ );
} else {
    if ( !function_exists( 'refine_fs' ) ) {
        // Create a helper function for easy SDK access.
        function refine_fs() {
            global $refine_fs;
            if ( !isset( $refine_fs ) ) {
                // Activate multisite network integration.
                if ( !defined( 'WP_FS__PRODUCT_18843_MULTISITE' ) ) {
                    define( 'WP_FS__PRODUCT_18843_MULTISITE', true );
                }
                // Include Freemius SDK.
                require_once dirname( __FILE__ ) . '/vendor/freemius/start.php';
                $refine_fs = fs_dynamic_init( array(
                    'id'              => '18843',
                    'slug'            => 'refineurl',
                    'type'            => 'plugin',
                    'public_key'      => 'pk_23ed0b1ca385a8a805d0eb14affc5',
                    'is_premium'      => false,
                    'premium_suffix'  => 'Premium',
                    'has_addons'      => false,
                    'has_paid_plans'  => true,
                    'has_affiliation' => 'selected',
                    'menu'            => array(
                        'slug'        => 'refineurl',
                        'first-path'  => '',
                        'support'     => false,
                        'contact'     => false,
                        'affiliation' => false,
                    ),
                    'is_live'         => true,
                ) );
            }
            return $refine_fs;
        }

        // Init Freemius.
        refine_fs();
        // Signal that SDK was initiated.
        do_action( 'refine_fs_loaded' );
    }
    // The key prefix Upper-case: SAPRFURL, lower-case: saprfurl
    // Define constants
    define( 'SAPRFURL_VERSION', '0.0.1' );
    define( 'SAPRFURL_ASSETS', plugin_dir_url( __FILE__ ) . 'assets/' );
    define( 'SAPRFURL_TEMPLATES', plugin_dir_path( __FILE__ ) . 'templates/' );
    // Enqueue CSS and JS files
    function saprfurl_enqueue_admin_assets() {
        // Enqueue CSS file
        wp_enqueue_style(
            'saprfurl-admin-style',
            SAPRFURL_ASSETS . 'css/admin-style.css',
            [],
            SAPRFURL_VERSION,
            'all'
        );
        // Enqueue JavaScript file
        wp_enqueue_script(
            'saprfurl-admin-script',
            SAPRFURL_ASSETS . 'js/admin-main-script.js',
            ['jquery'],
            SAPRFURL_VERSION,
            true
        );
    }

    add_action( 'admin_enqueue_scripts', 'saprfurl_enqueue_admin_assets' );
    // Include all the template file here
    $sapmrfurl_templates = [
        'all-hooks.php',
        // For all relevant hooks
        'dactivation.php',
        // For removing all the options
        'advanced-tools.php',
    ];
    foreach ( $sapmrfurl_templates as $template ) {
        $template_path = SAPRFURL_TEMPLATES . $template;
        if ( file_exists( $template_path ) ) {
            require_once $template_path;
        }
    }
    // Register the plugin menu in the admin sidebar
    function saprfurl_register_admin_menu() {
        $capability = 'manage_options';
        $parent_slug = 'refineurl';
        // Main menu starts here
        add_menu_page(
            esc_html__( 'RefineURL', 'refineurl' ),
            esc_html__( 'RefineURL', 'refineurl' ),
            $capability,
            $parent_slug,
            'saprfurl_url_change_page',
            'dashicons-editor-unlink',
            20
        );
        // Submenu starts here
        add_submenu_page(
            $parent_slug,
            esc_html__( 'Login Setup', 'refineurl' ),
            esc_html__( 'Login Setup', 'refineurl' ),
            $capability,
            $parent_slug,
            'saprfurl_url_change_page'
        );
        add_submenu_page(
            $parent_slug,
            esc_html__( 'Settings', 'refineurl' ),
            esc_html__( 'Settings', 'refineurl' ),
            $capability,
            'saprfurl-settings',
            'saprfurl_settings_page'
        );
        add_submenu_page(
            $parent_slug,
            esc_html__( 'Support', 'refineurl' ),
            esc_html__( 'Support', 'refineurl' ),
            $capability,
            'saprfurl-support',
            '__return_null'
        );
        add_submenu_page(
            $parent_slug,
            esc_html__( 'Advanced Tools', 'refineurl' ),
            esc_html__( 'Advanced Tools', 'refineurl' ),
            $capability,
            $parent_slug . '-more-tools',
            'saprfurl_advanced_tools'
        );
    }

    add_action( 'admin_menu', 'saprfurl_register_admin_menu' );
}
// Plugin login setup page
function saprfurl_url_change_page() {
    $saprfurl_login_setup_template = SAPRFURL_TEMPLATES . 'login-setup.php';
    if ( file_exists( $saprfurl_login_setup_template ) ) {
        include $saprfurl_login_setup_template;
    } else {
        ?>
        <div class="notice notice-warning is-dismissible">
            <h2><?php 
        echo esc_html__( 'Login setup page not found!', 'refineurl' );
        ?></h2>
        </div>
    <?php 
    }
}

// Retrieve the option value for hide only toggle
function saprfurl_get_hide_login_page() {
    return get_option( 'saprfurl_hide_login_page', 1 );
}

// Retrieve the option value for hide and redirect toggle
function saprfurl_get_hide_redirect_page() {
    return get_option( 'saprfurl_hide_redirect_page', 1 );
}

// Restrict wp-admin and wp-login.php
function saprfurl_restrict_wp_admin_and_login() {
    if ( !is_user_logged_in() ) {
        if ( isset( $_SERVER['REQUEST_URI'] ) ) {
            // Unslash and sanitize REQUEST_URI
            $saprfurl_request_uri = esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) );
            if ( strpos( $saprfurl_request_uri, 'wp-admin' ) !== false || strpos( $saprfurl_request_uri, 'wp-login.php' ) !== false ) {
                // Get the user input from the settings.php
                $saprfurl_custom_redirect_extension = get_option( 'saprfurl_custom_redirect', '404' );
                $saprfurl_custom_redirect_extension = sanitize_text_field( $saprfurl_custom_redirect_extension );
                $saprfurl_custom_redirect_extension = str_replace( ' ', '', $saprfurl_custom_redirect_extension );
                // Apply redirection
                $redirect_url = home_url( "/" . $saprfurl_custom_redirect_extension );
                wp_redirect( $redirect_url );
                exit;
            }
        }
    }
}

// Conditionally restrict access if setting is enabled
if ( saprfurl_get_hide_login_page() ) {
    add_action( 'init', 'saprfurl_restrict_wp_admin_and_login' );
} elseif ( saprfurl_get_hide_redirect_page() ) {
    add_action( 'init', 'saprfurl_restrict_wp_admin_and_login' );
}
// Plugin settings page
function saprfurl_settings_page() {
    $saprfurl_settings_template = SAPRFURL_TEMPLATES . 'settings.php';
    if ( file_exists( $saprfurl_settings_template ) ) {
        include $saprfurl_settings_template;
    } else {
        ?>
        <div class="notice notice-warning is-dismissible">
            <h2><?php 
        echo esc_html__( 'Settings page not found!', 'refineurl' );
        ?></h2>
        </div>
    <?php 
    }
}

// Add support link to sapwp support page
add_action( 'admin_print_footer_scripts', 'saprfurl_modify_support_link' );
function saprfurl_modify_support_link() {
    ?>
    <script type="text/javascript">
        (function() {
            const replacements = [{
                oldHref: 'admin.php?page=saprfurl-support',
                newHref: 'https://sapwp.com/support/'
            }, ];

            function updateLinks() {
                replacements.forEach(item => {
                    const link = document.querySelector(`a[href="${item.oldHref}"]`);
                    if (link) {
                        link.href = item.newHref;
                        link.target = '_blank';
                    }
                });
            }

            // Initial attempt
            updateLinks();

            // Observe DOM changes
            const observer = new MutationObserver(updateLinks);
            observer.observe(document.body, {
                childList: true,
                subtree: true
            });
        })();
    </script>
<?php 
}

// Register open link in new tab
add_action( 'admin_init', 'saprfurl_register_settings' );
function saprfurl_register_settings() {
    register_setting( 'saprfurl_settings_group', 'saprfurl_internal_link', array(
        'sanitize_callback' => 'sanitize_text_field',
    ) );
    register_setting( 'saprfurl_settings_group', 'saprfurl_external_link', array(
        'sanitize_callback' => 'sanitize_text_field',
    ) );
}

add_filter( 'the_content', 'saprfurl_modify_links_target' );
function saprfurl_modify_links_target(  $content  ) {
    $enable_internal = get_option( 'saprfurl_internal_link' );
    $enable_external = get_option( 'saprfurl_external_link' );
    $internal_follow = get_option( 'saprfurl_internal_follow', 'follow' );
    $external_follow = get_option( 'saprfurl_external_follow', 'follow' );
    if ( !$enable_internal && !$enable_external || trim( $content ) === '' ) {
        return $content;
    }
    $site_url = home_url();
    libxml_use_internal_errors( true );
    $doc = new DOMDocument();
    $encoded_content = mb_convert_encoding( $content, 'HTML-ENTITIES', 'UTF-8' );
    if ( trim( $encoded_content ) === '' ) {
        return $content;
    }
    // Load content without adding extra <html>/<body> tags
    $doc->loadHTML( '<?xml encoding="UTF-8">' . $encoded_content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD );
    $links = $doc->getElementsByTagName( 'a' );
    foreach ( $links as $link ) {
        $href = $link->getAttribute( 'href' );
        if ( !$href || preg_match( '/^(#|mailto:|tel:)/i', $href ) ) {
            continue;
        }
        $is_internal = strpos( $href, $site_url ) === 0 || !preg_match( '#^https?://#', $href ) && strpos( $href, '/' ) === 0;
        // Skip modifying if not enabled
        if ( $is_internal && !$enable_internal || !$is_internal && !$enable_external ) {
            continue;
        }
        // Always set target="_blank" for enabled
        $link->setAttribute( 'target', '_blank' );
        // Handle rel attribute
        $follow_setting = ( $is_internal ? $internal_follow : $external_follow );
        $existing_rel = $link->getAttribute( 'rel' );
        $rel_parts = array_filter( array_map( 'trim', explode( ' ', $existing_rel ) ) );
        // Remove 'nofollow' if it exists
        $rel_parts = array_diff( $rel_parts, ['nofollow'] );
        // Add 'nofollow' if selected
        if ( $follow_setting === 'nofollow' ) {
            $rel_parts[] = 'nofollow';
        }
        // Set the new rel attribute if needed
        if ( !empty( $rel_parts ) ) {
            $link->setAttribute( 'rel', implode( ' ', array_unique( $rel_parts ) ) );
        } else {
            $link->removeAttribute( 'rel' );
        }
    }
    return $doc->saveHTML();
}

add_filter(
    'login_redirect',
    'saprfurl_custom_login_redirect',
    10,
    3
);
function saprfurl_custom_login_redirect(  $redirect_to, $request, $user  ) {
    // Only redirect if the user is a valid WP_User object and logged in
    if ( is_a( $user, 'WP_User' ) && $user->exists() ) {
        $saprfurl_custom_redirect = get_option( 'saprfurl_user_redirect_url_after_login', '' );
        if ( !empty( $saprfurl_custom_redirect ) ) {
            return esc_url_raw( $saprfurl_custom_redirect );
        }
    }
    // Fallback to default behavior
    return $redirect_to;
}
