<?php
/**
 * @package BuddyBoss Child
 * The parent theme functions are located at /buddyboss-theme/inc/theme/functions.php
 * Add your own functions at the bottom of this file.
 */


/****************************** THEME SETUP ******************************/

/**
 * Sets up theme for translation
 *
 * @since BuddyBoss Child 1.0.0
 */
function buddyboss_theme_child_languages()
{
  /**
   * Makes child theme available for translation.
   * Translations can be added into the /languages/ directory.
   */

  // Translate text from the PARENT theme.
  load_theme_textdomain( 'buddyboss-theme', get_stylesheet_directory() . '/languages' );

  // Translate text from the CHILD theme only.
  // Change 'buddyboss-theme' instances in all child theme files to 'buddyboss-theme-child'.
  // load_theme_textdomain( 'buddyboss-theme-child', get_stylesheet_directory() . '/languages' );

}
add_action( 'after_setup_theme', 'buddyboss_theme_child_languages' );

/**
 * Enqueues scripts and styles for child theme front-end.
 *
 * @since Boss Child Theme  1.0.0
 */
function buddyboss_theme_child_scripts_styles()
{
  /**
   * Scripts and Styles loaded by the parent theme can be unloaded if needed
   * using wp_deregister_script or wp_deregister_style.
   *
   * See the WordPress Codex for more information about those functions:
   * http://codex.wordpress.org/Function_Reference/wp_deregister_script
   * http://codex.wordpress.org/Function_Reference/wp_deregister_style
   **/

  // Styles
  wp_enqueue_style( 'buddyboss-child-css', get_stylesheet_directory_uri().'/assets/css/custom.css' );

  // Javascript
  wp_enqueue_script( 'buddyboss-child-js', get_stylesheet_directory_uri().'/assets/js/custom.js' );
}
add_action( 'wp_enqueue_scripts', 'buddyboss_theme_child_scripts_styles', 9999 );


/****************************** CUSTOM FUNCTIONS ******************************/

// Add your own custom functions here

// Bypass BuddyBoss Private Network for blog posts
function bypass_private_network_for_blog() {
    // Check if we're on a blog-related page (posts, archives, categories, tags)
    if ( ! is_user_logged_in() ) {
        if ( is_single() && get_post_type() === 'post' ) {
            return true; // Single blog post
        }
        if ( is_home() || is_archive() || is_category() || is_tag() || is_author() || is_date() || is_search() ) {
            return true; // Blog index, archives, categories, tags, author pages, date archives, search
        }
    }
    return false;
}

// Remove Private Network restriction for blog posts
add_action( 'bp_template_redirect', function() {
    if ( bypass_private_network_for_blog() ) {
        // Remove the private network redirect for blog pages
        remove_action( 'bp_template_redirect', 'bp_private_network_template_redirect', 10 );
    }
}, 5 ); // Run before priority 10 where bp_private_network_template_redirect runs

//add webp support
function enable_webp_upload( $upload_mimes ) {
    $upload_mimes['webp'] = 'image/webp';
    return $upload_mimes;
}
add_filter( 'upload_mimes', 'enable_webp_upload', 10, 1 );

// custom login register
// Custom login/register function with alignment option
function bw_display_login_register_links($atts) {
    // Set default alignment to left
    $atts = shortcode_atts(
        array(
            'align' => 'left',
        ),
        $atts,
        'bw_login_register_links'
    );

    // Determine the CSS based on alignment
    $alignment_css = '';
    if ($atts['align'] === 'center') {
        $alignment_css = 'text-align: center;';
    } elseif ($atts['align'] === 'right') {
        $alignment_css = 'text-align: right;';
    } else {
        $alignment_css = 'text-align: left;';
    }

    if (!is_user_logged_in()) {
        return '<div style="' . esc_attr($alignment_css) . '">' .
                   '<div style="display: inline-flex; gap: 10px;">' .
                       '<a href="' . wp_login_url() . '" class="button secondary">Sign in</a>' .
                       '<a href="' . wp_registration_url() . '" class="button primary">Apply for an account</a>' .
                   '</div>' .
               '</div>';
    } else {
        $current_user = wp_get_current_user();
        $profile_url = home_url('/members/' . $current_user->user_nicename . '/');
        return '<div style="' . esc_attr($alignment_css) . '">' .
                   '<p>You are logged in as <a href="' . esc_url($profile_url) . '">' . esc_html($current_user->display_name) . '</a>.</p>' .
               '</div>';
    }
}
add_shortcode('bw_login_register_links', 'bw_display_login_register_links');

// hide blog posts for non logged in users
/*
function bw_restrict_full_post_content($content) {
    if (is_single() && !is_user_logged_in()) {
        // Display a message prompting users to log in
        $restricted_message = '<p>This content is only available to logged-in users. Please <a href="' . wp_login_url(get_permalink()) . '">log in</a> to view the full content.</a></p>';
        
        // Combine the restricted message with a snippet of the content
        $content = wp_trim_words($content, 40, '...') . $restricted_message; // Adjust 40 to the number of words you want to display
    }
    return $content;
}
add_filter('the_content', 'bw_restrict_full_post_content');
*/
function bw_display_featured_image_before_content($content) {
    if (is_single() && has_post_thumbnail()) {
        $featured_image = get_the_post_thumbnail(null, 'large');
        $content = $featured_image . $content;
    }
    return $content;
}
add_filter('the_content', 'bw_display_featured_image_before_content');

/* Hide blog posts feature start */
function bw_redirect_non_logged_users() {
    if (is_single() && !is_user_logged_in()) {
        wp_redirect(wp_login_url(get_permalink()));
        exit();
    }
}
add_action('template_redirect', 'bw_redirect_non_logged_users');
/* Hide blog posts feature end */

// retrieves the attachment ID from the file URL
function bw_get_image_id ( $image_url ) {
    global $wpdb;
    $attachment = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url ) ); 
    return $attachment[0]; 
}

// forum gender
function bw_filter_forums_by_acf_gender($query) {
    if (!is_admin() && $query->is_main_query() && is_post_type_archive('forum')) {
        if (isset($_GET['forum-gender']) && !empty($_GET['forum-gender'])) {
            $meta_query = array(
                array(
                    'key'     => 'forum_gender', // The ACF field name
                    'value'   => sanitize_text_field($_GET['forum-gender']),
                    'compare' => '=', // Check for exact match
                ),
            );
            $query->set('meta_query', $meta_query);
        }
    }
}
add_action('pre_get_posts', 'bw_filter_forums_by_acf_gender');

// change header aside - sign up button 

function bw_change_signup_button_text( $translated_text, $text, $domain ) {
    // Ensure we target the correct string and domain
    if ( $text == 'Sign up' && $domain == 'buddyboss-theme' ) {
        $translated_text = 'Apply for an account'; // Replace with your desired button text
    }
    return $translated_text;
}
add_filter( 'gettext', 'bw_change_signup_button_text', 20, 3 );

// simplify registration - generate autousername 



add_filter( 'gform_custom_merge_tags', function ( $merge_tags, $form_id, $fields, $element_id ) {

    $merge_tags[] = array(
        'label' => 'User First Name',
        'tag'   => '{user_first_name}'
    );

    $merge_tags[] = array(
        'label' => 'User Last Name',
        'tag'   => '{user_last_name}'
    );

    $merge_tags[] = array(
        'label' => 'User Phone',
        'tag'   => '{user_phone}'
    );

    $merge_tags[] = array(
        'label' => 'User Pronouns',
        'tag'   => '{user_pronouns}'
    );

    $merge_tags[] = array(
        'label' => 'User Biography',
        'tag'   => '{user_bio}'
    );

    return $merge_tags;
}, 10, 4 );

add_filter( 'gform_replace_merge_tags', function ( $text, $form, $entry, $url_encode, $esc_html, $nl2br, $format ) {

    // User First Name
    $merge_tag = '{user_first_name}';
    $field_value = xprofile_get_field_data( 'First Name', get_current_user_id() );
    $text = str_replace( $merge_tag, $field_value ? $field_value : '', $text );

    // User Last Name
    $merge_tag = '{user_last_name}';
    $field_value = xprofile_get_field_data( 'Last Name', get_current_user_id() );
    $text = str_replace( $merge_tag, $field_value ? $field_value : '', $text );

    // User Phone
    $merge_tag = '{user_phone}';
    $field_value = xprofile_get_field_data( 'Phone', get_current_user_id() );
    $text = str_replace( $merge_tag, $field_value ? html_entity_decode( strip_tags( $field_value ) ) : '', $text );

    // User Pronouns
    $merge_tag = '{user_pronouns}';
    $field_value = xprofile_get_field_data( 'Pronouns', get_current_user_id() );
    $text = str_replace( $merge_tag, $field_value ? $field_value : '', $text );

    // User Biography
    $merge_tag = '{user_bio}';
    $field_value = xprofile_get_field_data( 'Bio', get_current_user_id() );
    $text = str_replace( $merge_tag, $field_value ? html_entity_decode( strip_tags( $field_value ) ) : '', $text );

    return $text;
}, 10, 7 );

require_once 'includes/gf-create-post-acf-fix.php';

/* function bw_add_terms_of_service_field() {
    // Get the Terms of Service page ID (set to 10)
    $tos_page_id = 10; // Static ID for the TOS page
    $tos_page = get_post($tos_page_id);
    
    // Get the content and apply filters (e.g., shortcodes)
    if ($tos_page) {
        $tos_content = apply_filters('the_content', $tos_page->post_content);
        ?>
        <div class="tos-container">
            <label for="terms-of-service">Terms of Service</label>
            <div id="terms-of-service" class="tos-scroll">
                <?php echo wp_kses_post($tos_content); // Output sanitized TOS content ?>
            </div>
            <div>
                <input type="checkbox" id="agree-tos" name="agree_tos" required checked>
                <label for="agree-tos">By creating an account you are agreeing to the Terms of Service and Privacy Policy.</label>
            </div>
        </div>
        <?php
    }
}
// Change the hook to place the Terms of Service before the submit button
add_action('bp_before_registration_submit_buttons', 'bw_add_terms_of_service_field'); */

function bw_add_terms_of_service_field() {
    // Get the Terms of Service page ID (set to 10)
    $tos_page_id = 10; // Static ID for the TOS page
    $tos_page = get_post($tos_page_id);
    
    // Get the content and apply filters (e.g., shortcodes)
    if ($tos_page) {
        $tos_content = apply_filters('the_content', $tos_page->post_content);
        ?>
        <div class="tos-container">
            <label for="terms-of-service">Terms of Service</label>
            <div id="terms-of-service" class="tos-scroll">
                <?php echo wp_kses_post($tos_content); // Output sanitized TOS content ?>
            </div>
            <div>
                <input type="checkbox" id="agree-tos" name="agree_tos" required checked>
                <label for="agree-tos">
                    By creating an account you are agreeing to the 
                    <a class="popup-modal-register popup-terms" href="#terms-modal"><u>Terms of Service</u></a>.
                </label>
            </div>
        </div>

        <!-- BuddyBoss Modal for Terms of Service -->
        <div id="terms-modal" class="registration-popup bb-modal mfp-hide">
            <h1><?php echo esc_html($tos_page->post_title); ?></h1>
            <?php echo wp_kses_post($tos_content); // Output sanitized TOS content ?>
            <button title="Close (Esc)" type="button" class="mfp-close">×</button>
        </div>
        <?php
    }
}
// Change the hook to place the Terms of Service before the submit button
add_action('bp_before_registration_submit_buttons', 'bw_add_terms_of_service_field');


// Language Switcher for non logged in users
function bw_add_language_bar_to_menu($items, $args) {
    if (!is_user_logged_in() && $args->theme_location == 'header-menu-logout') {
        // Prepend or append the language bar directly to the main menu items
        $language_bar = '<li class="menu-item gtranslate-item">' . do_shortcode('[gtranslate]') . '</li>';
        $items .= $language_bar; // Append to the end of menu
        // or use `$items = $language_bar . $items;` to prepend
    }
    return $items;
}
add_filter('wp_nav_menu_items', 'bw_add_language_bar_to_menu', 10, 2);

add_action( 'bp_core_signup_user', function( $user_id ) {
    if ( isset( $_FILES['field_95'] ) && is_uploaded_file( $_FILES['field_95']['tmp_name'] ) && function_exists( 'bp_core_avatar_handle_upload' ) ) {
        // Temporarily set the displayed user ID for the upload
        $original_user_id = bp_displayed_user_id();
        bp_displayed_user_id( $user_id );

        // Handle the avatar upload
        $uploaded_avatar = bp_core_avatar_handle_upload( $_FILES['field_95'], 'bp_core_avatar_upload_dir' );

        // Restore the original user ID
        bp_displayed_user_id( $original_user_id );

        // Check if the upload succeeded
        if ( ! $uploaded_avatar ) {
            error_log( 'Avatar upload failed for user ID: ' . $user_id );
        }
    } else {
        error_log( 'Avatar file not uploaded or invalid for user ID: ' . $user_id );
    }
});




?>