<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}
define( 'HELLO_ELEMENTOR_CHILD_VERSION', '1.12.2' );

// Load child theme css and optional scripts
function hello_elementor_child_enqueue_scripts() {
	wp_enqueue_style( 'hello-elementor-child-style', get_stylesheet_directory_uri() . '/style.css',
		[], HELLO_ELEMENTOR_CHILD_VERSION
	);
}
add_action( 'wp_enqueue_scripts', 'hello_elementor_child_enqueue_scripts' );

// Add style such as fonts to wp admin and elementor
add_action('admin_enqueue_scripts', 'mn_admin_styles');
add_action('elementor/editor/before_enqueue_scripts', 'mn_admin_styles');
function mn_admin_styles() {
  wp_enqueue_style( 'admin-style', get_stylesheet_directory_uri() . '/admin.css' );
}

// Customize
require_once('customizer.php');

// Mavaranet Admin widget panel
function mn_admin_widget_panel() {
    wp_add_dashboard_widget(
        'mn_widget_panel',
        'ماورانت',
        'mn_widget_panel_content'
    );
}
function mn_widget_panel_content() {
    
    ?>
    <img src="<?php echo get_stylesheet_directory_uri(); ?>/copyright-logo.svg" />
    <div>این سایت بطور اختصاصی توسط ماورانت طراحی و توسعه داده شده است.</div>
    <?php
    
}
add_action('wp_dashboard_setup', 'mn_admin_widget_panel');


// Preload
function mn_preload(){
    if ( is_front_page() ){ ?>
    <link rel="alternate" href="<?php echo get_site_url(); ?>" hreflang="fa-ir" />
    <? } elseif (is_single()) { $f_img_url = get_the_post_thumbnail_url(get_the_ID(),'thumbnail'); ?>
    <link rel="preload" as="image" href="<? echo $f_img_url; ?>" />
    <? } else { ?>
    <? }
}
add_action('wp_head','mn_preload');

// Remove Wordpress Version
function mn_remove_version() {
    return '';
}
add_filter('the_generator', 'mn_remove_version');

// Remove URL form Comments Field
add_filter('comment_form_default_fields', 'mn_remove_url_email_comments');
function mn_remove_url_email_comments($fields)
{
  if(isset($fields['url'])) {
	unset($fields['url']);
  }
  return $fields;
}

// Do Not Store URL Commenter IP
add_filter( 'pre_comment_user_ip', 'mn_not_store_commentsip' );
function mn_not_store_commentsip( $comment_author_ip ) {
	return '';
}

// Add Mavaranet Font Group
add_filter( 'elementor/fonts/groups', function( $font_groups ) {
	$font_groups['Mavaranet'] = 'Mavaranet';
	return $font_groups;
} );
// Add Persian Font to Elementor
add_filter( 'elementor/fonts/additional_fonts', function( $additional_fonts ) {
	$additional_fonts['IRANSansX'] = 'Mavaranet';
	$additional_fonts['IRANYekanX'] = 'Mavaranet';
	$additional_fonts['Anjoman'] = 'Mavaranet';
	$additional_fonts['Dana'] = 'Mavaranet';
	$additional_fonts['Kalameh'] = 'Mavaranet';
	$additional_fonts['Modam'] = 'Mavaranet';
	$additional_fonts['Morabba'] = 'Mavaranet';
	$additional_fonts['Peyda'] = 'Mavaranet';
	$additional_fonts['Aviny'] = 'Mavaranet';
	$additional_fonts['rokh'] = 'Mavaranet';
	$additional_fonts['YekanBakh'] = 'Mavaranet';
	$additional_fonts['Farhang'] = 'Mavaranet';

	return $additional_fonts;
} );

// Fallback image for featured image of posts
add_filter( 'get_post_metadata', 'mn_fallback_featured_image', 100, 4 );
function mn_fallback_featured_image($metadata, $object_id, $meta_key, $single){
    // Here is the catch, add additional controls if needed (post_type, etc)
    $meta_needed = '_thumbnail_id';
    if ( isset( $meta_key ) && $meta_needed == $meta_key ){
        remove_filter( 'get_post_metadata', 'mn_fallback_featured_image', 100 );
        $current_meta = get_post_meta( $object_id, $meta_needed, TRUE );
        add_filter('get_post_metadata', 'mn_fallback_featured_image', 100, 4);

        // Do what you need to with the meta value - translate, append, etc
        $fb_img = get_theme_mod( 'mn_fallback_image' );
        if($current_meta < 1 && $fb_img > 1) {
            return $fb_img;
        }
        return $current_meta;
    }
    // Return original if the check does not pass
    return $metadata;
}

// Change of Avatars of Comments Section 
add_action('wp_head','mn_new_avatar');
function mn_new_avatar () {
    $img_id = get_theme_mod( 'mn_clinet_avatar' );
	$avatar = wp_get_attachment_url($img_id);
    if ( is_single() && $img_id > 1){ ?>
    <style>
        #comments .bypostauthor .comment-author:before { background-image: url( <?php echo $avatar; ?> );}
    </style>
    <?php }
}

// Removing Default Image Link in WordPress
function mn_imagelink_remove() {
    $image_set = get_option( 'image_default_link_type' );
     
    if ($image_set !== 'none') {
        update_option('image_default_link_type', 'none');
    }
}
add_action('admin_init', 'mn_imagelink_remove', 10);

// Disable Auto email updates to admin
add_filter( 'auto_core_update_send_email', 'mn_stop_update_emails', 10, 4 );
add_filter( 'auto_plugin_update_send_email', '__return_false' );
add_filter( 'auto_theme_update_send_email', '__return_false' );
function mn_stop_update_emails( $send, $type, $core_update, $result ) {
    if ( ! empty( $type ) && $type == 'success' ) {
    return false;
    }
    return true;
}

// Elementor's Table of Content is a jock
add_filter('the_content', 'mn_add_ids_to_header_tags');
function mn_add_ids_to_header_tags($content){
    $pattern = '#(?P<full_tag><(?P<tag_name>h\d)(?P<tag_extra>[^>]*)>(?P<tag_contents>[^<]*)</h\d>)#i';
    if (preg_match_all($pattern, $content, $matches, PREG_SET_ORDER)) {
        $find = array();
        $replace = array();
        foreach ($matches as $match) {
            if (strlen($match['tag_extra']) && false !== stripos($match['tag_extra'], 'id=')) {
                continue;
            }
            $find[] = $match['full_tag'];
            $id = sanitize_title($match['tag_contents']);
            $id_attr = sprintf(' id="%s"', $id);
            $title_attr = sprintf(' title="%s"', $match['tag_contents']);
            $replace[] = sprintf('<%1$s%2$s%3$s>%4$s</%1$s>', $match['tag_name'], $match['tag_extra'], $id_attr . $title_attr, $match['tag_contents']);
        }
        $content = str_replace($find, $replace, $content);
    }
    return $content;
}

// Elementor's TOC Inline script printed out in the footer
add_action('wp_footer', 'mn_add_titles_toc');
function mn_add_titles_toc() {
    if ( is_single() && 'post' == get_post_type() ) {
    ?>
<script>
    setTimeout(function() {
        let toc = jQuery('.elementor-widget-table-of-contents'),
        	toc_item = toc.find('.elementor-toc__list-item');
        toc_item.each(function () {
        let item = jQuery(this).find('a.elementor-toc__list-item-text'),
            item_text = item.text();
        item.attr('title', item_text);
        });
            
    }, 1000);
</script>
    <?php
    }
}

// Disable Feed
function mn_disable_feeds() {
 	wp_die( __( 'No feed available, please visit the <a href="'. esc_url( home_url( '/' ) ) .'">homepage</a>!' ) );
}
add_action('do_feed', 'mn_disable_feeds', 1);
add_action('do_feed_rdf', 'mn_disable_feeds', 1);
add_action('do_feed_rss', 'mn_disable_feeds', 1);
add_action('do_feed_rss2', 'mn_disable_feeds', 1);
add_action('do_feed_atom', 'mn_disable_feeds', 1);
add_action('do_feed_rss2_comments', 'mn_disable_feed', 1);
add_action('do_feed_atom_comments', 'mn_disable_feed', 1);
remove_action( 'wp_head', 'feed_links_extra', 3 );
remove_action( 'wp_head', 'feed_links', 2 );


// Disable auto-update emails.
add_filter( 'auto_core_update_send_email', '__return_false' );
// Disable auto-update emails for plugins.
add_filter( 'auto_plugin_update_send_email', '__return_false' );
// Disable auto-update emails for themes.
add_filter( 'auto_theme_update_send_email', '__return_false' );

// Remove WordPress Version Number
add_filter('the_generator', '__return_empty_string');

// Disable Attachment Pages on the frontend from all visitors. 
add_action(
	'template_redirect',
	function () {
		global $post;
		if ( ! is_attachment() || ! isset( $post->post_parent ) || ! is_numeric( $post->post_parent ) ) {
			return;
		}

		// Does the attachment have a parent post?
		// If the post is trashed, fallback to redirect to homepage.
		if ( 0 !== $post->post_parent && 'trash' !== get_post_status( $post->post_parent ) ) {
			// Redirect to the attachment parent.
			wp_safe_redirect( get_permalink( $post->post_parent ), 301 );
		} else {
			// For attachment without a parent redirect to homepage.
			wp_safe_redirect( get_bloginfo( 'wpurl' ), 302 );
		}
		exit;
	},
	1
);

// Change Admin Panel Footer Text
add_filter(
	'admin_footer_text',
	function ( $footer_text ) {
		$footer_text = get_stylesheet_directory_uri() . '/copyright-logo.svg';		
		return '<img style="width:150px" src="' . $footer_text . '">';
	}
);

// Disable Fullscreen Editor
add_action(
	'enqueue_block_editor_assets',
	function () {
		$script = "jQuery( window ).load(function() { const isFullscreenMode = wp.data.select( 'core/edit-post' ).isFeatureActive( 'fullscreenMode' ); if ( isFullscreenMode ) { wp.data.dispatch( 'core/edit-post' ).toggleFeature( 'fullscreenMode' ); } });";
		wp_add_inline_script( 'wp-blocks', $script );
	}
);

// Disable Site Admin Email Verification
add_filter( 'admin_email_check_interval', '__return_false' );

// Decrease Auto-Save Interval
if ( ! defined( 'AUTOSAVE_INTERVAL' ) ) {
	// Change 5 to the number of minutes you want to use.
	define( 'AUTOSAVE_INTERVAL', 5 * MINUTE_IN_SECONDS );
}

// Limit the Number of Post Revisions
add_filter( 'wp_revisions_to_keep', function( $limit ) {
	// Limit to the last 20 revisions. Change 20 to whatever limit you want.
	return 20;
} );

// Disable Login Screen Language Switcher
add_filter( 'login_display_language_dropdown', '__return_false' );


// Remove Site Health Dashboard Widget
add_action('wp_dashboard_setup', 'mn_remove_dashboard_widget' );
function mn_remove_dashboard_widget() {
    remove_meta_box( 'dashboard_site_health', 'dashboard', 'normal' );
}
// Remove Site Health Sub Menu Item
add_action( 'admin_menu', 'mn_remove_site_health_menu' );
function mn_remove_site_health_menu(){
  remove_submenu_page( 'tools.php','site-health.php' ); 
}

// Date of post (shamshi)
add_shortcode('mn-date-published', 'mn_date_published');
function mn_date_published(){
	$date = get_the_date('j F Y');
	$fa_num = array('۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹');
	$en_num = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
	$sh_date = str_replace($en_num, $fa_num, $date);
	return $sh_date;	
}




// font display
function update_font_display() {

	return 'swap'; // Or any other value.

}
add_filter( 'elementor_pro/custom_fonts/font_display', 'update_font_display' );


// آخرین بروزرسانی پست با شرط اختلاف 24 ساعت و اعداد فارسی
function show_last_updated_date_shortcode() {
    $modified_time = get_the_modified_time('U');
    $publish_time = get_the_time('U');

    // محاسبه اختلاف زمانی به ساعت
    $time_difference = ($modified_time - $publish_time) / 3600;

    if ($time_difference >= 24) {
        if (function_exists('jdate')) {
            $date = jdate('j F Y', $modified_time);
        } else {
            $date = get_the_modified_date('j F Y');
        }
        $date_farsi = convert_numbers_to_persian($date);
        return 'بروزرسانی در : ' . $date_farsi;
    } elseif ($modified_time != $publish_time) {
        // اگر کمتر از 24 ساعت از انتشار گذشته باشد و ادیت شده باشد
        return 'بدون تغییر جدید';
    }

    return '';
}
add_shortcode('last_updated', 'show_last_updated_date_shortcode');

// تبدیل اعداد انگلیسی به فارسی
function convert_numbers_to_persian($string) {
    $english = ['0','1','2','3','4','5','6','7','8','9'];
    $persian = ['۰','۱','۲','۳','۴','۵','۶','۷','۸','۹'];
    return str_replace($english, $persian, $string);
}