<?php
/**
 * Blogging Hub functions and definitions
 *
 * @link https://developer.WordPress.org/themes/basics/theme-functions/
 *
 * @package blogging_hub
 */

if ( ! function_exists( 'blogging_hub_setup' ) ) :
	function blogging_hub_setup() {
		add_theme_support( 'automatic-feed-links' );

		load_theme_textdomain( 'blogging-hub', get_template_directory() . '/languages' );

		add_theme_support( 'title-tag' );

		add_theme_support( 'post-thumbnails' );

		add_theme_support( 'woocommerce' );

		register_nav_menus( array(
			'primary_menu' 		=> esc_html__( 'Primary Menu', 'blogging-hub' ),
		) );

		add_theme_support( 'html5', array(
			'search-form',
			'comment-form',
			'comment-list',
			'gallery',
			'caption',
		) );

		// Set up the WordPress core custom background feature.
		add_theme_support( 'custom-background', array(
			'default-color' => 'ffffff'
		) );

		// Add theme support for selective refresh for widgets.
		add_theme_support( 'customize-selective-refresh-widgets' );

		/**
		 * Add support for core custom logo.
		 *
		 * @link https://codex.WordPress.org/Theme_Logo
		 */
		add_theme_support( 'custom-logo', array(
			'height'      => 250,
			'width'       => 250,
			'flex-width'  => true,
			'flex-height' => true,
		) );

		add_editor_style( array( '/assets/css/editor-style.css', blogging_hub_get_fonts_url() ) );

		// Gutenberg support
		add_theme_support( 'editor-color-palette', array(
	       	array(
				'name' => esc_html__( 'Blue', 'blogging-hub' ),
				'slug' => 'blue',
				'color' => '#2c7dfa',
	       	),
	       	array(
	           	'name' => esc_html__( 'Green', 'blogging-hub' ),
	           	'slug' => 'green',
	           	'color' => '#07d79c',
	       	),
	       	array(
	           	'name' => esc_html__( 'Orange', 'blogging-hub' ),
	           	'slug' => 'orange',
	           	'color' => '#ff8737',
	       	),
	       	array(
	           	'name' => esc_html__( 'Black', 'blogging-hub' ),
	           	'slug' => 'black',
	           	'color' => '#2f3633',
	       	),
	       	array(
	           	'name' => esc_html__( 'Grey', 'blogging-hub' ),
	           	'slug' => 'grey',
	           	'color' => '#82868b',
	       	),
	   	));

		add_theme_support( 'align-wide' );
		add_theme_support( 'editor-font-sizes', array(
		   	array(
		       	'name' => esc_html__( 'small', 'blogging-hub' ),
		       	'shortName' => esc_html__( 'S', 'blogging-hub' ),
		       	'size' => 12,
		       	'slug' => 'small'
		   	),
		   	array(
		       	'name' => esc_html__( 'regular', 'blogging-hub' ),
		       	'shortName' => esc_html__( 'M', 'blogging-hub' ),
		       	'size' => 16,
		       	'slug' => 'regular'
		   	),
		   	array(
		       	'name' => esc_html__( 'larger', 'blogging-hub' ),
		       	'shortName' => esc_html__( 'L', 'blogging-hub' ),
		       	'size' => 36,
		       	'slug' => 'larger'
		   	),
		   	array(
		       	'name' => esc_html__( 'huge', 'blogging-hub' ),
		       	'shortName' => esc_html__( 'XL', 'blogging-hub' ),
		       	'size' => 48,
		       	'slug' => 'huge'
		   	)
		));
		add_theme_support('editor-styles');
		add_theme_support( 'wp-block-styles' );

		/**
		 * Demo Import
		 */
		require get_template_directory() . '/apex-library/dashboard/dashboard-settings.php';
	}
endif;
add_action( 'after_setup_theme', 'blogging_hub_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 blogging_hub_content_width() {
	$GLOBALS['content_width'] = apply_filters( 'blogging_hub_content_width', 790 );
}
add_action( 'after_setup_theme', 'blogging_hub_content_width', 0 );

/**
 * Register widget area.
 *
 * @link https://developer.WordPress.org/themes/functionality/sidebars/#registering-a-sidebar
 */
function blogging_hub_widgets_init() {
	register_sidebar( 
		array(
			'name'          => esc_html__( 'Sidebar', 'blogging-hub' ),
			'id'            => 'sidebar-1',
			'description'   => esc_html__( 'Add widgets here.', 'blogging-hub' ),
			'before_widget' => '<section id="%1$s" class="widget %2$s">',
			'after_widget'  => '</section>',
			'before_title'  => '<h2 class="widget-title">',
			'after_title'   => '</h2>',
		) 
	);

	register_sidebar(
		array(
			'name'          => __( 'Footer 1', 'blogging-hub' ),
			'id'            => 'sidebar-2',
			'description'   => __( 'Add widgets here to appear in your footer.', 'blogging-hub' ),
			'before_widget' => '<section id="%1$s" class="widget %2$s">',
			'after_widget'  => '</section>',
			'before_title'  => '<h2 class="widget-title">',
			'after_title'   => '</h2>',
		)
	);

	register_sidebar(
		array(
			'name'          => __( 'Footer 2', 'blogging-hub' ),
			'id'            => 'sidebar-3',
			'description'   => __( 'Add widgets here to appear in your footer.', 'blogging-hub' ),
			'before_widget' => '<section id="%1$s" class="widget %2$s">',
			'after_widget'  => '</section>',
			'before_title'  => '<h2 class="widget-title">',
			'after_title'   => '</h2>',
		)
	);

	register_sidebar(
		array(
			'name'          => __( 'Footer 3', 'blogging-hub' ),
			'id'            => 'sidebar-4',
			'description'   => __( 'Add widgets here to appear in your footer.', 'blogging-hub' ),
			'before_widget' => '<section id="%1$s" class="widget %2$s">',
			'after_widget'  => '</section>',
			'before_title'  => '<h2 class="widget-title">',
			'after_title'   => '</h2>',
		)
	);

	register_sidebar(
		array(
			'name'          => __( 'Footer 4', 'blogging-hub' ),
			'id'            => 'sidebar-5',
			'description'   => __( 'Add widgets here to appear in your footer.', 'blogging-hub' ),
			'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', 'blogging_hub_widgets_init' );

/**
* Enqueue theme fonts.
*/
function blogging_hub_fonts() {
	$fonts_url = blogging_hub_get_fonts_url();

	// Load Fonts if necessary.
	if ( $fonts_url ) {
		require_once get_theme_file_path( 'apex-library/wptt-webfont-loader.php' );
		wp_enqueue_style( 'blogging-hub-fonts', blogging_hub_wptt_get_webfont_url( $fonts_url ), array(), null );
	}
}
add_action( 'wp_enqueue_scripts', 'blogging_hub_fonts', 1 );
add_action( 'enqueue_block_editor_assets', 'blogging_hub_fonts', 1 );

/**
 * Retrieve webfont URL to load fonts locally.
 */
function blogging_hub_get_fonts_url() {
	$font_families = array(
		'Outfit:wght@100..900',
	);

	$query_args = array(
		'family'  => urlencode( implode( '|', $font_families ) ),
		'subset'  => urlencode( 'latin,latin-ext' ),
		'display' => urlencode( 'swap' ),
	);

	return apply_filters( 'blogging_hub_get_fonts_url', add_query_arg( $query_args, 'https://fonts.googleapis.com/css2' ) );
}

/**
 * Enqueue scripts and styles.
 */
function blogging_hub_scripts() {

	wp_enqueue_style( 'bootstrap-css', get_template_directory_uri() . '/assets/css/bootstrap.css' );

	wp_enqueue_style( 'bootstrap-icon', get_template_directory_uri() . '/assets/css/bootstrap-icons.css' );

	wp_enqueue_style( 'owl-carousel-css', get_template_directory_uri() . '/assets/css/owl.carousel.css' );

	wp_enqueue_style( 'blogging-hub-navigation-css', get_template_directory_uri() . '/assets/css/navigation.css' );

	wp_enqueue_style( 'blogging-hub-blocks', get_template_directory_uri() . '/assets/css/blocks.css' );
	
	wp_enqueue_style( 'font-awesome-css', get_template_directory_uri().'/assets/css/fontawesome-all.css' );

	wp_enqueue_style( 'blogging-hub-style', get_stylesheet_uri() );
	wp_style_add_data('blogging-hub-style', 'rtl', 'replace');

	wp_enqueue_script( 'blogging-hub-skip-link-focus-fix', get_template_directory_uri() . '/assets/js/skip-link-focus-fix.js', array(), '20151215', true );

	wp_enqueue_script( 'bootstrap-js', get_template_directory_uri() . '/assets/js/bootstrap.js', array('jquery'), '1.0', true );

	wp_enqueue_script( 'owl-carousel-js', get_template_directory_uri() . '/assets/js/owl.carousel.js', array('jquery'), '1.0', true );

	wp_enqueue_script( 'blogging-hub-navigation-js', get_template_directory_uri() . '/assets/js/navigation.js', array('jquery'), '1.0', true );
	
	wp_enqueue_script( 'blogging-hub-custom-script', get_template_directory_uri() . '/assets/js/theme-custom-script.js', array('jquery'), '20151215', true );

	// Localize script for AJAX
	wp_localize_script( 'blogging-hub-custom-script', 'blogging_hub_ajax_object', array(
		'ajax_url' => admin_url( 'admin-ajax.php' ),
		'nonce'    => wp_create_nonce( 'blogging_hub_filter_nonce' )
	) );

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

/**
 * Enqueue editor styles for Gutenberg
 *
 * @since Blogging Hub 1.0.0
 */
function blogging_hub_block_editor_styles() {
	// Block styles.
	wp_enqueue_style( 'blogging-hub-block-editor-style', get_theme_file_uri( '/assets/css/editor-blocks.css' ) );
	// Add custom fonts.
	wp_enqueue_style( 'blogging-hub-fonts', blogging_hub_get_fonts_url(), array(), null );
}
add_action( 'enqueue_block_editor_assets', 'blogging_hub_block_editor_styles' );

/**
 * Checkbox sanitization callback example.
 */
function blogging_hub_sanitize_checkbox( $checked ) {
	// Boolean check.
	return ( ( isset( $checked ) && true == $checked ) ? true : false );
}

/**
 * Removing category text from category page.
 */
function blogging_hub_category_title( $title ) {
    if ( is_category() ) {
        $title = single_cat_title( '', false );
    }
    return $title;
}
add_filter( 'get_the_archive_title', 'blogging_hub_category_title' );

/*radio button sanitization*/
function blogging_hub_sanitize_choices( $input, $setting ) {
    global $wp_customize;
    $control = $wp_customize->get_control( $setting->id );
    if ( array_key_exists( $input, $control->choices ) ) {
        return $input;
    } else {
        return $setting->default;
    }
}

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

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

/**
 * Functions which enhance the theme by hooking into WordPress.
 */
require get_template_directory() . '/apex-library/template-functions.php';

/**
 * Customizer additions.
 */
require get_template_directory() . '/apex-library/customizer.php';

/**
 * SVG icons functions and filters.
 */
require get_template_directory() . '/apex-library/icon-functions.php';

/**
 * Get Started Page.
 */
require get_template_directory() . '/apex-library/theme-info.php';

function blogging_hub_set_post_views($postID) {
    $blogging_hub_count_key = 'post_views_count';
    $blogging_hub_count = get_post_meta($postID, $blogging_hub_count_key, true);
    if($blogging_hub_count == ''){
        $blogging_hub_count = 1;
        update_post_meta($postID, $blogging_hub_count_key, $blogging_hub_count);
    } else {
        $blogging_hub_count++;
        update_post_meta($postID, $blogging_hub_count_key, $blogging_hub_count);
    }
}

// Get post views
function blogging_hub_get_post_views($postID){
    $blogging_hub_count_key = 'post_views_count';
    $blogging_hub_count = get_post_meta($postID, $blogging_hub_count_key, true);
    return $blogging_hub_count ? $blogging_hub_count . ' ' : '0 ';
}

// Hook into wp_head to count on single posts
function blogging_hub_track_post_views($post_id) {
    if (!is_single()) return;
    if (empty($post_id)) {
        global $post;
        $post_id = $post->ID;
    }
    blogging_hub_set_post_views($post_id);
}
add_action('wp_head', 'blogging_hub_track_post_views');

function blogging_hub_get_categories() {
    $blogging_hub_cats = get_categories();
    $blogging_hub_cat_choices = array();

    $blogging_hub_cat_choices[''] = __('Select Category', 'blogging-hub');

    foreach ($blogging_hub_cats as $blogging_hub_cat) {
        $blogging_hub_cat_choices[$blogging_hub_cat->term_id] = $blogging_hub_cat->name;
    }

    return $blogging_hub_cat_choices;
}

function blogging_hub_get_post_rating($post_id) {

    // 1. Custom Field (Manual rating)
    $blogging_hub_rating = get_post_meta($post_id, 'post_rating', true);

    if ($blogging_hub_rating) {
        return floatval($blogging_hub_rating);
    }

    // 2. Based on comments count
    $blogging_hub_comments = get_comments_number($post_id);

    if ($blogging_hub_comments > 0) {
        return min(5, round(3 + ($blogging_hub_comments / 5), 1)); 
    }

    // 3. Default
    return 4.5;
}

// =============================
// ADD IMAGE FIELD TO CATEGORY
// =============================
function blogging_hub_category_add_image($taxonomy) {
	?>
	<div class="form-field term-group">
		<label for="category-image"><?php esc_html_e('Category Image', 'blogging-hub'); ?></label>
		<input type="hidden" id="category-image" name="category_image" value="">
		<div id="category-image-wrapper"></div>
		<p>
			<button type="button" class="button button-secondary upload_category_image_button">
				<?php esc_html_e('Add Image', 'blogging-hub'); ?>
			</button>
			<button type="button" class="button button-secondary remove_category_image_button">
				<?php esc_html_e('Remove Image', 'blogging-hub'); ?>
			</button>
		</p>
	</div>
	<?php
	}
add_action('category_add_form_fields', 'blogging_hub_category_add_image', 10, 2);

function blogging_hub_category_edit_image($term, $taxonomy) {

    $blogging_hub_image_id = get_term_meta($term->term_id, 'category_image', true); ?>
	<tr class="form-field term-group-wrap">
		<th scope="row">
			<label for="category-image"><?php esc_html_e('Category Image', 'blogging-hub'); ?></label>
		</th>
		<td>
			<input type="hidden" id="category-image" name="category_image" value="<?php echo esc_attr($blogging_hub_image_id); ?>">

			<div id="category-image-wrapper">
				<?php if ($blogging_hub_image_id) echo wp_get_attachment_image($blogging_hub_image_id, 'thumbnail'); ?>
			</div>

			<p>
				<button type="button" class="button button-secondary upload_category_image_button">
					<?php esc_html_e('Add Image', 'blogging-hub'); ?>
				</button>
				<button type="button" class="button button-secondary remove_category_image_button">
					<?php esc_html_e('Remove Image', 'blogging-hub'); ?>
				</button>
			</p>
		</td>
	</tr>
<?php
}
add_action('category_edit_form_fields', 'blogging_hub_category_edit_image', 10, 2);

function blogging_hub_save_category_image($term_id) {
    if (isset($_POST['category_image'])) {
        update_term_meta($term_id, 'category_image', absint($_POST['category_image']));
    }
}
add_action('created_category', 'blogging_hub_save_category_image', 10, 2);
add_action('edited_category', 'blogging_hub_save_category_image', 10, 2);

add_action('admin_enqueue_scripts', function($hook){
    if ($hook === 'edit-tags.php' || $hook === 'term.php') {
        wp_enqueue_media();
    }
});

add_action('admin_footer', function() {
	?>
	<script>
	jQuery(function($){
	
		$(document).on('click', '.upload_category_image_button', function(e){
			e.preventDefault();
	
			var button = $(this);
			var wrapper = button.closest('td, .form-field');
	
			// ALWAYS NEW FRAME (IMPORTANT FIX 🔥)
			var frame = wp.media({
				title: 'Select Category Image',
				button: { text: 'Use this image' },
				library: { type: 'image' },
				multiple: false
			});
	
			frame.on('select', function(){
				var attachment = frame.state().get('selection').first().toJSON();
	
				wrapper.find('input[name="category_image"]').val(attachment.id);
	
				wrapper.find('#category-image-wrapper').html(
					'<img src="'+attachment.url+'" style="max-width:100px;">'
				);
			});
	
			frame.open();
		});
	
		$(document).on('click', '.remove_category_image_button', function(){
			var wrapper = $(this).closest('td, .form-field');
	
			wrapper.find('input[name="category_image"]').val('');
			wrapper.find('#category-image-wrapper').html('');
		});
	
	});
	</script>
	<?php
});


// Add admin notice
function blogging_hub_admin_notice() { 
    global $pagenow;

    $blogging_hub_theme = wp_get_theme();
    $blogging_hub_meta  = get_option('blogging_hub_admin_notice');
    $blogging_hub_screen                  = get_current_screen();

    if ( !$blogging_hub_meta ) {

        if ( is_network_admin() || ! current_user_can('manage_options') ) {
            return;
        }

        if ( $blogging_hub_screen->base !== 'appearance_page_blogging-hub-info' ) {

            $blogging_hub_version = $blogging_hub_theme->get('Version');
            ?>

            <div class="notice blogging-hub-notice-main-div">

                <!-- Dismiss -->
				<a class="blogging-hub-dismiss" href="<?php echo esc_url( add_query_arg( 'blogging_hub_admin_notice', '1' ) ); ?>">
					<span class="dashicons dashicons-no-alt"></span>
				</a>

                <!-- Header -->
                <div class="blogging-hub-notice">
                    <div class="blogging-hub-notice-title">
                        <h1><?php echo esc_html( $blogging_hub_theme->get('Name') ); ?></h1>
                        <span>
                            <?php esc_html_e('Version', 'blogging-hub'); ?>
                            <?php echo esc_html($blogging_hub_version); ?>
                        </span>
                    </div>

                    <div class="blogging-hub-notice-buttons">
                        <a href="<?php echo esc_url( admin_url( 'themes.php?page=blogging-hub-info' ) ); ?>" target="_blank" class="button">
                            <?php esc_html_e('Get Started', 'blogging-hub'); ?>
                        </a>

                        <a href="<?php echo esc_url('https://www.apexthemes.net/products/blogging-wordpress-theme/'); ?>" target="_blank" class="button button-primary">
                            <?php esc_html_e('Get Premium', 'blogging-hub'); ?>
                        </a>

                        <a href="<?php echo esc_url('https://trial.apexthemes.net/blogging-hub/'); ?>" target="_blank" class="button">
                            <?php esc_html_e('Live Demo', 'blogging-hub'); ?>
                        </a>
                    </div>

					<div class="blogging-hub-notice-logo">
						<img src="<?php echo esc_url( get_stylesheet_directory_uri() . '/assets/images/apex-logo.png' ); ?>" alt="<?php esc_attr_e( 'Theme Screenshot', 'blogging-hub' ); ?>">
                    </div>
                </div>

            </div>

            <?php
        }
    }
}
add_action('admin_notices', 'blogging_hub_admin_notice');

if( ! function_exists( 'blogging_hub_update_admin_notice' ) ) :
/**
 * Updating admin notice on dismiss
*/
function blogging_hub_update_admin_notice(){
    if ( isset( $_GET['blogging_hub_admin_notice'] ) && $_GET['blogging_hub_admin_notice'] = '1' ) {
        update_option( 'blogging_hub_admin_notice', true );
    }
}
endif;
add_action( 'admin_init', 'blogging_hub_update_admin_notice' );


add_action('after_switch_theme', 'blogging_hub_setup_options');
function blogging_hub_setup_options () {
    update_option('blogging_hub_admin_notice', FALSE );
}

function blogging_hub_notice_styles() {
	wp_enqueue_style(
		'blogging-hub-notice-function',
		get_stylesheet_directory_uri() . '/assets/css/notice-function.css',
		array(),
		'1.0.0'
	);
}
add_action( 'admin_enqueue_scripts', 'blogging_hub_notice_styles' );