<?php
/**
 * Functions which enhance the theme by hooking into WordPress
 *
 * @package Pointify_-_Listing_Directory_WordPress_Theme
 */

/**
 * Adds custom classes to the array of body classes.
 *
 * @param array $classes Classes for the body element.
 * @return array
 */
function pointify_body_classes( $classes ) {
	// Adds a class of hfeed to non-singular pages.
	if ( ! is_singular() ) {
		$classes[] = 'hfeed';
	}

	// Adds a class of no-sidebar when there is no sidebar present.
	if ( ! is_active_sidebar( 'sidebar-1' ) ) {
		$classes[] = 'no-sidebar';
	}

	return $classes;
}
add_filter( 'body_class', 'pointify_body_classes' );

/**
 * pointify_get_listing_page_permalink
 */

function pointify_get_listing_page_permalink() {
	if ( function_exists( 'job_manager_get_permalink' ) ) {
		return job_manager_get_permalink( 'jobs' );
	}

	return false;
}

/**
 * Add a pingback url auto-discovery header for single posts, pages, or attachments.
 */
function pointify_pingback_header() {
	if ( is_singular() && pings_open() ) {
		printf( '<link rel="pingback" href="%s">', esc_url( get_bloginfo( 'pingback_url' ) ) );
	}
}
add_action( 'wp_head', 'pointify_pingback_header' );


/**
 * Post Page Category Function
 */

function pointify_get_the_category() {
	$category = get_the_category();
	if ( isset( $category[0] ) && $category[0] ) {
		echo '<span class="post-cat-cls"><a href="' . get_category_link( $category[0]->term_id ) . '" title="'.$category[0]->cat_name.'">' . $category[0]->cat_name . '</a></span>';
	}	
}
/**
 * Post Page Tag Function
 */

function pointify_get_the_tags() {
	$post_tags = get_the_tags();
	$separator = '#';
	if ( ! empty( $post_tags ) ) {
        foreach ( $post_tags as $tag ) {
			printf(
				__( '<span class="post-tag-cls"><a href="%1$s" title="%3$s">%2$s%3$s </a></span>', 'pointify' ),
				esc_attr( get_tag_link( $tag->term_id ) ),
				$separator,
				$tag->name
			);
        }
    }
}		

/**
 * Post Author Sectin
 */

function pointify_author_details() {
	$author_id = get_the_author_meta('ID');
	$author_name = get_the_author_meta('display_name', $author_id);
	$author_avatar = get_avatar_url($author_id, array('size' => 96));

	echo '<div class="author-info">';
	echo '<div class="author-avatar">';
	if ($author_avatar) {
		echo '<img src="' . esc_url($author_avatar) . '" alt="Author Avatar" />';
	} else {
		// Default image or fallback if the author doesn't have a Gravatar
		echo '<img src="' . esc_url(get_template_directory_uri() . '/path-to-default-image.jpg') . '" alt="Default Image" />';
	}
	echo '</div>';
	echo '<p class="author-name">' . esc_html__('', 'pointify') . $author_name . '</p>';
	echo '</div>';
}

/**
 * Post Time 
 */ 

function pointify_post_time_details() {
	$post_date_custom_format = get_the_date('F j, Y');
	$post_time_custom_format = get_the_time('g:i A');

	echo '<div class="post-published_date">Date: ' . $post_date_custom_format . '</div>';
	echo '<div class="post-published_time">Time: ' . $post_time_custom_format .'</div>';
}

/**
 * Share post function
 */

function pointify_post_share() {
	$twitter_share_url = 'https://twitter.com/intent/tweet?url=' . urlencode(get_permalink()) . '&text=' . urlencode(get_the_title());
	$facebook_share_url = 'https://www.facebook.com/sharer/sharer.php?u=' . urlencode(get_permalink());
	$instagram_profile_url = 'https://www.instagram.com/your_instagram_handle/';
?>
	<div class="post-share-cls">Share:</div> 
	<a href="<?php echo esc_url($instagram_profile_url); ?>" target="_blank" rel="nofollow" title="<?php esc_attr_e( 'instagram', 'pointify' ); ?>"><i class="fa fa-instagram" aria-hidden="true"></i></a>
	<a href="<?php echo esc_url($twitter_share_url); ?>" target="_blank" rel="nofollow" title="<?php esc_attr_e( 'twitter', 'pointify' ); ?>"><i class="fa fa-twitter" aria-hidden="true"></i>
</a>
	<a href="<?php echo esc_url($facebook_share_url); ?>" target="_blank" rel="nofollow" title="<?php esc_attr_e( 'facebook', 'pointify' ); ?>"><i class="fa fa-facebook" aria-hidden="true"></i>
</a>
	
<?php
}

/**
 * Post Pagination 
 */

function pointify_post_pagination() {
	global $wp_query;

    $big = 999999999; // need an unlikely integer

    $paginate_links = paginate_links(array(
        'base'    => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
        'format'  => '?paged=%#%',
        'current' => max(1, get_query_var('paged')),
        'total'   => $wp_query->max_num_pages,
        'type'    => 'span',
        'prev_text' => __('<i class="fa fa-angle-left" aria-hidden="true"></i>', 'pointify'),
        'next_text' => __('<i class="fa fa-angle-right" aria-hidden="true"></i>', 'pointify'),
    ));

    return $paginate_links;
}

/**
 * Page Header Function
 */

function pointify_page_header() {
	if (is_home()) : ?>
		<div class="pointify-page-header">
			<h2 class="pointify-blog-title"><?php echo esc_html__('Blog', 'pointify'); ?></h2>
		</div>
	<?php elseif(is_archive()) : ?>
		<div class="pointify-page-header">
			<h2 class="pointify-blog-title"><?php the_archive_title(); ?></h2>
		</div>
	<?php elseif ( is_404() ) : ?>
        <div class="pointify-page-header">
            <h2 class="pointify-page-title"><?php esc_html_e( 'Page Not Found', 'pointify' ); ?></h2>
        </div>
    <?php else : ?>
		<div class="pointify-page-header">
			<h2 class="pointify-page-title"><?php the_title(); ?></h2>
		</div>
	<?php endif;
}

function pointify_page_breadcrumb() {
    // Home link
    $output = '<a href="' . esc_url(home_url('/')) . '" title="' . esc_html('Home') . '">' . esc_html('Home') . '</a> <i class="fa fa-angle-right" aria-hidden="true"></i> ';
    
    // Check if on a single post
    if (is_single()) {
        $categories = get_the_category();
        if ($categories) {
            $output .= '<a href="' . esc_url(get_category_link($categories[0]->term_id)) . '" title="' . esc_html($categories[0]->name) . '">' . esc_html($categories[0]->name) . '</a> <i class="fa fa-angle-right" aria-hidden="true"></i> ';
        }
        $output .= get_the_title();
    }
    // Check if on a page
    elseif (is_page()) {
        $ancestors = get_post_ancestors(get_the_ID());
        if ($ancestors) {
            $ancestors = array_reverse($ancestors);
            foreach ($ancestors as $ancestor) {
                $output .= '<a href="' . esc_url(get_permalink($ancestor)) . '" title="' . esc_html(get_the_title($ancestor)) . '" >' . esc_html(get_the_title($ancestor)) . '</a> <i class="fa fa-angle-right" aria-hidden="true"></i> ';
            }
        }
        $output .= get_the_title();
    }
    // Check if on an archive page (category, tag, custom taxonomy)
    elseif (is_category() || is_tag() || is_tax()) {
        $output .= single_term_title('', false);
    }
    // Check if on the blog page
    elseif (is_home()) {
        $output .= esc_html('Blog');
    }
    // Check if on the search results page
    elseif (is_search()) {
        $output .= esc_html('Search results for: ') . get_search_query();
    }
    // Check if on the 404 page
    elseif (is_404()) {
        $output .= esc_html('Page Not Found');
    }
	elseif (is_archive()) {
		$output .= esc_html('Archive');
	}
    // Check if on an Shop page
    elseif (is_shop()) {
        $output .= esc_html('Shop');
    }
    // Default fallback for other cases
    else {
        $output .= get_the_title();
    }

    return $output;
}

/**
 * Post Comment Time Function
 */

function pointify_comment_date($date, $comment) {
    // Customize the date format as needed
    if ( get_post_type() !== 'product' ) { 
		$get_comment_time = get_comment_time( 'U' );
        $custom_date = printf( _x( '%s ago', '%s = human-readable time difference', 'pointify' ), human_time_diff( intval($get_comment_time), current_time( 'timestamp' ) ) );
        return $custom_date;
    }
}
add_filter('get_comment_date', 'pointify_comment_date', 10, 2);

/**
 * Logout Functionality
 */

function pointify_add_logout_link_to_menu($items, $args) {
    if ($args->theme_location == 'user-menu' && is_user_logged_in()) {
        $logout_link = '<li><a href="' . wp_logout_url(home_url()) . '" title="'. esc_html__('Logout', 'pointify') .'">';
        $logout_link .= esc_html__('Logout', 'pointify');
        $logout_link .= '</a></li>';
        $items .= $logout_link;
    }else{
		if ($args->theme_location == 'user-menu' && !is_user_logged_in()) {
			$logout_link = '<li><a href="' . wp_login_url(home_url()) . '" title="'. esc_html__('Login', 'pointify') .'">';
			$logout_link .= esc_html__('Login', 'pointify');
			$logout_link .= '</a></li>';
			$items .= $logout_link;
		}
	}
    return $items;
}

add_filter('wp_nav_menu_items', 'pointify_add_logout_link_to_menu', 10, 2);

/**
 * Search Form
 */

function pointify_custom_search_form($form) {
    $form = '<form method="get" class="search-form" action="' . home_url('/') . '">
		<label>
			<span class="screen-reader-text">Search for:</span>
			<input type="search" class="search-field" placeholder="Search…" value="' . get_search_query() . '" name="s" id="s">
		</label>
		<button type="submit" id="searchsubmit" class="search-submit"><i class="fa fa-search"></i></button>
    </form>';
    return $form;
}
add_filter('get_search_form', 'pointify_custom_search_form');

/**
 * Add pointify fields to user profile
 */ 

function pointify_add_user_social_fields($user) {
    ?>
    <h3><?php esc_html_e('Social Media Links', 'pointify'); ?></h3>
    
    <table class="form-table">
        <tr>
            <th><label for="facebook"><?php esc_html_e('Facebook', 'pointify'); ?></label></th>
            <td>
                <input type="text" name="facebook" id="facebook" value="<?php echo esc_attr(get_user_meta($user->ID, 'facebook', true)); ?>" class="regular-text" />
            </td>
        </tr>
        <tr>
            <th><label for="twitter"><?php esc_html_e('Twitter', 'pointify'); ?></label></th>
            <td>
                <input type="text" name="twitter" id="twitter" value="<?php echo esc_attr(get_user_meta($user->ID, 'twitter', true)); ?>" class="regular-text" />
            </td>
        </tr>
        <tr>
            <th><label for="instagram"><?php esc_html_e('Instagram', 'pointify'); ?></label></th>
            <td>
                <input type="text" name="instagram" id="instagram" value="<?php echo esc_attr(get_user_meta($user->ID, 'instagram', true)); ?>" class="regular-text" />
            </td>
        </tr>
		<tr>
            <th><label for="youtube"><?php esc_html_e('Youtube', 'pointify'); ?></label></th>
            <td>
                <input type="text" name="youtube" id="youtube" value="<?php echo esc_attr(get_user_meta($user->ID, 'youtube', true)); ?>" class="regular-text" />
            </td>
        </tr>
    </table>
    <?php
}
add_action('show_user_profile', 'pointify_add_user_social_fields');
add_action('edit_user_profile', 'pointify_add_user_social_fields');

/**
 * Save custom fields
 */

function pointify_save_user_social_fields($user_id) {
    if (current_user_can('edit_user', $user_id)) {
        update_user_meta($user_id, 'facebook', sanitize_text_field($_POST['facebook']));
        update_user_meta($user_id, 'twitter', sanitize_text_field($_POST['twitter']));
        update_user_meta($user_id, 'instagram', sanitize_text_field($_POST['instagram']));
        update_user_meta($user_id, 'youtube', sanitize_text_field($_POST['youtube']));
    }
}
add_action('personal_options_update', 'pointify_save_user_social_fields');
add_action('edit_user_profile_update', 'pointify_save_user_social_fields');

/**
 * Woocommerce Product Page Funtions Start
 */

add_action( 'woocommerce_before_shop_loop', 'pointify_shop_page_start_action' );

function pointify_shop_page_start_action(){
    ?>
    <div class="product-main-caption">
        <div class="container">
            <div class="row">
                <div class="col-md-3">
                    <div class="product-sidebar">
                        <?php dynamic_sidebar( 'product-page-widget' ); ?>
                    </div>
                </div>
                <div class="col-md-9">
                    <div class="product-main-section">
    <?php
} 

add_action( 'woocommerce_after_shop_loop', 'pointify_shop_page_end_action' );

function pointify_shop_page_end_action(){
    ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php
} 

/**
 * WooCommerce Breadcrumb and Sidebar Hide
 */

/**
 * Remove WooCommerce Sidebar, Page Title, Breadcrumb
 */

add_filter( 'woocommerce_before_main_content', 'pointify_remove_breadcrumbs');
function pointify_remove_breadcrumbs() {
    if(is_shop() || is_product() || is_product_category()) {
        remove_action( 'woocommerce_before_main_content','woocommerce_breadcrumb', 20, 0);
        remove_action( 'woocommerce_sidebar', 'woocommerce_get_sidebar', 10 );
        add_filter( 'woocommerce_show_page_title', '__return_null' );
    }
}

/**
 * WooCommerce Product Page Function Start
 */

add_action( 'woocommerce_before_single_product', 'pointify_product_single_page_start_action' );

 /**
  * Function for `woocommerce_before_single_product` action-hook.
  * 
  */
function pointify_product_single_page_start_action(){
?>
    <div class="product-main-caption">
        <div class="container">
            <div class="row">
<?php
} 

add_action( 'woocommerce_after_single_product', 'pointify_product_single_page_end_action' );

/**
 * Function for `woocommerce_after_single_product_summary` action-hook.
 * 
 * @return void
 */
function pointify_product_single_page_end_action(){
    ?>
            </div>
        </div>
    </div>
<?php
}

/**
 * Change Product Title Tag H1 to H#
 */
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_title', 5 );
add_action( 'woocommerce_single_product_summary', 'pointify_changed_product_title_action', 5 );
function pointify_changed_product_title_action() {
    the_title( '<h3 class="product_title entry-title">', '</h3>' );
}

/**
 * WooCommerce Product Page Function End
 */

/**
 * WooCommerce Review time ago function start
 */

function pointify_custom_review_date_time() {

    echo '<time class="woocommerce-review__published-date" datetime="'.human_time_diff(get_comment_time('U'), current_time('timestamp')). __(' ago', 'pointify').'">'.human_time_diff(get_comment_time('U'), current_time('timestamp')). __(' ago', 'pointify').'</time>';

}

add_action('woocommerce_review_before_comment_text', 'pointify_custom_review_date_time', 20);

/**
 * WooCommerce Review time ago function end
 */

/**
 * Add quantity field with plus and minus buttons on product pages
 */

//1. Show Buttons
add_action( 'woocommerce_before_add_to_cart_quantity', 'pointify_display_quantity_plus' );
function pointify_display_quantity_plus() {
   echo '<div class="quantity-sec-cls"> <button type="button" class="plus" >+</button>';
}
add_action( 'woocommerce_after_add_to_cart_quantity', 'pointify_display_quantity_minus' );
function pointify_display_quantity_minus() {
   echo '<button type="button" class="minus" >-</button></div>';
}
//2. Trigger jQuery script
add_action( 'wp_footer', 'pointify_add_cart_quantity_plus_minus' );
function pointify_add_cart_quantity_plus_minus() {
   // Only run this on the single product page
   if ( class_exists( 'WooCommerce' ) ) {
    if ( ! is_product() ) return; ?>
      <script type="text/javascript">  
      jQuery(document).ready(function($){   
         $('form.cart').on( 'click', 'button.plus, button.minus', function() {
            // Get current quantity values
            var qty = $( this ).closest( 'form.cart' ).find( '.qty' );
            var val   = parseFloat(qty.val());
            var max = parseFloat(qty.attr( 'max' ));
            var min = parseFloat(qty.attr( 'min' ));
            var step = parseFloat(qty.attr( 'step' ));
            // Change the value if plus or minus
            if ( $( this ).is( '.plus' ) ) {
               if ( max && ( max <= val ) ) {
                  qty.val( max );
               } else {
                  qty.val( val + step );
               }
            } else {
               if ( min && ( min >= val ) ) {
                  qty.val( min );
               } else if ( val > 1 ) {
                  qty.val( val - step );
               }
            } 
         }); 
      });  
      </script>
   <?php
   }
}

/**
 * First Name and Last Name Field added Start
 */
function pointify_extra_register_fields() {
    return array(
        'first_name' => array('type' => 'text',    'class' => ['form-row-first'], 'required' => 1, 'label' => __('First name', 'pointify') ),
        'last_name'  => array('type' => 'text',    'class' => ['form-row-last'],  'required' => 1, 'label' => __('Last name', 'pointify') ),
    );
}

// Add extra register fields
if(!class_exists('WooCommerce_Simple_Registration')){
    add_action( 'woocommerce_register_form_start', 'pointify_wooc_extra_register_fields' );
}
function pointify_wooc_extra_register_fields() {
    foreach ( pointify_extra_register_fields() as $fkey => $values ) {
    
        $value = isset($_POST['billing_'.$fkey]) ? esc_attr($_POST['billing_'.$fkey]) : '';

        woocommerce_form_field( 'billing_'.$fkey, $values, $value );
    }
}

// Extra register fields validation
if(!class_exists('WooCommerce_Simple_Registration')){
    add_action( 'woocommerce_register_post', 'pointify_wc_validate_reg_form_fields', 10, 3 );
}
function pointify_wc_validate_reg_form_fields( $username, $email, $validation_errors ) {
    foreach ( pointify_extra_register_fields() as $fkey => $values ) {
        if (isset($_POST['billing_'.$fkey]) && empty($_POST['billing_'.$fkey]) && $values['required'] ) {
            $validation_errors->add( 'extra_fields', sprintf('%s is a required field', $values['label']) );
        }
    }
    return $validation_errors;
}

// Save extra register fields values
if(!class_exists('WooCommerce_Simple_Registration')){
    add_action( 'woocommerce_created_customer', 'pointify_wooc_save_extra_register_fields' );
}
function pointify_wooc_save_extra_register_fields( $customer_id ) {
    foreach( pointify_extra_register_fields() as $fkey => $values ) {
        if ( isset($_POST['billing_'.$fkey]) ) {
            $value = in_array($fkey, ['country', 'state']) ? sanitize_text_field($_POST['billing_'.$fkey]) : esc_attr($_POST['billing_'.$fkey]);

            update_user_meta( $customer_id, 'billing_'.$fkey, $value );

            if ( in_array($fkey, ['first_name', 'last_name']) )
                update_user_meta( $customer_id, $fkey, $value );
        }
    }
}

/**
 * First Name and Last Name Field added end
 */

/**
 * Job Listing Feature Image Start
 */

function pointify_featured_image( $fields ) {
    $fields['job']['featured_image'] = array(
        'label'       => __( 'Featured Image', 'pointify' ),
        'description' => __( 'Used for the Job Spotlight display', 'pointify' ),
        'type'        => 'file',
        'required'    => false,
        'placeholder' => '',
        'priority'    => 5,
        'ajax'        => true,
        'allowed_mime_types' => array(
            'jpg'  => 'image/jpeg',
            'jpeg' => 'image/jpeg',
            'gif'  => 'image/gif',
            'png'  => 'image/png',
        ),
    );

    return $fields;
}

add_filter( 'submit_job_form_fields', 'pointify_featured_image' );

function pointify_featured_image_admin( $fields ) {
    $fields['_featured_image'] = array(
        'label'       => __( 'Featured Image', 'pointify' ),
        'description' => __( 'Used for the Job Spotlight display', 'pointify' ),
        'type'        => 'file',
        'priority'    => 5,
    );

    return $fields;
}

add_filter( 'job_manager_job_listing_data_fields', 'pointify_featured_image_admin' );

/**
 * Job Listing Feature Image End
 */

/**
 * Listing Comment Enabled Start
 */

 // Add comment support to the job listing post type - you'll need to enable the comments for old listings manually
add_filter( 'register_post_type_job_listing', 'pointify_register_post_type_job_listing_enable_comments' );
 
function pointify_register_post_type_job_listing_enable_comments( $post_type ) {
  $post_type['supports'][] = 'comments';
  return $post_type;
}
 
// Make comments open by default for new job listings
add_filter( 'submit_job_form_save_job_data', 'pointify_custom_submit_job_form_save_job_data' );
 
function pointify_custom_submit_job_form_save_job_data( $job_data ) {
  $job_data['comment_status'] = 'open';
  return $job_data;
}

/**
 * Listing Comment Enabled End
 */

/**
 * WP Favorites Post Type Start
 */

function pointify_favorites_post_types( $post_types ) {
    // Reset to just job listings.
    $post_types = array( 'job_listing' );
    return $post_types;
}

add_filter( 'astoundify_favorites_post_types', 'pointify_favorites_post_types' );

/**
 * WP Favorites Post Type End
 */

 /**
  * Review Comment Func
  */

function pointify_reviews_get_stars( $comment_id = null ) {
	if ( ! $comment_id ) {
		return false;
	}

	// Get review average.
    $rating = (float) get_comment_meta( $comment_id, 'review_average', true );

	// Display stars based on total average ratings.
	$full_stars = floor( $rating );
	$half_stars = ceil( $rating - $full_stars );
	$empty_stars = wpjmr_get_max_stars() - $full_stars - $half_stars;
	ob_start(); 
?>

    <span class="stars-rating wp-job-manager-star-listing-star-rating">
        <?php echo str_repeat( '<span class="dashicons dashicons-star-filled"></span>', $full_stars ); ?>
        <?php echo str_repeat( '<span class="dashicons dashicons-star-half"></span>', $half_stars ); ?>
        <?php echo str_repeat( '<span class="dashicons dashicons-star-empty"></span>', $empty_stars ); ?>
    </span>

<?php
	return ob_get_clean();
} 

/**
 * Date and time ago func
 */

function pointify_time_ago($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );
    
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }
    
    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';
} 

/**
 * Category thumbnail fields.
 */

function pointify_add_term_fields() {
    wp_enqueue_media();
    ?>
    <div class="form-field term-thumbnail-wrap">
        <label><?php _e( 'Featured Image', 'pointify' ); ?></label>
        <div id="term_thumbnail" style="float: left; margin-right: 10px;"><img src="<?php echo esc_url( wc_placeholder_img_src() ); ?>" width="60px" height="60px" /></div>
        <div style="line-height: 60px;">
            <input type="hidden" id="term_thumbnail_id" name="term_thumbnail_id" />
            <button type="button" class="upload_image_button button"><?php _e( 'Upload/Add image', 'pointify' ); ?></button>
            <button type="button" class="remove_image_button button"><?php _e( 'Remove image', 'pointify' ); ?></button>
        </div>
        <script type="text/javascript">

            // Only show the "remove image" button when needed
            if ( ! jQuery( '#term_thumbnail_id' ).val() ) {
                jQuery( '.remove_image_button' ).hide();
            }

            // Uploading files
            var file_frame;

            jQuery( document ).on( 'click', '.upload_image_button', function( event ) {

                event.preventDefault();

                // If the media frame already exists, reopen it.
                if ( file_frame ) {
                    file_frame.open();
                    return;
                }

                // Create the media frame.
                file_frame = wp.media.frames.downloadable_file = wp.media({
                    title: '<?php esc_html_e( 'Choose an image', 'pointify' ); ?>',
                    button: {
                        text: '<?php esc_html_e( 'Use image', 'pointify' ); ?>'
                    },
                    multiple: false
                });

                // When an image is selected, run a callback.
                file_frame.on( 'select', function() {
                    var attachment = file_frame.state().get( 'selection' ).first().toJSON();
                    if (attachment && attachment.sizes && attachment.sizes.full && attachment.sizes.full.url) {
                            jQuery('#term_thumbnail_id').val(attachment.id);
                            jQuery('#term_thumbnail').find('img').attr('src', attachment.sizes.full.url);
                            jQuery('.remove_image_button').show();
                        } else {
                            // Handle case where no valid attachment is selected
                            console.error('No valid attachment selected');
                        }
                });

                // Finally, open the modal.
                file_frame.open();
            });

            jQuery( document ).on( 'click', '.remove_image_button', function() {
                jQuery( '#term_thumbnail' ).find( 'img' ).attr( 'src', '<?php echo esc_js( wc_placeholder_img_src() ); ?>' );
                jQuery( '#term_thumbnail_id' ).val( '' );
                jQuery( '.remove_image_button' ).hide();
                return false;
            });

        </script>
        <div class="clear"></div>
    </div>
    <?php
} 

add_action( 'job_listing_category_add_form_fields', 'pointify_add_term_fields' );

/**
 * Category Background fields.
 */

 function pointify_add_bg_term_fields() {
    wp_enqueue_media();
    ?>
    <div class="form-field term-thumbnail-wrap">
        <label><?php _e( 'Background Image', 'pointify' ); ?></label>
        <div id="term_background_img" style="float: left; margin-right: 10px;"><img src="<?php echo esc_url( wc_placeholder_img_src() ); ?>" width="60px" height="60px" /></div>
        <div style="line-height: 60px;">
            <input type="hidden" id="term_background_img_id" name="term_background_img_id" />
            <button type="button" class="upload_bg_image_button button"><?php _e( 'Upload/Add image', 'pointify' ); ?></button>
            <button type="button" class="remove_bg_image_button button"><?php _e( 'Remove image', 'pointify' ); ?></button>
        </div>
        <script type="text/javascript">

            // Only show the "remove image" button when needed
            if ( ! jQuery( '#term_background_img_id' ).val() ) {
                jQuery( '.remove_bg_image_button' ).hide();
            }

            // Uploading files
            var file_frame;

            jQuery( document ).on( 'click', '.upload_bg_image_button', function( event ) {

                event.preventDefault();

                // If the media frame already exists, reopen it.
                if ( file_frame ) {
                    file_frame.open();
                    return;
                }

                // Create the media frame.
                file_frame = wp.media.frames.downloadable_file = wp.media({
                    title: '<?php esc_html_e( 'Choose an image', 'pointify' ); ?>',
                    button: {
                        text: '<?php esc_html_e( 'Use image', 'pointify' ); ?>'
                    },
                    multiple: false
                });

                // When an image is selected, run a callback.
                file_frame.on( 'select', function() {
                    var attachment = file_frame.state().get( 'selection' ).first().toJSON();
                    if (attachment && attachment.sizes && attachment.sizes.full && attachment.sizes.full.url) {
                            jQuery('#term_background_img_id').val(attachment.id);
                            jQuery('#term_background_img').find('img').attr('src', attachment.sizes.full.url);
                            jQuery('.remove_bg_image_button').show();
                        } else {
                            // Handle case where no valid attachment is selected
                            console.error('No valid attachment selected');
                        }
                });

                // Finally, open the modal.
                file_frame.open();
            });

            jQuery( document ).on( 'click', '.remove_bg_image_button', function() {
                jQuery( '#term_background_img' ).find( 'img' ).attr( 'src', '<?php echo esc_js( wc_placeholder_img_src() ); ?>' );
                jQuery( '#term_background_img_id' ).val( '' );
                jQuery( '.remove_bg_image_button' ).hide();
                return false;
            });

        </script>
        <div class="clear"></div>
    </div>
    <?php
} 

add_action( 'job_listing_category_add_form_fields', 'pointify_add_bg_term_fields' );

/**
 * Edit category thumbnail field.
 *
 * @param mixed $term Term (category) being edited
 */

function pointify_edit_term_fields( $term ) {
    wp_enqueue_media();
    $thumbnail_id = absint( get_term_meta( $term->term_id, 'thumbnail_id', true ) );

    if ( $thumbnail_id ) {
        $image = wp_get_attachment_thumb_url( $thumbnail_id );
    } else {
        $image = wc_placeholder_img_src();
    }
    ?>
    <tr class="form-field">
        <th scope="row" valign="top"><label><?php _e( 'Featured Image', 'pointify' ); ?></label></th>
        <td>
            <div id="term_thumbnail" style="float: left; margin-right: 10px;"><img src="<?php echo esc_url( $image ); ?>" width="60px" height="60px" /></div>
            <div style="line-height: 60px;">
                <input type="hidden" id="term_thumbnail_id" name="term_thumbnail_id" value="<?php echo esc_attr( $thumbnail_id ); ?>" />
                <button type="button" class="upload_image_button button"><?php _e( 'Upload/Add image', 'pointify' ); ?></button>
                <button type="button" class="remove_image_button button"><?php _e( 'Remove image', 'pointify' ); ?></button>
            </div>
            <script type="text/javascript">

                // Only show the "remove image" button when needed
                if ( '0' === jQuery( '#term_thumbnail_id' ).val() ) {
                    jQuery( '.remove_image_button' ).hide();
                }

                // Uploading files
                var file_frame;

                jQuery( document ).on( 'click', '.upload_image_button', function( event ) {

                    event.preventDefault();

                    // If the media frame already exists, reopen it.
                    if ( file_frame ) {
                        file_frame.open();
                        return;
                    }

                    // Create the media frame.
                    file_frame = wp.media.frames.downloadable_file = wp.media({
                        title: '<?php esc_html_e( 'Choose an image', 'pointify' ); ?>',
                        button: {
                            text: '<?php esc_html_e( 'Use image', 'pointify' ); ?>'
                        },
                        multiple: false
                    });
                  
                    // When an image is selected, run a callback.
                    file_frame.on( 'select', function() {
                       
                        var attachment = file_frame.state().get( 'selection' ).first().toJSON();
                        // console.log(attachment); return false;
                        if (attachment && attachment.sizes && attachment.sizes.full && attachment.sizes.full.url) {
                            jQuery('#term_thumbnail_id').val(attachment.id);
                            jQuery('#term_thumbnail').find('img').attr('src', attachment.sizes.full.url);
                            jQuery('.remove_image_button').show();
                        } else {
                            // Handle case where no valid attachment is selected
                            console.error('No valid attachment selected');
                        }

                    });

                    // Finally, open the modal.
                    file_frame.open();
                });

                jQuery( document ).on( 'click', '.remove_image_button', function() {
                    jQuery( '#term_thumbnail' ).find( 'img' ).attr( 'src', '<?php echo esc_js( wc_placeholder_img_src() ); ?>' );
                    jQuery( '#term_thumbnail_id' ).val( '' );
                    jQuery( '.remove_image_button' ).hide();
                    return false;
                });

            </script>
            <div class="clear"></div>
        </td>
    </tr>
    <?php
}

add_action( 'job_listing_category_edit_form_fields', 'pointify_edit_term_fields', 10, 1 );

/**
 * Edit category backgound field.
 *
 * @param mixed $term Term (category) being edited
 */

 function pointify_edit_bg_term_fields( $term ) {
    wp_enqueue_media();
    $thumbnail_bg_id = absint( get_term_meta( $term->term_id, 'thumbnail_bg_id', true ) );

    if ( $thumbnail_bg_id ) {
        $bg_image = wp_get_attachment_thumb_url( $thumbnail_bg_id );
    } else {
        $bg_image = wc_placeholder_img_src();
    }
    ?>
    <tr class="form-field">
        <th scope="row" valign="top"><label><?php _e( 'Backgound Image', 'pointify' ); ?></label></th>
        <td>
            <div id="term_background_img" class="term_bg_cls" style="float: left; margin-right: 10px;"><img src="<?php echo esc_url( $bg_image ); ?>" width="60px" height="60px" /></div>
            <div style="line-height: 60px;">
                <input type="hidden" id="term_background_img_id" name="term_background_img_id" value="<?php echo esc_attr( $thumbnail_bg_id ); ?>" />
                <button type="button" class="upload_bg_image_button button"><?php _e( 'Upload/Add image', 'pointify' ); ?></button>
                <button type="button" class="remove_bg_image_button button"><?php _e( 'Remove image', 'pointify' ); ?></button>
            </div>
            <script type="text/javascript">

                // Only show the "remove image" button when needed
                if ( '0' === jQuery( '#term_background_img_id' ).val() ) {
                    jQuery( '.remove_bg_image_button' ).hide();
                }

                // Uploading files
                var file_frame_bg;

                jQuery( document ).on( 'click', '.upload_bg_image_button', function( event ) {

                    event.preventDefault();

                    // If the media frame already exists, reopen it.
                    if ( file_frame_bg ) {
                        file_frame_bg.open();
                        return;
                    }

                    // Create the media frame.
                    file_frame_bg = wp.media.frames.downloadable_file = wp.media({
                        title: '<?php esc_html_e( 'Choose an image', 'pointify' ); ?>',
                        button: {
                            text: '<?php esc_html_e( 'Use image', 'pointify' ); ?>'
                        },
                        multiple: false
                    });
                  
                    // When an image is selected, run a callback.
                    file_frame_bg.on( 'select', function() {
                       
                        var attachment_bg = file_frame_bg.state().get( 'selection' ).first().toJSON();
                        // console.log(attachment); return false;
                        if (attachment_bg && attachment_bg.sizes && attachment_bg.sizes.full && attachment_bg.sizes.full.url) {
                            jQuery('#term_background_img_id').val(attachment_bg.id);
                            jQuery('#term_background_img').find('img').attr('src', attachment_bg.sizes.full.url);
                            jQuery('.remove_bg_image_button').show();
                        } else {
                            // Handle case where no valid attachment is selected
                            console.error('No valid attachment selected');
                        }

                    });

                    // Finally, open the modal.
                    file_frame.open();
                });

                jQuery( document ).on( 'click', '.remove_bg_image_button', function() {
                    jQuery( '#term_background_img' ).find( 'img' ).attr( 'src', '<?php echo esc_js( wc_placeholder_img_src() ); ?>' );
                    jQuery( '#term_background_img_id' ).val( '' );
                    jQuery( '.remove_bg_image_button' ).hide();
                    return false;
                });

            </script>
            <div class="clear"></div>
        </td>
    </tr>
    <?php
}

add_action( 'job_listing_category_edit_form_fields', 'pointify_edit_bg_term_fields', 10, 1 );

/**
 * Thumbnail column added to category admin.
 *
 * @param mixed $columns
 * @return array
 */

function pointify_term_columns( $columns ) {
    $new_columns          = array();
    if ( isset( $columns['cb']  ) ) {
        $new_columns['cb']    = $columns['cb'];
        unset( $columns['cb'] );
    }
    $new_columns['thumb'] = __( 'Featured Image', 'pointify' );
    return array_merge( $new_columns, $columns );
}

add_filter( 'manage_edit-job_listing_category_columns', 'pointify_term_columns' );

/**
 * Thumbnail column value added to category admin.
 *
 * @param string $columns
 * @param string $column
 * @param int    $id
 * @return array
 */

function pointify_term_column( $columns, $column, $id ) {
    if ( 'thumb' == $column ) {
        $thumbnail_id = get_term_meta( $id, 'thumbnail_id', true );

        if ( $thumbnail_id ) {
            $image = wp_get_attachment_thumb_url( $thumbnail_id );
        } else {
            $image = wc_placeholder_img_src();
        }

        // Prevent esc_url from breaking spaces in urls for image embeds
        // Ref: http://core.trac.wordpress.org/ticket/23605
        $image = str_replace( ' ', '%20', $image );

        $columns .= '<img src="' . esc_url( $image ) . '" alt="' . esc_attr__( 'Thumbnail', 'pointify' ) . '" class="wp-post-image" height="48" width="48" />';
    }

    return $columns;
}

add_filter( 'manage_job_listing_category_custom_column', 'pointify_term_column', 10, 3 );

/**
 * save_category_fields function.
 *
 * @param mixed  $term_id Term ID being saved
 * @param mixed  $tt_id
 * @param string $taxonomy
 */

 class Pointify_Term_Meta_Handler {

    public $taxonomies = array( 'job_listing_category' );

    public function __construct() {
        add_action( 'created_term', array( $this, 'save_term_fields' ), 10, 3 );
        add_action( 'edited_term', array( $this, 'save_term_fields' ), 10, 3 );
    }

    public function save_term_fields( $term_id, $tt_id = '', $taxonomy = '' ) {
        if ( isset( $_POST['term_thumbnail_id'] ) && in_array( $taxonomy, $this->taxonomies ) ) {
            update_term_meta( $term_id, 'thumbnail_id', absint( $_POST['term_thumbnail_id'] ) );
        }
        if ( isset( $_POST['term_background_img_id'] ) && in_array( $taxonomy, $this->taxonomies ) ) {
            update_term_meta( $term_id, 'thumbnail_bg_id', absint( $_POST['term_background_img_id'] ) );
        }
    }
}

$term_meta_handler = new Pointify_Term_Meta_Handler();

/**
 * Make WordPress aware of custom meta keys.
 *
 * @since 1.0.0
 */

function pointify_tertiary_menu_register_meta() {
    register_meta(
        'post',
        'enable_tertiary_navigation',
        array(
            'sanitize_callback' => 'absint',
            'type'              => 'integer',
        )
    );

}

add_action( 'init', 'pointify_tertiary_menu_register_meta' );

/**
 * Output the tertiary menu.
 *
 * @since 1.0.0
 */
function pointify_tertiary_menu() {
    global $post, $wp_query, $listify_woocommerce;

    $enabled = (bool) get_post_meta( $post->ID, 'enable_tertiary_navigation', true );

    if ( ! $enabled ) {
        return;
    }

    // Hack based on where our page titles fall.
    $wp_query->in_the_loop = false;

    ob_start();

    wp_nav_menu(
        array(
            'theme_location'  => 'tertiary',
            'container_class' => 'navigation-bar tertiary nav-menu',
            'menu_class'      => 'tertiary nav-menu',
            'fallback_cb'     => false,
        )
    );

    $menu = ob_get_clean();

    if ( '' === $menu ) {
        return;
    }

    //if ( listify_has_integration( 'woocommerce' ) ) {
         remove_filter( 'the_title', 'wc_page_endpoint_title' );
    //}
    ?>

    <nav class="tertiary-navigation">
        <div class="container">
            <a href="#" class="navigation-bar-toggle" title="<?php echo esc_attr( 'Tertiary', 'pointify'); ?>">
                <i class="ion-navicon-round"></i>
                <?php echo esc_attr( 'Tertiary', 'pointify'); ?>
            </a>
            <div class="navigation-bar-wrapper">
                <?php echo $menu; // WPCS: XSS ok. ?>
            </div>
        </div>
    </nav><!-- #site-navigation -->

    <?php
        add_filter( 'the_title', 'wc_page_endpoint_title' );

}

// Tertiary.
add_action( 'pointify_page_before', 'pointify_tertiary_menu' );

/**
 * Output the metabox content
 *
 * @since 1.0.0
 */
function pointify_meta_box_settings() {
    $post = get_post();

    $tertiary      = $post->enable_tertiary_navigation;

    $blacklist = array(
        get_option( 'page_for_posts' ),
        get_option( 'page_on_front' ),
        get_option( 'woocommerce_shop_page_id' ),
        get_option( 'job_manager_jobs_page_id' ),
    );
 ?>
    <p>
    <label for="enable_tertiary_navigation">
        <input type="checkbox" name="enable_tertiary_navigation" id="enable_tertiary_navigation" value="1" <?php checked( 1, $tertiary ); ?>>
        <?php esc_html_e( 'Show tertiary navigation bar', 'pointify' ); ?>
    </label>
    </p>
    <?php
}

function pointify_tertiary_add_meta_box() {
    add_meta_box( 'pointify-settings', __( 'Page Settings', 'pointify' ), 'pointify_meta_box_settings', 'page', 'side' );
}   
add_action( 'admin_menu',  'pointify_tertiary_add_meta_box' );    

function pointify_save_post( $post_id ) {
    global $post;

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

    if ( ! is_object( $post ) ) {
        return;
    }

    if ( 'page' !== $post->post_type ) {
        return;
    }

    if ( ! current_user_can( 'edit_post', $post->ID ) ) {
        return;
    }

    $tertiary = isset( $_POST['enable_tertiary_navigation'] ) ? 1 : 0;

    update_post_meta( $post->ID, 'enable_tertiary_navigation', $tertiary );
}

add_action( 'save_post', 'pointify_save_post'  );

/**
 * Add the avatar to the My Account dashboard page.
 *
 * @since 1.0.0
 */
function pointify_add_avatar_to_dashboard() {
    if ( '' != WC()->query->get_current_endpoint() ) {
        return;
    }

    $current_user = wp_get_current_user();

    printf(
        '<div class="woocommerce-MyAccount-avatar">%s</div>',
        get_avatar( $current_user->user_email, 100 )
    );
}

// remove account navigation
remove_action( 'woocommerce_account_navigation', 'woocommerce_account_navigation' );

// add the account avatar
add_action( 'woocommerce_account_navigation', 'pointify_add_avatar_to_dashboard', 99 );

// User Profile
add_action( 'woocommerce_edit_account_form_start', 'pointify_add_avatar_to_account_form' );
function pointify_add_avatar_to_account_form() {
    $current_user_id = get_current_user_id();
    $current_user_avatar_url = get_avatar_url($current_user_id);
    ?>
    <p class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide">
        <?php if ( $current_user_avatar_url ) { ?>
            <div id="avatar_preview_container">
                <div class="avatar-image-section">
                    <?php $gravatar_url = 'https://gravatar.com/'; ?>
                    <a href="<?php echo esc_url($gravatar_url); ?>" target="_blank" class="gravatar-link" title="<?php echo esc_attr( 'Gravatar', 'pointify'); ?>"><i class="fa fa-pencil" aria-hidden="true"></i></a>
                    <img id="avatar_preview" src="<?php echo esc_url( $current_user_avatar_url ); ?>" alt="Preview" style="max-width: 200px;">
                </div>
            </div>
        <?php } ?>
    </p>
    <?php
}

// Account Menu Link

function pointify_account_menu_item_url( $atts, $item, $args ) {
    if ( in_array( 'edit-profile', $item->classes ) ) {
        $atts['href'] = esc_url( wc_get_account_endpoint_url( 'edit-account' ) );
    }elseif( in_array( 'billing-details', $item->classes ) ){
        $billing_url = home_url('/my-account/edit-address/billing');
        $atts['href'] = $billing_url;
    }elseif( in_array( 'edit-address', $item->classes ) ){
        $billing_url = home_url('/my-account/edit-address');
        $atts['href'] = $billing_url;
    }
    return $atts;
}
add_filter( 'nav_menu_link_attributes', 'pointify_account_menu_item_url', 10, 3 );

/**
 * Claim Listing
 */

function submit_claim_link( $job_listing_id ) {

    /* Var */
    $link = '';

    /* Get Submit Claim URL */
    $submit_claim_url = submit_claim_url( $job_listing_id );

    /* Link HTML */
    if ( $submit_claim_url ) {
        $link = '<a href="' . esc_url( $submit_claim_url ) . '" class="claim-listing"><span>' . __( 'Claim this listing', 'pointify' ) . '</span></a>';
    }

    /* Filter The output. */
    return apply_filters( 'wpjmcl_submit_claim_link', $link, $job_listing_id, $submit_claim_url );
}

function submit_claim_url( $job_listing_id ) {

    /* Claim Listing Page URL */
    $submit_claim_page_url = job_manager_get_permalink( 'claim_listing' );
    if ( ! $submit_claim_page_url ) { return false; // page not set.
    }

    /* Job Listing Check */
    if ( ! is_claimable( $job_listing_id ) ) {
        return false;
    }

    /* Check if it's the author of the listing */
    if ( is_user_logged_in() ) {
        $post_obj = get_post( $job_listing_id );
        $curr_user_id = get_current_user_id();
        $can_claim_own_listing = get_option( 'wpjmcl_claim_own_listing', false );
        if ( ! $can_claim_own_listing && $curr_user_id == $post_obj->post_author ) {
            return false;
        }
    }

    /* Build URL */
    $url = add_query_arg( array(
        'listing_id' => $job_listing_id,
    ), $submit_claim_page_url );

    return esc_url( $url );
}

function add_claim_link() {
    $job_listing_id = get_the_ID();
    echo submit_claim_link( $job_listing_id );
}

function is_claimable( $job_listing_id ) {
    $claimable = true;

    /* Check if listing entry exist */
    $post_obj = get_post( $job_listing_id );

    if ( ! $post_obj ) {
        $claimable = false;
    }

    /* Check post type */
    if ( 'job_listing' !== $post_obj->post_type ) {
        $claimable = false;
    }

    /* Check status. */
    if ( 'preview' === $post_obj->post_status ) {
        $claimable = false;
    }

    /* Check if it's already claimed/verified. */
    $claimed = get_post_meta( $job_listing_id, '_claimed', true );

    if ( 1 == $claimed ) {
        $claimable = false;
    }

    return apply_filters( 'wpjmcl_is_claimable', $claimable, $post_obj );
}

function is_claimed() {
    // Claim Listing >= 3.x
    if ( defined( 'WPJMCL_VERSION' ) ) {
        return ! get_post_meta( get_post()->ID, '_claimed', true );
    }

    // Claim Listing < 3.x
    if ( class_exists( 'WP_Job_Manager_Claim_Listing' ) ) {
        if ( method_exists( $this->wpjmcl->listing, 'is_claimable' ) ) {
            return $this->wpjmcl->listing->is_claimable();
        } else {
            return ! $this->wpjmcl->listing->is_claimed();
        }
    }
}

add_action( 'pointify_single_job_listing_actions_start', 'add_claim_link' );

/**
 * Admin notice for premium feature
 */

function pointify_unlock_feature_notice() {
    ?>
    <div class="notice notice-info is-dismissible pointify-unlock-notice">
        <p>
            <?php 
            echo sprintf(
                /* translators: %s: URL to unlock features page */
                __('Enable all the features by setting up compatible plugins. To see compatible plugins, <br><br> <a href="%s" class="button button-primary">Click Here</a>', 'pointify'), 
                esc_url(admin_url('?page=pointify-unlock-feature'))
            ); 
            ?>
        </p>
    </div>

    <?php
}
if ( ! class_exists( 'Extensify' ) ) {
    add_action('admin_notices', 'pointify_unlock_feature_notice');
}

