HEX
Server: nginx/1.24.0
System: Linux DGT-WORDPRESS-VM-SERVER 6.14.0-1014-azure #14~24.04.1-Ubuntu SMP Fri Oct 3 20:52:11 UTC 2025 x86_64
User: ubuntu (1000)
PHP: 8.4.12
Disabled: NONE
Upload Files
File: /mnt/data/ifa-wp/wp-content/themes/dreamsrent/functions.php
<?php
 if(defined('DREMSRENT_URL') 	== false) 	define('DREMSRENT_URL', get_template_directory());
 if(defined('DREMSRENT_URI') 	== false) 	define('DREMSRENT_URI', get_template_directory_uri());
 add_action('after_setup_theme', 'dreamsrent_load_textdomain');
function dreamsrent_load_textdomain() {
    load_theme_textdomain('dreamsrent', get_template_directory() . '/languages');
 }    

 
 

            // require libraries, function
            require( DREMSRENT_URL.'/inc/init.php' );

            // Add js, css
            require( DREMSRENT_URL.'/inc/add_js_css.php' );
             // register menu, widget
            require( DREMSRENT_URL.'/inc/register_menu_widget.php' );

            // require menu
            require_once (DREMSRENT_URL.'/inc/dsr_walker_nav_menu.php');

            // require content
            require_once (DREMSRENT_URL.'/templates/blog/define_blocks_content.php');
            
            // require breadcrumbs
            require( DREMSRENT_URL.'/inc/breadcrumbs.php' );

     
            // Require customize
            // if( is_user_logged_in() ){
            //     require( DREMSRENT_URL.'/inc/customize_google_font/customizer_google_font.php' );
            //     require( DREMSRENT_URL.'/inc/customizer.php' );
            // }

            //Redux Functions
            if(in_array('redux-framework/redux-framework.php', apply_filters('active_plugins', get_option('active_plugins'))))
            {
                add_action( 'after_setup_theme', 'dreamsrent_register_redux_sections', 20 );
function dreamsrent_register_redux_sections() {
                require_once ( DREMSRENT_URL.'/inc/options-init.php' );
}
            }
            // Require metabox
  

           

            function dreamsrent_remove_widget_editort() {
                remove_theme_support( 'widgets-block-editor' );
            }
            add_action( 'after_setup_theme', 'dreamsrent_remove_widget_editort' );

        //get options from wp_options for redux
            if( !function_exists('dreamsrent_fl_framework_getoptions') )
            {
                function dreamsrent_fl_framework_getoptions($get_text)
                {
                    global $dreamsrent_theme_options;
                    if(isset($dreamsrent_theme_options[$get_text]) &&  $dreamsrent_theme_options[$get_text] !=""):
                        return $dreamsrent_theme_options[$get_text];
                    else:
                        return false;
                    endif;
                }
            }

            // Remove <p> and <br/> from Contact Form 7
        add_filter('wpcf7_autop_or_not', '__return_false');

 

        //added for password and confirm password
        function enqueue_jquery() {
            wp_enqueue_script('jquery');
        }
        add_action('wp_enqueue_scripts', 'enqueue_jquery');

        require_once ( get_template_directory() . '/inc/typo.php');

        if ( ! function_exists( 'dreamsrent_function_name_given' ) ) :    
            /**     * get the value of view.     */ 
            function dreamsrent_function_name_given($postID) {   
            $count_key = 'wpb_post_views_count';    
            $count = get_post_meta($postID, $count_key, true);    
            if($count ==''){        
            $count = 1;        
            delete_post_meta($postID, $count_key);        
            add_post_meta($postID, $count_key, '1');    
            } else {        
            $count++;        
            update_post_meta($postID, $count_key, $count);    
            }
            }
        endif; 


        // Disable XML-RPC
        add_filter('xmlrpc_enabled', '__return_false');

        // for cart section
        // require_once ( DREMSRENT_URL.'/inc/dsrent-cart.php' );
        // require_once ( DREMSRENT_URL.'/inc/bookings/dreamsrent_booking.php' );

        // add_filter( 'woocommerce_data_stores', 'dreams_woocommerce_data_stores' );

        // function dreams_woocommerce_data_stores( $stores ) {
        //     require_once ( DREMSRENT_URL.'/inc/bookings/class-data-store-cpt.php' );
        //     require_once ( DREMSRENT_URL.'/inc/bookings/dreamsrent_booking.php' );
        //     $stores['product'] = 'Dreams_Product_Data_Store_CPT';
        //     return $stores;
        // // do_action( ' woocommerce_new_order ');
        // }

 

 

        add_filter( 'woocommerce_should_load_paypal_standard', '__return_true' );
        add_theme_support( 'woocommerce' );

        function add_paypal_standard_gateway($gateways) {
            $gateways[] = 'WC_Gateway_Paypal';
            return $gateways;
        }
        add_filter( 'woocommerce_payment_gateways', 'add_paypal_standard_gateway' );

 
  





        add_action('wp_ajax_verify_otp', 'verify_otp');
        add_action('wp_ajax_nopriv_verify_otp', 'verify_otp');

        function verify_otp() {
            check_ajax_referer('send_otp_nonce', 'security');

            $email = sanitize_email($_POST['email']);
            $otp = sanitize_text_field($_POST['otp']);
            
            $stored_otp = get_transient('otp_' . md5($email));

            if ($stored_otp && $stored_otp == $otp) {
                delete_transient('otp_' . md5($email));
                wp_send_json_success();
            } else {
                wp_send_json_error(array('message' => 'Invalid or expired OTP.'));
            }

            wp_die();
        }

 


 


add_action( 'init', 'replace_cart_and_checkout_page_content_with_shortcodes' );

function replace_cart_and_checkout_page_content_with_shortcodes() {
    // Replace content on the Cart page
    $cart_page = get_page_by_path( 'cart' );
    if ( $cart_page && has_block( 'woocommerce/cart', $cart_page->post_content ) ) {
        wp_update_post( [
            'ID'           => $cart_page->ID,
            'post_content' => '[woocommerce_cart]',
        ] );
    }

    // Replace content on the Checkout page
    $checkout_page = get_page_by_path( 'checkout' );
    if ( $checkout_page && has_block( 'woocommerce/checkout', $checkout_page->post_content ) ) {
        wp_update_post( [
            'ID'           => $checkout_page->ID,
            'post_content' => '[woocommerce_checkout]',
        ] );
    }
}


function my_theme_register_block_styles() {
    // Add custom styles for the Paragraph block
    register_block_style(
        'core/paragraph',
        array(
            'name'  => 'fancy-paragraph',
            'label' => __( 'Fancy Paragraph', 'dreamsrent' ),
            'inline_style' => '.wp-block-paragraph.is-style-fancy-paragraph { font-style: italic; color: #3498db; }',
        )
    );

    // Add custom styles for the Image block
    register_block_style(
        'core/image',
        array(
            'name'  => 'rounded-image',
            'label' => __( 'Rounded Image', 'dreamsrent' ),
            'inline_style' => '.wp-block-image.is-style-rounded-image img { border-radius: 50%; }',
        )
    );
}
add_action( 'init', 'my_theme_register_block_styles' );


function my_theme_register_block_patterns() {
    // Register a simple hero block pattern
    register_block_pattern(
        'my-theme/hero-section',
        array(
            'title'       => __( 'Hero Section', 'dreamsrent' ),
            'description' => __( 'A hero section with a heading, paragraph, and button.', 'dreamsrent' ),
            'content'     => '<!-- wp:group {"align":"full","style":{"spacing":{"padding":{"top":"50px","bottom":"50px"}}},"backgroundColor":"primary","textColor":"white"} -->
                <div class="wp-block-group alignfull has-white-color has-primary-background-color has-text-color has-background" style="padding-top:50px;padding-bottom:50px;">
                    <!-- wp:heading {"textAlign":"center"} -->
                    <h2 style="text-align:center">Welcome to My Website</h2>
                    <!-- /wp:heading -->

                    <!-- wp:paragraph {"align":"center"} -->
                    <p style="text-align:center">This is a hero section to grab attention and provide important information.</p>
                    <!-- /wp:paragraph -->

                    <!-- wp:buttons {"layout":{"type":"flex","justifyContent":"center"}} -->
                    <div class="wp-block-buttons">
                        <!-- wp:button {"backgroundColor":"secondary","textColor":"white"} -->
                        <div class="wp-block-button"><a class="wp-block-button__link has-white-color has-secondary-background-color has-text-color has-background">Learn More</a></div>
                        <!-- /wp:button -->
                    </div>
                    <!-- /wp:buttons -->
                </div>
                <!-- /wp:group -->',
            'categories'  => array( 'featured' ),
        )
    );
}
add_action( 'init', 'my_theme_register_block_patterns' );




/**
 * Theme setup for adding block editor support.
 */
function dreamsrent_theme_setup() {
    // Enable support for core block styles.
    add_theme_support( 'wp-block-styles' );

    // Optionally, enable support for other block editor features:
    // Add wide alignment for blocks.
    add_theme_support( 'align-wide' );

    // Add support for responsive embeds.
    add_theme_support( 'responsive-embeds' );

    // Add support for editor styles.
    add_theme_support( 'editor-styles' );

    // Enqueue a custom editor style.
    add_editor_style( 'editor-style.css' );
}
add_action( 'after_setup_theme', 'dreamsrent_theme_setup' );


/**
 * Add support for custom logo in the theme.
 */
function dreamsrent_custom_logo_setup() {
    $defaults = array(
        'height'      => 100, // Set the height of the logo.
        'width'       => 400, // Set the width of the logo.
        'flex-height' => true, // Allow flexible height.
        'flex-width'  => true, // Allow flexible width.
        'header-text' => array( 'site-title', 'site-description' ), // Elements to hide when logo is displayed.
        'unlink-homepage-logo' => true, // WordPress 5.5+: Remove the link to the homepage if the logo is set.
    );
    add_theme_support( 'custom-logo', $defaults );
}
add_action( 'after_setup_theme', 'dreamsrent_custom_logo_setup' );



add_action('admin_enqueue_scripts', 'dreams_enqueue_brand_media_uploader');
function dreams_enqueue_brand_media_uploader($hook) {
    // Load only on taxonomy edit/add pages
    if (isset($_GET['taxonomy']) && $_GET['taxonomy'] === 'brand') {
        wp_enqueue_media();
        wp_enqueue_script('dreams-brand-image-upload', get_template_directory_uri() . '/assets/js/brand-image-upload.js', ['jquery'], null, true);
    }
}




  
// Custom Style enque
    
function dreamsrent_enqueue_styles() {
    wp_enqueue_style('dreamsrent-style', get_stylesheet_uri());
}
add_action('wp_enqueue_scripts', 'dreamsrent_enqueue_styles');


// 1. Add Meta Box to Page Editor
function custom_page_options_meta_box() {
    add_meta_box(
        'custom_page_options',                 // ID
        'Page Options',                        // Title
        'custom_page_options_callback',        // Callback function
        'page',                                // Post type
        'side',                                // Context: normal, side, advanced
        'default'                              // Priority
    );
}
add_action('add_meta_boxes', 'custom_page_options_meta_box');

// 2. Output Fields in Meta Box
function custom_page_options_callback($post) {
    // Add nonce for security
    wp_nonce_field('custom_page_options_nonce_action', 'custom_page_options_nonce');

    // Get current values
    $hide_title = get_post_meta($post->ID, '_hide_title', true);
    ?>
    <p>
        <label>
            <input type="checkbox" name="custom_hide_title" value="1" <?php checked($hide_title, '1'); ?> />
            Hide Page Title
        </label>
    </p>
    <?php
}

// 3. Save Meta Box Data
function save_custom_page_options($post_id) {
    // Verify nonce
    if (!isset($_POST['custom_page_options_nonce']) || 
        !wp_verify_nonce($_POST['custom_page_options_nonce'], 'custom_page_options_nonce_action')) {
        return;
    }

    // Don't save during autosave or revision
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (wp_is_post_revision($post_id)) return;

    // Save or delete meta
    if (isset($_POST['custom_hide_title'])) {
        update_post_meta($post_id, '_hide_title', '1');
    } else {
        delete_post_meta($post_id, '_hide_title');
    }
}
add_action('save_post', 'save_custom_page_options');


 
 

function enqueue_custom_slider_script() {
    if ( is_page('home') ) { // Or use is_front_page(), is_single('custom-slug'), is_page(123), etc.
                 wp_enqueue_script('custom-slider', get_template_directory_uri() . '/assets/js/custom-slider.js', ['jquery'], null, true);
     }
}
add_action('wp_enqueue_scripts', 'enqueue_custom_slider_script');




// table
function pmpro_membership_levels_table() {
    global $wpdb;
    $levels = $wpdb->get_results("SELECT id, name, description, initial_payment FROM {$wpdb->prefix}pmpro_membership_levels");

    if (empty($levels)) return "<p>No membership levels found.</p>";

    ob_start();
    ?>
    <div class="pmpro-membership-container">
        <?php foreach ($levels as $level) : ?>
            <div class="membership-plan <?php echo strtolower(str_replace(' ', '-', esc_html($level->name))); ?>">
                <h3><?php echo esc_html($level->name); ?></h3>
                <?php if ($level->name === 'Premium Membership') : ?>
                    <span class="popular-label">Popular</span>
                <?php endif; ?>
                <p class="price">£<?php echo esc_html(number_format((float)$level->initial_payment, 2, '.', '')); ?> /year</p>
                <ul class="benefits">
                    <?php 
                    $benefits = explode(',', $level->description); // Assuming the description contains a comma-separated list
                    foreach ($benefits as $benefit) : 
                    ?>
                        <li><?php echo esc_html(trim($benefit)); ?></li>
                    <?php endforeach; ?>
			
                </ul>
				<?php $option_value = get_option('pmpro_checkout_page_id');
				
?>
                <a href="<?php echo esc_url(get_permalink($option_value) . '?pmpro_level=' . $level->id); ?>" class="join-now-btn">
    Join Now
</a>

            </div>
        <?php endforeach; ?>
    </div>
    <style>
        .pmpro-membership-container { display: flex; gap: 20px; justify-content: center; text-align: center; }
        .membership-plan { border: 1px solid #ddd; padding: 20px; border-radius: 8px; width: 300px; background: #f9f9f9; }
        .membership-plan h3 { font-size: 20px; margin-bottom: 10px; }
        .popular-label { display: block; background: #ff9800; color: white; padding: 5px; font-size: 14px; margin-bottom: 10px; }
        .price { font-size: 24px; font-weight: bold; color: #333; margin: 10px 0; }
        .benefits { list-style: none; padding: 0; }
        .benefits li { font-size: 14px; padding: 5px 0; }
        .join-now-btn { display: inline-block; padding: 10px 20px; background: #0073aa; color: #fff; text-decoration: none; border-radius: 5px; margin-top: 15px; transition: 0.3s; }
        .join-now-btn:hover { background: #005f8d; }
    </style>
    <?php
    return ob_get_clean();
}

add_shortcode('pmpro_membership_table', 'pmpro_membership_levels_table');

add_filter( 'wp_2fa_enforced_roles', function( $roles ) {
    // Remove 'administrator' role from 2FA enforcement
    if( isset($roles['administrator']) ) {
        unset( $roles['administrator'] );
    }
    return $roles;
});


function create_announcements_cpt() {
    $labels = array(
        'name' => 'Announcements',
        'singular_name' => 'Announcement',
        'add_new' => 'Add New',
        'add_new_item' => 'Add New Announcement',
        'edit_item' => 'Edit Announcement',
        'new_item' => 'New Announcement',
        'view_item' => 'View Announcement',
        'view_items' => 'View Announcements',
        'search_items' => 'Search Announcements',
        'not_found' => 'No Announcements found',
        'all_items' => 'All Announcements',
    );

    $args = array(
        'label' => 'Announcements',
        'labels' => $labels,
        'public' => true,
        'menu_icon' => 'dashicons-megaphone',
        'supports' => array('title', 'editor','excerpt', 'thumbnail'), // thumbnail = featured image
        'has_archive' => true,
        'show_in_rest' => true,
      'taxonomies' => array('announcement_category'), // ✅ enable default categories

    );

    register_post_type('announcement', $args);
}
add_action('init', 'create_announcements_cpt');


function register_announcement_taxonomy() {
    register_taxonomy('announcement_category', ['announcement'], array(
        'labels' => array(
            'name' => 'Announcement Categories',
            'singular_name' => 'Announcement Category',
            'search_items' => 'Search Categories',
            'all_items' => 'All Categories',
            'edit_item' => 'Edit Category',
            'update_item' => 'Update Category',
            'add_new_item' => 'Add New Category',
            'new_item_name' => 'New Category Name',
            'menu_name' => 'Categories',
        ),
        'hierarchical' => true, // behaves like default category
        'public' => true,
        'show_ui' => true,
        'show_in_rest' => true,
        'show_admin_column' => true,
    ));
}
add_action('init', 'register_announcement_taxonomy');


add_action( 'add_meta_boxes', 'announcement_add_custom_meta_box' );

function announcement_add_custom_meta_box() {
    add_meta_box(
        'announcement_custom_meta_box',
        __( 'Announcement Details', 'dreamsrent_elementor' ),
        'announcement_custom_meta_box_callback',
        'announcement',
        'normal',
        'default'
    );
}
function announcement_custom_meta_box_callback( $post ) {
    // Nonce field
    wp_nonce_field( 'announcement_save_custom_meta', 'announcement_custom_meta_nonce' );

    // Get existing values
    $address = get_post_meta( $post->ID, '_announcement_address', true );
    $date    = get_post_meta( $post->ID, '_announcement_date', true );
    $time    = get_post_meta( $post->ID, '_announcement_time', true );

    ?>
    <p>
        <label for="announcement_address"><strong><?php _e( 'Address:', 'dreamsrent_elementor' ); ?></strong></label><br>
        <input type="text" id="announcement_address" name="announcement_address" value="<?php echo esc_attr( $address ); ?>" style="width:100%;" />
    </p>
    <p>
        <label for="announcement_date"><strong><?php _e( 'Date:', 'dreamsrent_elementor' ); ?></strong></label><br>
        <input type="date" id="announcement_date" name="announcement_date" value="<?php echo esc_attr( $date ); ?>" />
    </p>
    <p>
        <label for="announcement_time"><strong><?php _e( 'Time:', 'dreamsrent_elementor' ); ?></strong></label><br>
        <input type="time" id="announcement_time" name="announcement_time" value="<?php echo esc_attr( $time ); ?>" />
    </p>
    <?php
}
add_action( 'save_post', 'announcement_save_custom_meta' );

function announcement_save_custom_meta( $post_id ) {
    // Verify nonce
    if ( ! isset( $_POST['announcement_custom_meta_nonce'] ) ||
         ! wp_verify_nonce( $_POST['announcement_custom_meta_nonce'], 'announcement_save_custom_meta' ) ) {
        return;
    }

    // Prevent autosave overwrite
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;

    // Permissions check
    if ( isset( $_POST['post_type'] ) && 'announcement' === $_POST['post_type'] ) {
        if ( ! current_user_can( 'edit_post', $post_id ) ) return;
    }

    // Save Address
    if ( isset( $_POST['announcement_address'] ) ) {
        update_post_meta( $post_id, '_announcement_address', sanitize_text_field( $_POST['announcement_address'] ) );
    }

    // Save Date
    if ( isset( $_POST['announcement_date'] ) ) {
        update_post_meta( $post_id, '_announcement_date', sanitize_text_field( $_POST['announcement_date'] ) );
    }

    // Save Time
    if ( isset( $_POST['announcement_time'] ) ) {
        update_post_meta( $post_id, '_announcement_time', sanitize_text_field( $_POST['announcement_time'] ) );
    }
}


function add_announcement_gallery_meta_box() {
    add_meta_box(
        'announcement_gallery_meta_box',
        'Gallery Images',
        'render_announcement_gallery_meta_box',
        'announcement',
        'normal',
        'high'
    );
}
add_action('add_meta_boxes', 'add_announcement_gallery_meta_box');

function render_announcement_gallery_meta_box($post) {
    $gallery_images = get_post_meta($post->ID, '_announcement_gallery', true);
    wp_nonce_field('save_announcement_gallery', 'announcement_gallery_nonce');
    ?>
    <div id="announcement-gallery-wrapper">
        <button type="button" class="button" id="add-gallery-images">Add Gallery Images</button>
        <ul id="announcement-gallery-list">
            <?php
            if (!empty($gallery_images) && is_array($gallery_images)) {
                foreach ($gallery_images as $image_id) {
                    $img_url = wp_get_attachment_image_url($image_id, 'thumbnail');
                    echo '<li data-id="' . esc_attr($image_id) . '">
                            <img src="' . esc_url($img_url) . '" style="width:80px;height:80px;" />
                            <span class="remove-image">×</span>
                        </li>';
                }
            }
            ?>
        </ul>
        <input type="hidden" id="announcement-gallery-ids" name="announcement_gallery" value="<?php echo esc_attr(implode(',', (array) $gallery_images)); ?>" />
    </div>
    <style>
        #announcement-gallery-list { list-style: none; padding: 0; display: flex; flex-wrap: wrap; gap: 10px; }
        #announcement-gallery-list li { position: relative; }
        #announcement-gallery-list .remove-image {
            position: absolute;
            top: 0;
            right: 0;
            background: red;
            color: white;
            padding: 0 5px;
            cursor: pointer;
        }
    </style>
    <script>
        jQuery(document).ready(function($) {
            var frame;
            $('#add-gallery-images').on('click', function(e) {
                e.preventDefault();
                if (frame) { frame.open(); return; }
                frame = wp.media({
                    title: 'Select or Upload Gallery Images',
                    button: { text: 'Use these images' },
                    multiple: true
                });
                frame.on('select', function() {
                    var selection = frame.state().get('selection');
                    var ids = [];
                    var list = $('#announcement-gallery-list').empty();
                    selection.map(function(attachment) {
                        attachment = attachment.toJSON();
                        ids.push(attachment.id);
                        list.append('<li data-id="'+attachment.id+'"><img src="'+attachment.sizes.thumbnail.url+'" style="width:80px;height:80px;" /><span class="remove-image">×</span></li>');
                    });
                    $('#announcement-gallery-ids').val(ids.join(','));
                });
                frame.open();
            });

            $('#announcement-gallery-list').on('click', '.remove-image', function() {
                $(this).parent().remove();
                var ids = [];
                $('#announcement-gallery-list li').each(function() {
                    ids.push($(this).data('id'));
                });
                $('#announcement-gallery-ids').val(ids.join(','));
            });
        });
    </script>
    <?php
}

function save_announcement_gallery_meta_box($post_id) {
    if (!isset($_POST['announcement_gallery_nonce']) || !wp_verify_nonce($_POST['announcement_gallery_nonce'], 'save_announcement_gallery')) {
        return;
    }

    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;

    if (isset($_POST['announcement_gallery'])) {
        $gallery_ids = array_filter(array_map('intval', explode(',', $_POST['announcement_gallery'])));
        update_post_meta($post_id, '_announcement_gallery', $gallery_ids);
    }
}
add_action('save_post', 'save_announcement_gallery_meta_box');

 // Only show billing address fields for logged-in users
add_filter('pmpro_include_billing_address_fields', 'show_billing_address_for_logged_in_users');

function show_billing_address_for_logged_in_users($show) {
    if (!is_user_logged_in()) {
        return false; // Hide the billing fields
    }
    return $show; // Keep original behavior for logged-in users
}

add_filter('pmpro_include_payment_information_fields', 'show_payment_information_for_logged_in_users');


function show_payment_information_for_logged_in_users($show) {
    if (!is_user_logged_in()) {
        return false; // Hide the billing fields
    }
    return $show; // Keep original behavior for logged-in users
}


add_filter('pmpro_confirmed_data', 'show_pmpro_confirmed_data_for_logged_in_users');


function show_pmpro_confirmed_data_for_logged_in_users($show) {
    if (!is_user_logged_in()) {
        return false; // Hide the billing fields
    }
    return $show; // Keep original behavior for logged-in users
}



add_action('pmpro_checkout_after_user_fields', 'add_hidden_redirect_input_for_otp');
function add_hidden_redirect_input_for_otp() {
    if (!is_user_logged_in()) {
        ?>
 <input type="hidden" name="redirect_after_verification" value="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>">
        <?php
    }
}


add_action('wp_head', function () {
    if (!is_user_logged_in()) {
        echo '<style>#pmpro_message_bottom { display: none !important; } #pmpro_message { display: none !important; } </style>';
    }
});


add_filter('pmpro_checkout_message', 'show_pmpro_checkout_message_for_logged_in_users');
function show_pmpro_checkout_message_for_logged_in_users($show) {
    if (!is_user_logged_in()) {
        return false; // Hide the billing fields
    }
    return $show; // Keep original behavior for logged-in users
}




add_filter('authenticate', 'urv_block_unverified_users', 30, 3);
function urv_block_unverified_users($user, $username, $password) {
    // Return if already error or invalid
    if (is_wp_error($user) || !$user) {
        return $user;
    }

    // Allow admin users to log in even if not verified
    if (user_can($user, 'administrator')) {
        return $user;
    }

    // Check if the user is verified
    $is_verified = get_user_meta($user->ID, 'urv_verified', true);
    if ($is_verified != true) {
        return new WP_Error(
            'urv_not_verified',
            __('<strong>Error:</strong> Your email address is not verified. Please check your email for the OTP.', 'urv')
        );
    }

    return $user;
}
// add_action('init', function() {
//     if ( isset($_GET['send_test_email']) ) {
//         $to = '[email protected]'; // Change to your email
//         $subject = 'Test Email from WordPress';
//         $message = '<p>This is a <strong>test</strong> email sent using the default PHP mail() function.</p>';
//         $headers = ['Content-Type: text/html; charset=UTF-8'];

//         // Optional: Set From name and email
//         add_filter( 'wp_mail_from', function( $email ) {
//             return '[email protected]'; // Replace with a valid domain-based email
//         });
//         add_filter( 'wp_mail_from_name', function( $name ) {
//             return 'Your Website Name'; // Your site name or brand
//         });

//         // Send the email
//         if (wp_mail($to, $subject, $message, $headers)) {
//             echo '✅ Email sent successfully using PHP mail()!';
//         } else {
//             echo '❌ Email failed to send. Server may not support mail().';
//         }

//         exit;
//     }
// });


add_action('admin_menu', function () {
    add_management_page('Import Members', 'Import Members', 'manage_options', 'import_members', 'custom_import_members_page');
});

function custom_import_members_page() {
    ?>
    <div class="wrap">
        <h1>Import Members from CSV</h1>
        <form method="post" enctype="multipart/form-data">
            <input type="file" name="members_csv" accept=".csv" required>
            <?php submit_button('Import'); ?>
        </form>
        <hr>
        <?php
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_FILES['members_csv']['tmp_name'])) {
            custom_process_members_csv($_FILES['members_csv']['tmp_name']);
        }
        ?>
    </div>
    <?php
}

function custom_process_members_csv($csv_file_path) {
    if (!function_exists('pmpro_changeMembershipLevel')) {
        echo '<div class="notice notice-error"><p>PMPro is not active.</p></div>';
        return;
    }

    if (($handle = fopen($csv_file_path, 'r')) !== false) {
        $row = 0;
        while (($data = fgetcsv($handle, 1000, ',')) !== false) {
            if ($row === 0) {
                $headers = array_map('trim', $data);
            } else {
                $user_data = array_combine($headers, $data);

                $user_login = sanitize_user($user_data['user_login']);
                $user_email = sanitize_email($user_data['user_email']);
                $first_name = sanitize_text_field($user_data['first_name']);
  $user_title = sanitize_user($user_data['title']);
				$businessname = sanitize_user($user_data['businessname']);
                $last_name = sanitize_text_field($user_data['last_name']);
                $role = in_array($user_data['role'], ['administrator', 'subscriber']) ? $user_data['role'] : 'subscriber';

                $address = sanitize_text_field($user_data['address'] ?? '');
                $address2 = sanitize_text_field($user_data['address2'] ?? '');
                $state = sanitize_text_field($user_data['state'] ?? '');
                $postalcode = sanitize_text_field($user_data['postalcode'] ?? '');
                $city = sanitize_text_field($user_data['city'] ?? '');
                $mobile = sanitize_text_field($user_data['mobile'] ?? '');
                $payment_status = sanitize_text_field($user_data['payment_status'] ?? '');
                $membership_name = trim($user_data['membership_name'] ?? '');
                $membership_level = intval($user_data['membership_level']);
                $urv_verified = intval($user_data['urv_verified']);


                // Map membership name to ID
                $membership_map = [
                    'Free' => 1,
                    'Premium' => 2,
                    'Business' => 3,
                ];

                $membership_level_old = $membership_map[$membership_name] ?? 0;

                if (!$user_login || !$user_email) {
                    echo "<p style='color:red;'>Missing login or email for row $row.</p>";
                    continue;
                }

                if (!username_exists($user_login) && !email_exists($user_email)) {
                    $user_id = wp_insert_user([
                        'user_login' => $user_login,
                        'user_email' => $user_email,
                        'first_name' => $first_name,
                        'last_name' => $last_name,
                        'user_pass' => wp_generate_password(),
                        'role' => $role
                    ]);

                    if (!is_wp_error($user_id)) {
                        pmpro_changeMembershipLevel($membership_level, $user_id);
                        update_user_meta($user_id, 'address', $address);
						  update_user_meta($user_id, 'user_title', $user_title);
                        update_user_meta($user_id, 'city', $city);
                        update_user_meta($user_id, 'mobile', $mobile);
						update_user_meta($user_id, 'businessname', $businessname);

                        update_user_meta($user_id, 'address2', $address2);
                        update_user_meta($user_id, 'state', $state);
                        update_user_meta($user_id, 'postalcode', $postalcode);

    update_user_meta($user_id, 'pmpro_bfirstname', $first_name);
    update_user_meta($user_id, 'pmpro_blastname', $last_name);
						update_user_meta($user_id, 'pmprorhprefix_title', $user_title);
						update_user_meta($user_id, 'pmpro_businessname', $businessname);
						update_user_meta($user_id, 'businessname', $businessname);
update_user_meta($user_id, 'pmpro_bphone', $mobile);
                          // Update PMPro billing fields (for checkout form)
    update_user_meta($user_id, 'pmpro_baddress1', $address);

    update_user_meta($user_id, 'pmpro_baddress2', $address2);
    update_user_meta($user_id, 'pmpro_bstate', $state);
    update_user_meta($user_id, 'pmpro_bzipcode', $postalcode);

    update_user_meta($user_id, 'pmpro_bcity', $city);

                        update_user_meta($user_id, 'urv_verified', $urv_verified);
                        update_user_meta($user_id, 'payment_status', $payment_status);
                        echo "<p style='color:green;'>User <strong>$user_login</strong> imported and assigned to <strong>$membership_name</strong>.</p>";
                    } else {
                        echo "<p style='color:red;'>Error creating user <strong>$user_login</strong>: " . $user_id->get_error_message() . "</p>";
                    }
                } else {
                    echo "<p style='color:orange;'>User <strong>$user_login</strong> already exists. Skipped.</p>";
                }
            }
            $row++;
        }
        fclose($handle);
    } else {
        echo '<p>Unable to open CSV file.</p>';
    }
	
	add_filter('pmpro_include_billing_address_fields', '__return_true');
add_filter('pmpro_include_payment_information_fields', '__return_true'); 
	
} 


// Force billing fields to display in PMPro checkout
// Redirect unpaid Premium/Business members to checkout
function redirect_unpaid_members_to_checkout() {
    // Skip if user is not logged in or is admin
    if (!is_user_logged_in() || current_user_can('administrator')) {
        return;
    }
    
    // Get current user and membership info
    $user_id = get_current_user_id();
    $membership_level = pmpro_getMembershipLevelForUser($user_id);
    
    // Check if user has Premium (2) or Business (3) membership but hasn't paid
    if ($membership_level && in_array($membership_level->ID, array(2, 3))) {
        $payment_status = get_user_meta($user_id, 'payment_status', true);
        
        // If payment status is not 'success' or empty, redirect to checkout
        if (empty($payment_status) || $payment_status !== 'success') {
            // Get checkout page URL
            $checkout_page_id = get_option('pmpro_checkout_page_id');
            if ($checkout_page_id) {
                $checkout_url = add_query_arg(
                    array(
                        'pmpro_level' => $membership_level->ID,
                        'unpaid_redirect' => '1'
                    ),
                    get_permalink($checkout_page_id)
                );
                
                // Redirect if not already on checkout page
                if (!is_page($checkout_page_id)) {
                    wp_redirect($checkout_url);
                    exit;
                }
            }
        }
    }
}
add_action('template_redirect', 'redirect_unpaid_members_to_checkout');

// Add custom message on checkout page for unpaid members
function add_unpaid_member_checkout_message() {
    if (!is_user_logged_in() || !isset($_GET['unpaid_redirect'])) {
        return;
    }
    
    $user_id = get_current_user_id();
    $membership_level = pmpro_getMembershipLevelForUser($user_id);
    
    if ($membership_level && in_array($membership_level->ID, array(2, 3))) {
        echo '<div class="pmpro_message pmpro_alert">';
        echo '<p><strong>Payment Required:</strong> Your ' . esc_html($membership_level->name) . ' membership requires payment to access all features. Please complete your payment below.</p>';
        echo '</div>';
    }
}
add_action('pmpro_checkout_before_form', 'add_unpaid_member_checkout_message');

// Update payment status when payment is completed
function update_payment_status_after_checkout($user_id, $order) {
    if ($order->status === 'success') {
        update_user_meta($user_id, 'payment_status', 'success');
        
        // Also update in PMPro user meta for consistency
        update_user_meta($user_id, 'pmpro_payment_status', 'success');
    }
}
add_action('pmpro_after_checkout', 'update_payment_status_after_checkout', 10, 2);

// Handle payment status updates from payment gateways
function handle_payment_status_update($user_id, $order) {
    if ($order->status === 'success') {
        update_user_meta($user_id, 'payment_status', 'success');
    }
}
add_action('pmpro_updated_order', 'handle_payment_status_update', 10, 2);

// Add payment status column to admin users list
function add_payment_status_column($columns) {
    $columns['payment_status'] = 'Payment Status';
    return $columns;
}
add_filter('manage_users_columns', 'add_payment_status_column');

function show_payment_status_column($value, $column_name, $user_id) {
    if ($column_name === 'payment_status') {
        $payment_status = get_user_meta($user_id, 'payment_status', true);
        $membership_level = pmpro_getMembershipLevelForUser($user_id);
        
        if ($membership_level && in_array($membership_level->ID, array(2, 3))) {
            if ($payment_status === 'success') {
                return '<span style="color:green;">Paid</span>';
            } else {
                return '<span style="color:red;">Unpaid</span>';
            }
        } else {
            return 'N/A';
        }
    }
    return $value;
}
add_filter('manage_users_custom_column', 'show_payment_status_column', 10, 3);

// Make payment status column sortable
function make_payment_status_sortable($columns) {
    $columns['payment_status'] = 'payment_status';
    return $columns;
}
add_filter('manage_users_sortable_columns', 'make_payment_status_sortable');

// Add bulk action to update payment status
function add_payment_status_bulk_action($bulk_actions) {
    $bulk_actions['mark_paid'] = 'Mark as Paid';
    $bulk_actions['mark_unpaid'] = 'Mark as Unpaid';
    return $bulk_actions;
}
add_filter('bulk_actions-users', 'add_payment_status_bulk_action');

function handle_payment_status_bulk_action($redirect_to, $doaction, $user_ids) {
    if ($doaction === 'mark_paid') {
        foreach ($user_ids as $user_id) {
            update_user_meta($user_id, 'payment_status', 'success');
        }
        $redirect_to = add_query_arg('marked_paid', count($user_ids), $redirect_to);
    } elseif ($doaction === 'mark_unpaid') {
        foreach ($user_ids as $user_id) {
            update_user_meta($user_id, 'payment_status', '');
        }
        $redirect_to = add_query_arg('marked_unpaid', count($user_ids), $redirect_to);
    }
    return $redirect_to;
}
add_filter('handle_bulk_actions-users', 'handle_payment_status_bulk_action', 10, 3);

// Admin notice for bulk actions
function payment_status_bulk_admin_notice() {
    if (!empty($_REQUEST['marked_paid'])) {
        $count = intval($_REQUEST['marked_paid']);
        printf('<div class="notice notice-success"><p>Marked %d users as paid.</p></div>', $count);
    }
    if (!empty($_REQUEST['marked_unpaid'])) {
        $count = intval($_REQUEST['marked_unpaid']);
        printf('<div class="notice notice-success"><p>Marked %d users as unpaid.</p></div>', $count);
    }
}
add_action('admin_notices', 'payment_status_bulk_admin_notice');