<?php
/**
 * bottleup functions and definitions.
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @package bottleup
 */

if ( ! function_exists( 'bottleup_setup' ) ) :
/**
 * Sets up theme defaults and registers support for various WordPress features.
 *
 * Note that this function is hooked into the after_setup_theme hook, which
 * runs before the init hook. The init hook is too late for some features, such
 * as indicating support for post thumbnails.
 */
function bottleup_setup() {
	/*
	 * Make theme available for translation.
	 * Translations can be filed in the /languages/ directory.
	 * If you're building a theme based on bottleup, use a find and replace
	 * to change 'bottleup' to the name of your theme in all the template files.
	 */
	load_theme_textdomain( 'bottleup', get_template_directory() . '/languages' );

	// Add default posts and comments RSS feed links to head.
	add_theme_support( 'automatic-feed-links' );

	/*
	 * Let WordPress manage the document title.
	 * By adding theme support, we declare that this theme does not use a
	 * hard-coded <title> tag in the document head, and expect WordPress to
	 * provide it for us.
	 */
	add_theme_support( 'title-tag' );

	/*
	 * Enable support for Post Thumbnails on posts and pages.
	 *
	 * @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/
	 */
	add_theme_support( 'post-thumbnails' );

	// This theme uses wp_nav_menu() in one location.
	register_nav_menus( array(
		'primary' => esc_html__( 'Primary', 'bottleup' ),
	) );

	/*
	 * Switch default core markup for search form, comment form, and comments
	 * to output valid HTML5.
	 */
	add_theme_support( 'html5', array(
		'search-form',
		'comment-form',
		'comment-list',
		'gallery',
		'caption',
	) );

	/*
	 * Enable support for Post Formats.
	 * See https://developer.wordpress.org/themes/functionality/post-formats/
	 */
	add_theme_support( 'post-formats', array(
		'aside',
		'image',
		'video',
		'quote',
		'link',
	) );

	// Set up the WordPress core custom background feature.
	add_theme_support( 'custom-background', apply_filters( 'bottleup_custom_background_args', array(
		'default-color' => 'ffffff',
		'default-image' => '',
	) ) );
}
endif;
add_action( 'after_setup_theme', 'bottleup_setup' );

/**
 * Set the content width in pixels, based on the theme's design and stylesheet.
 *
 * Priority 0 to make it available to lower priority callbacks.
 *
 * @global int $content_width
 */
function bottleup_content_width() {
	$GLOBALS['content_width'] = apply_filters( 'bottleup_content_width', 640 );
}
add_action( 'after_setup_theme', 'bottleup_content_width', 0 );

/**
 * Register widget area.
 *
 * @link https://developer.wordpress.org/themes/functionality/sidebars/#registering-a-sidebar
 */
function bottleup_widgets_init() {
	register_sidebar( array(
		'name'          => esc_html__( 'Sidebar', 'bottleup' ),
		'id'            => 'sidebar-1',
		'description'   => '',
		'before_widget' => '<section id="%1$s" class="widget %2$s">',
		'after_widget'  => '</section>',
		'before_title'  => '<h2 class="widget-title">',
		'after_title'   => '</h2>',
	) );
}
add_action( 'widgets_init', 'bottleup_widgets_init' );

/**
 * Enqueue scripts and styles.
 */
function bottleup_scripts() {
	wp_enqueue_style( 'bootstrap-css', get_template_directory_uri() . '/bootstrap/css/bootstrap.min.css');
	wp_enqueue_script( 'bootstrap-min-js', get_template_directory_uri() . '/bootstrap/js/bootstrap.min.js', array(), '20160202', true );

	wp_enqueue_script( 'scotch-min-js', get_template_directory_uri() . '/js/scotchPanels.min.js', array('jquery'), '20160208', true );

	wp_enqueue_style( 'bottleup-style', get_stylesheet_uri() );
	//wp_enqueue_script( 'bottleup-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '20120206', true );
	wp_enqueue_script( 'bottleup-skip-link-focus-fix', get_template_directory_uri() . '/js/skip-link-focus-fix.js', array(), '20130115', true );

	if(is_page('challenges')) {
		wp_register_script( 'challenge-js',get_template_directory_uri() . '/js/challenge.js', array('jquery'), '1.0', true );
		wp_localize_script( 'challenge-js', 'challengesAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
		wp_enqueue_script( 'challenge-js' );
	}

	wp_enqueue_script( 'custom-js', get_template_directory_uri() . '/js/custom.js', array('jquery'), '20160208', true );

	wp_enqueue_style( 'main-css', get_template_directory_uri() . '/css/main.css');

	if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
		wp_enqueue_script( 'comment-reply' );
	}
}
add_action( 'wp_enqueue_scripts', 'bottleup_scripts' );

/**
 * Implement the Custom Header feature.
 */
require get_template_directory() . '/inc/custom-header.php';

/**
 * Custom template tags for this theme.
 */
require get_template_directory() . '/inc/template-tags.php';

/**
 * Custom functions that act independently of the theme templates.
 */
require get_template_directory() . '/inc/extras.php';

/**
 * Customizer additions.
 */
require get_template_directory() . '/inc/customizer.php';

/**
 * Load Jetpack compatibility file.
 */
require get_template_directory() . '/inc/jetpack.php';

/**
 * Block public access to site with some exceptions.
 */
function hwdsb_block_access() {
	if ( is_user_logged_in() ) {
		return;
	}

//	$redirect = is_buddypress();
	$redirect = true;

	$site_path = bp_core_get_site_path();

	// subdirectory install
	if ( is_multisite() && ! is_subdomain_install() ) {
		global $current_blog;
		$site_path = $current_blog->path;
	}

	// strip site path from URI
	$path = substr( esc_url( $_SERVER['REQUEST_URI'] ), strlen( $site_path ) );

//	if ( ! $redirect && function_exists( 'is_bbpress' ) ) {
//		$redirect = is_bbpress();
//	}

	// redirect if we match a condition and we're not on the homepage
	if ( (bool) $redirect === true && $path != '' ) {
		bp_core_redirect( bp_core_get_root_domain() );
		exit();
	}

}
add_action( 'template_redirect', 'hwdsb_block_access', 0 );

/**
 * Redirect after login
 */
add_filter( 'login_redirect', 'my_login_redirect', 10, 3 );
function my_login_redirect( $redirect_to, $request, $user ) {
	if( $user && is_object( $user ) && is_a( $user, 'WP_User' ) ) {
		return get_permalink(2);
	}
}

/**
 * Change activity title
 */
add_filter( 'bp_get_directory_title', 'rtp_change_activity_title', 999 );
function rtp_change_activity_title( $title ) {
	if ( $title == __( 'Site-Wide Activity', 'bottleup' ) ) {
		$title = __( 'Timeline', 'bottleup' );
	}
	return $title;
}

/**
 * Remove Admin bar header in Frontend
 */
function hide_admin_bar_from_front_end(){
	if (is_blog_admin()) {
		return true;
	}
	remove_action( 'wp_head', '_admin_bar_bump_cb' );
	return false;
}
add_filter( 'show_admin_bar', 'hide_admin_bar_from_front_end' );

/**
 * Remove permalink link from time since on activity list
 */
add_filter( 'bp_activity_permalink', 'homepagers_activity_permalink',10,2 );
function homepagers_activity_permalink( $time_since, $activity ){
	$action =  $activity->action;
	$action = preg_replace(array('"<a href(.*?)>"', '"</a>"'), array('<div class="username">','</div>'), $action);
	$time_since = '<span class="time-since">' . bp_core_time_since( $activity->date_recorded ) . '</span>';
	$content = sprintf( '%1$s %2$s', $action,  $time_since );
	return $content;
}

// Extend login session
add_filter( 'auth_cookie_expiration', 'keep_me_logged_in_for_month' );
function keep_me_logged_in_for_month( $expirein ) {
	return 2592000; // 30 days
}


remove_action( 'wp_ajax_activity_mark_fav', 'bp_legacy_theme_mark_activity_favorite' );
remove_action( 'wp_ajax_nopriv_activity_mark_fav', 'bp_legacy_theme_mark_activity_favorite' );
function ccsm_mark_activity_favorite() {
	$my_fav_count = bp_activity_get_meta( $_POST['id'], 'favorite_count' );
	if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) )
		return;

	if ( bp_activity_add_user_favorite( $_POST['id'] ) ) {
		_e( 'This can\'t work', 'buddypress' ); echo ('<span>'.($my_fav_count+1).'</span>');
	} else {
		_e( 'This can work', 'buddypress' ); echo ('<span>'.($my_fav_count).'</span>');
	}

	exit;
}
add_action( 'wp_ajax_activity_mark_fav', 'ccsm_mark_activity_favorite' );
add_action( 'wp_ajax_nopriv_activity_mark_fav', 'ccsm_mark_activity_favorite' );


remove_action( 'wp_ajax_activity_mark_fav', 'bp_legacy_theme_unmark_activity_favorite' );
remove_action( 'wp_ajax_nopriv_activity_mark_fav', 'bp_legacy_theme_unmark_activity_favorite' );
function ccsm_unmark_activity_favorite() {
	$my_fav_count = bp_activity_get_meta( $_POST['id'], 'favorite_count' );

	// Bail if not a POST action
	if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) )
		return;

	if ( bp_activity_remove_user_favorite( $_POST['id'] ) ) {
		_e('This can work', 'buddypress' ); echo ('<span>'.($my_fav_count-1).'</span>');
	} else {
		_e( 'This can\'t work', 'buddypress' ); echo ('<span>'.($my_fav_count).'</span>');
	}
	exit;
}
add_action( 'wp_ajax_activity_mark_unfav', 'ccsm_unmark_activity_favorite' );
add_action( 'wp_ajax_nopriv_activity_mark_unfav', 'ccsm_unmark_activity_favorite' );

/*
 * CC Admin restrictions
 */
// Remove admin Dashboard and Profile pages for chat agents
if ( ! function_exists('hide_the_dashboard_and_profile') ) {
	function hide_the_dashboard_and_profile()
	{
		global $current_user;
		if (is_array($current_user->roles)) {
			if (($current_user->ID === 2) || ($current_user->ID === 3)) {
				remove_menu_page('index.php');
				remove_menu_page('edit.php');
				remove_menu_page('upload.php');
				remove_menu_page('edit.php?post_type=page');
				remove_menu_page('edit-comments.php');
				remove_menu_page('themes.php');
				remove_menu_page('plugins.php');
				remove_menu_page('users.php');
				remove_menu_page('rtmedia-settings');
				remove_menu_page('profile-builder');
				remove_menu_page('tools.php');
				remove_menu_page('options-general.php');
				remove_menu_page('edit.php?post_type=acf');
				remove_menu_page('tools.php');
			}
		}
	}
	add_action('admin_menu', 'hide_the_dashboard_and_profile', 9999);
}
// Remove unnecessary admin functions for Chat agents
if ( ! function_exists('galleria_admin_bar_render') ) {
	function galleria_admin_bar_render()
	{
		global $current_user;
		if (is_array($current_user->roles)) {
			if (($current_user->ID === 2) || ($current_user->ID === 3)) {
				global $wp_admin_bar;
				$wp_admin_bar->remove_menu('wp-logo');          // Remove the WordPress logo
				$wp_admin_bar->remove_menu('about');            // Remove the about WordPress link
				$wp_admin_bar->remove_menu('wporg');            // Remove the WordPress.org link
				$wp_admin_bar->remove_menu('documentation');    // Remove the WordPress documentation link
				$wp_admin_bar->remove_menu('support-forums');   // Remove the support forums link
				$wp_admin_bar->remove_menu('feedback');         // Remove the feedback link
				$wp_admin_bar->remove_menu('site-name');        // Remove the site name menu
				$wp_admin_bar->remove_menu('view-site');        // Remove the view site link
				$wp_admin_bar->remove_menu('updates');          // Remove the updates link
				$wp_admin_bar->remove_menu('comments');         // Remove the comments link
				$wp_admin_bar->remove_menu('new-content');      // Remove the content link
				$wp_admin_bar->remove_menu('w3tc');             // If you use w3 total cache remove the performance link
				//$wp_admin_bar->remove_menu('my-account');       // Remove the user details tab
			}
		}
	}
	add_action('wp_before_admin_bar_render', __NAMESPACE__ . '\\galleria_admin_bar_render');
}

/* ---------------------------------------------------------------------------
 * Ajax save_challenge
 * --------------------------------------------------------------------------- */
if( ! function_exists( 'save_challenge' ) ) {

	add_action("wp_ajax_save_challenge", "save_challenge");
	add_action("wp_ajax_nopriv_save_challenge", "save_challenge");

	function save_challenge() {

		if ( !wp_verify_nonce( $_REQUEST['nonce'], "save_challenge_nonce")) {
			exit("No naughty business please");
		}
		$title = stripslashes($_REQUEST['hashtag']);
		$description = stripslashes($_REQUEST['description']);
		$hashtag = preg_replace('/[^A-Za-z0-9]/', '', $title);
		$result['type'] = "error";

		if (!empty($title) && !empty($description)) {
			$post_id = wp_insert_post(array (
				'post_type' => 'challenge',
				'post_title' => $title,
				'post_status' => 'publish',
				'comment_status' => 'closed',
				'ping_status' => 'closed'
			));
			if ($post_id) {
				// insert post meta
				add_post_meta($post_id, 'hashtag', $hashtag);
				add_post_meta($post_id, 'challenge_description', $description);
			}
			$result['type'] = "success";
		}

		if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
			$result = json_encode($result);
			echo $result;
		}
		else {
			header("Location: ".$_SERVER["HTTP_REFERER"]);
		}
		die();
	}
} /* End if function_exists */

/* ---------------------------------------------------------------------------
 * Ajax lock_challenge
 * --------------------------------------------------------------------------- */
if( ! function_exists( 'lock_challenge' ) ) {

	add_action("wp_ajax_lock_challenge", "lock_challenge");
	add_action("wp_ajax_nopriv_lock_challenge", "lock_challenge");

	function lock_challenge() {

		if ( !wp_verify_nonce( $_REQUEST['nonce'], "lock_challenge_nonce")) {
			exit("No naughty business please");
		}
		$post_id = stripslashes($_REQUEST['post_id']);
		$status = stripslashes($_REQUEST['status']);
		$new_status = ($status === "archive")?"active":"archive";
		$result['type'] = "error";

		if (!empty($post_id)) {
			// update post meta
			update_post_meta($post_id, 'status', $new_status);
			$result['type'] = "success";
		}

		if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
			$result = json_encode($result);
			echo $result;
		}
		else {
			header("Location: ".$_SERVER["HTTP_REFERER"]);
		}
		die();
	}
} /* End if function_exists */

/* ---------------------------------------------------------------------------
 * Ajax hide_challenge
 * --------------------------------------------------------------------------- */
if( ! function_exists( 'hide_challenge' ) ) {

	add_action("wp_ajax_hide_challenge", "hide_challenge");
	add_action("wp_ajax_nopriv_hide_challenge", "hide_challenge");

	function hide_challenge() {

		if ( !wp_verify_nonce( $_REQUEST['nonce'], "hide_challenge_nonce")) {
			exit("No naughty business please");
		}
		$post_id = stripslashes($_REQUEST['post_id']);
		$result['type'] = "error";

		if (!empty($post_id)) {
			// update post
			wp_update_post(array (
				'ID' => $post_id,
				'post_status' => 'draft'
			));
			$result['type'] = "success";
		}

		if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
			$result = json_encode($result);
			echo $result;
		}
		else {
			header("Location: ".$_SERVER["HTTP_REFERER"]);
		}
		die();
	}
} /* End if function_exists */