<?php
/**
 * Tema WP Prestasi menambahkan beberapa fungsi hook
 * Memanggil beberapa fungsi lain, dibawah ini
 */

function wp_prestasi_activate() { 
    // mendaftarkan custom post type.
    create_post_type(); 
    // update permalink otomatis ketika tema diaktifkan, untuk menghindari halaman 404 terjadi.
    flush_rewrite_rules(); 
}
register_activation_hook( __FILE__, 'wp_prestasi_activate' );

if ( version_compare( $GLOBALS['wp_version'], '5.5', '<' ) ) {
	// WP prestasi baiknya dijalankan pada WordPress 5.5 atau lebih tinggi.
	require get_template_directory() . '/include/back-compat.php';
}

if ( ! function_exists( 'prestasi_setup' ) ) :
    function prestasi_setup() {
		$color_scheme             = prestasi_get_color_scheme();
		$default_background_color = trim( $color_scheme[0], '#' );
		add_theme_support(
		'custom-background',
		apply_filters(
			'roooda_custom_background_args',
			array(
				'default-color' => $default_background_color,
			)
		)
    	);
    	
		// custom logo
		add_theme_support( 'custom-logo', array(
	    	'height'      => 240,
	    	'width'       => 600,
	    	'flex-height' => true,
    	) );
		
		// custom ukuran slide
		if ( get_theme_mod('slide_width') != "" ) {
			$swidth = get_theme_mod('slide_width');
	    } else {
			$swidth = 1200;
		}
		if ( get_theme_mod('slide_height') != "" ) {
			$sheight = get_theme_mod('slide_height');
		} else {
		    $sheight = 700;
	    }
	    $xlite = $swidth / 400;
		if ( $xlite !=0 ) {
	    	$xheight = $sheight / $xlite;
		} else {
			$xheight = 1;
		}
	    add_theme_support('post-thumbnails');
	    add_image_size('slider', $swidth, $sheight, true);
		add_image_size('sliderlite', 400, $xheight, true);
	    add_image_size('news', 600, 450, true);
	    add_image_size('photo', 300, 400, true);
	    add_image_size('mini', 100, 133, true);
	    add_image_size('small', 80, 60, true);
	    add_image_size('gals', 200, 150, true);
		
		// menambahkan menu navigasi
		register_nav_menus(array(
	    	'navigation' => __('Tampilkan Menu Ini di Navigasi Header', 'prestasi'),
    	));
		add_theme_support('html5', array(
	    	'search-form', 'comment-form', 'comment-list',
    	));
		
		add_theme_support( 'customize-selective-refresh-widgets' );
		add_theme_support( 'responsive-embeds' );
	
	    
    }

endif; // prestasi_setup
add_action( 'after_setup_theme', 'prestasi_setup' );


function prestasi_content_width() {
	$GLOBALS['content_width'] = apply_filters( 'prestasi_content_width', 840 );
}
add_action( 'after_setup_theme', 'prestasi_content_width', 0 );

/*
 * Register widget (sidebar).
 */
function prestasi_widgets_init() {
	require get_template_directory().'/widgets/posts.php';
	register_widget('Recentposts');
	require get_template_directory().'/widgets/school.php';
	register_widget('SchoolInfo');
	require get_template_directory().'/widgets/agenda.php';
	register_widget('RecentAgenda');
	require get_template_directory().'/widgets/pengumuman.php';
	register_widget('RecentPengumuman');
	require get_template_directory().'/widgets/blog.php';
	register_widget('RecentBlog');
	require get_template_directory().'/widgets/videos.php';
	register_widget('Videos');

	register_sidebar(array(
		'name' => __('Footer 1', 'prestasi'),
		'id'   => 'sidebar-1',
		'before_widget' => '<div id="%1$s" class="%2$s widget">',
		'after_widget' => '</div>',
		'before_title' => '<h3><span>',
		'after_title' => '</span></h3>'
	));
	
	register_sidebar(array(
		'name' => __('Footer 2', 'prestasi'),
		'id'   => 'sidebar-2',
		'before_widget' => '<div id="%1$s" class="%2$s widget">',
		'after_widget' => '</div>',
		'before_title' => '<h3><span>',
		'after_title' => '</span></h3>'
	));

	register_sidebar(array(
		'name' => __('Footer 3', 'prestasi'),
		'id'   => 'sidebar-3',
		'before_widget' => '<div id="%1$s" class="%2$s widget">',
		'after_widget' => '</div>',
		'before_title' => '<h3><span>',
		'after_title' => '</span></h3>'
	));
	
}
add_action('widgets_init', 'prestasi_widgets_init');

/**
 *
 * Hide Admin on Frontend
 */
 
show_admin_bar(false);

function return_30( $seconds ) {
  // change the default feed cache recreation period to 30 seconds;
  return 120;
}
add_filter( 'wp_feed_cache_transient_lifetime' , 'return_30' ); 
 
/**
 * Register script
 */
 
function prestasi_stylescripts() {
	$theme_version = wp_get_theme()->get( 'Version' );
	// panggil css
	wp_enqueue_style('press-style', get_stylesheet_uri(), array(), $theme_version );
	wp_enqueue_style('press-owl', get_template_directory_uri().'/stylesheet/owl.carousel.min.css', array(), $theme_version );
	wp_enqueue_style('press-ani', get_template_directory_uri().'/stylesheet/owl.animate.css', array(), $theme_version );
	wp_enqueue_style('press-theme', get_template_directory_uri().'/stylesheet/owl.theme.default.min.css', array(), $theme_version );
	wp_enqueue_style('press-awe', get_template_directory_uri().'/fontawesome/css/font-awesome.css', array(), $theme_version );
}
add_action('wp_enqueue_scripts', 'prestasi_stylescripts');

function prestasi_scripts() {
	// panggil script
	if (is_singular() && comments_open() && get_option('thread_comments')) {
		wp_enqueue_script('comment-reply');
	}
	wp_enqueue_script( 'jquery' );
	wp_enqueue_script( 'press-owls', get_template_directory_uri() . '/javascript/owl.carousel.min.js', array(), false, true );
	wp_enqueue_script( 'press-ticker', get_template_directory_uri() . '/javascript/newstickers.js', array(), false, true );
	
}
add_action('wp_enqueue_scripts', 'prestasi_scripts');

/**
 * Custom template untuk tema WP prestasi.
 */
require get_template_directory() . '/include/template-tags.php';

/**
 * Panel untuk Customizer.
 */
require get_template_directory() . '/include/customizer.php';
require get_template_directory() . '/include/partialrefresh.php';

/**
 * Panel untuk Customizer.
 */
require get_template_directory() . '/include/coloring.php';
require get_template_directory() . '/include/color-option.php';
require get_template_directory() . '/include/color-enqueue.php';
require get_template_directory() . '/include/color-print.php';
require get_template_directory() . '/include/color-print-footer.php';
require get_template_directory() . '/include/color-inline-css.php';

/**
 * Daftarkan post type.
 */
require get_template_directory() . '/post-type/post-type.php';

/**
 * Breadcrumb.
 */
require get_template_directory() . '/include/func/breadcrumb.php';

/**
 * Ajax Login
 */
require get_template_directory() . '/include/custom-ajax-auth.php';

/**
 * Ciuss News.
 */
require get_template_directory() . '/include/func/ciuss-news.php';

if (is_admin() && isset($_GET['activated']) && $pagenow == 'themes.php') {
	update_option('posts_per_page', 12);
}

function prestasi_numeric_pagination() {

	if( is_singular() )
		return;
	global $wp_query;

	if( $wp_query->max_num_pages <= 1 )
		return;

	$paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;
	$max   = intval( $wp_query->max_num_pages );
	if ( $paged >= 1 )
		$links[] = $paged;
	if ( $paged >= 3 ) {
		$links[] = $paged - 1;
		$links[] = $paged - 2;
	}

	if ( ( $paged + 2 ) <= $max ) {
		$links[] = $paged + 2;
		$links[] = $paged + 1;
	}

	if ( ! in_array( 1, $links ) ) {
		$class = 1 == $paged ? ' class="active"' : '';
		printf( '<a%s href="%s">%s</a>' . "\n", $class, esc_url( get_pagenum_link( 1 ) ), '1' );
		if ( ! in_array( 2, $links ) )
			echo ' … ';
	}

	sort( $links );
	foreach ( (array) $links as $link ) {
		$class = $paged == $link ? ' class="active"' : '';
		printf( '<a%s href="%s">%s</a>' . "\n", $class, esc_url( get_pagenum_link( $link ) ), $link );
	}

	if ( ! in_array( $max, $links ) ) {
		if ( ! in_array( $max - 1, $links ) )
			echo ' … ' . "\n";
		$class = $paged == $max ? ' class="active"' : '';
		printf( '<a%s href="%s">%s</a>' . "\n", $class, esc_url( get_pagenum_link( $max ) ), $max );
	}

}

function shapeSpace_popular_posts($post_id) {
	$count_key = 'popular_posts';
	$count = get_post_meta($post_id, $count_key, true);
	if ($count == '') {
		$count = 0;
		delete_post_meta($post_id, $count_key);
		add_post_meta($post_id, $count_key, '0');
	} else {
		$count++;
		update_post_meta($post_id, $count_key, $count);
	}
}
function shapeSpace_track_posts($post_id) {
	if (!is_single()) return;
	if (empty($post_id)) {
		global $post;
		$post_id = $post->ID;
	}
	shapeSpace_popular_posts($post_id);
}
add_action('wp_head', 'shapeSpace_track_posts');

function getPostViews($postID){ 
    $count_key = 'post_views_count'; 
	$count = get_post_meta($postID, 
	$count_key, true); 
	
	if($count==''){ 
	delete_post_meta($postID, $count_key); 
	add_post_meta($postID, $count_key, '0'); return "0 View"; 
	} 
	return $count; 
} 
	
function setPostViews($postID) { 
    $count_key = 'post_views_count'; 
	$count = get_post_meta($postID, $count_key, true); 
	
	if($count==''){ 
	$count = 0; delete_post_meta($postID, $count_key); 
	add_post_meta($postID, $count_key, '0'); 
	}else{ 
	$count++; 
	update_post_meta($postID, $count_key, $count); 
	} 
}

function prestasi_event_expired($post_ID) {
	    global $post;
        $post_event_date = get_post_meta($post_ID, '_tevent', true);
		$end = get_post_meta($post_ID, '_tevent', true).' '.get_post_meta($post_ID, '_jam', true);
		$exp = strtotime(date_i18n($end));
		$dday = strtotime(date_i18n('d-m-Y H:i'));
		$sisa = $exp-$dday;
		$event_date = date("d F Y", strtotime($post_event_date));
        if ($post_event_date != "" ) {
            echo $event_date;
			if ( $sisa < 0 ) { 
			    echo __( '<br/><strong class="expired">Acara Sudah Lewat</strong>', 'prestasi' ); 
			} else {
				echo __( '<br/><strong class="next">Acara Segera Berlangsung</strong>', 'prestasi' );
			}
        }
}

function prestasi_event_columns($defaults) {
        $defaults['prestasi_expired'] = __( 'Pelaksanaan', 'prestasi' );
        return $defaults;
}
	
function event_columns_content($column_name, $post_ID) {
        if ($column_name == 'prestasi_expired') {
			global $post;
            $post_expired_event = prestasi_event_expired($post_ID);
			$end = get_post_meta($post_ID, '_tevent', true).' '.get_post_meta($post_ID, '_jam', true);
	    	$exp = strtotime(date_i18n($end));
	    	$dday = strtotime(date_i18n('d-m-Y H:i'));
	    	$sisa = $exp-$dday;
			if ($post_expired_event != "" ) {
                echo $post_expired_event;
				if ( $sisa < 0 ) { echo __( '<br/><strong>Acara Sudah Lewat</strong>', 'prestasi' ); }
            }
        }
}
	
add_filter('manage_event_posts_columns', 'prestasi_event_columns', 10);
add_action('manage_event_posts_custom_column', 'event_columns_content', 10, 2);

function prestasi_mobile() {    
    return preg_match("/(android|avantgo|blackberry|bolt|boost|cricket|docomo|fone|hiptop|mini|mobi|palm|phone|pie|tablet|up\.browser|up\.link|webos|wos)/i", $_SERVER["HTTP_USER_AGENT"]);
}

function new_excerpt_length($length) {
	return 200;
}
add_filter('excerpt_length', 'new_excerpt_length');

function smart_excerpt($string, $limit) {
	$words = explode(" ", $string);
	if (count($words) >= $limit) $dots = '..';
	else $dots = '';
	echo implode(" ", array_splice($words, 0, $limit)).$dots;
}

function commentslist($comment, $args, $depth) {
	$GLOBALS['comment'] = $comment; ?>
	
	    <div class="clear">
		    <div class="comment__avatar">
		        <?php if(get_avatar($comment)) { ?>
					<?php echo get_avatar($comment, 60); ?>
				<?php } else { ?>
					<img src="<?php echo get_template_directory_uri(); ?>/roo-img/avatar.png"/>
				<?php } ?>
			</div>
			<div class="comment__meta">
				<?php if ($comment->comment_approved == '0'): ?>
					<p><?php _e('Komentar Anda Menunggu Disetujui Admin.', 'prestasi') ?></p>
					<br/>
				<?php endif; ?>
				<?php printf(__('<div class="comment__author"><span>%s</span>, <em>%s</em></div>'), get_comment_author_link(), get_comment_date('l, j M Y')) ?>
				<?php comment_text() ?>
				<?php comment_reply_link(array_merge($args, array('depth' => $depth, 'max_depth' => $args['max_depth']))) ?>
			</div>
		</div>
<?php
}

function comments_link_attributes() {
	return 'class="comments_popup_link"';
}
add_filter('comments_popup_link_attributes', 'comments_link_attributes');

function next_posts_attributes() {
	return 'class="nextpostslink"';
}
add_filter('next_posts_link_attributes', 'next_posts_attributes');

function prev_posts_attributes() {
	return 'class="previouspostslink"';
}
add_filter('previous_posts_link_attributes', 'prev_posts_attributes');

$exl_posts = array();

add_action('admin_head', 'prestasi_admin_styles');

function prestasi_admin_styles() { ?>
	<style>
	    <?php 
		    $user = wp_get_current_user();
            $allowed_roles = array( 'guru', 'master', 'operator', 'siswa' );
            if ( array_intersect( $allowed_roles, $user->roles ) ) { ?>
            
			.user-rich-editing-wrap,
			.user-admin-color-wrap,
			.show-admin-bar,
			.user-comment-shortcuts-wrap,
			.show-admin-bar user-admin-bar-front-wrap,
			.user-language-wrap,
			.user-profile-picture,
			#application-passwords-section {
				display: none;
		    }
			<?php 
			} 
		?>
		.press_metabox label {
			display: block;
			margin: 8px 0;
		}
		.clear:after {
            content: ".";
			display: block;
			height: 0;
			clear: both;
			visibility: hidden;
		}
		.press_metabox table {
			width: 100%;
		}
		.half {
			width: calc( 50% - 40px );
			float: left;
		}
		.halfclose {
			width: 80px;
			float: left;
		}
		.halfin {
			padding: 0 12px 8px 0;
		}
		.press_hidden {
			position: relative;
		}
		.press_hidden:after {
			content: "";
			position: absolute;
			left: 0;
			top: 0;
			width: 100%;
			height: 100%;
			z-index: 10;
			background: #fff;
			opacity: 0.4;
		}
		.family {
			width: 50%; float: left;
		}
		.infam {
			padding: 0 15px 0 0;
		}
		.rss-box {
			margin: -12px -12px 12px;
		}
		.rss-box img {
			width: 100%;
			height: auto;
		}
		.rss-footer {
			margin: 12px -12px 0;
			padding: 12px 12px 0;
			border-top: 1px solid #ddd; 
		}
		.press_metabox .full {
			width: 100%;
		}
		.press_metabox .abcd {
			width: 25%;
			float: left;
		}
		.button-move {
			background: #f33;
		}
		
		@media screen and (max-width:800px) {
		.rss-web {
			display: none;
		}
		.rss-mob {
			display: inline-block;
		}
		} 
		
	</style>
<?php }

/**
 * Shortcode.
 */
require get_template_directory() . '/include/func/shortcode.php';

/**
 * Change default screen title post_type.
 */
function prestasi_title_text( $title ){
    $screen = get_current_screen();
    // Default screen title post_type Agenda
    if  ( 'agenda' == $screen->post_type ) {
        $title = __( 'Judul Agenda ...', 'prestasi' );
	} else if  ( 'testimoni' == $screen->post_type ) {
        $title = __( 'Add Name ...', 'prestasi' );
    } else if  ( 'model' == $screen->post_type ) {
        $title = __( 'Add Model..', 'prestasi' );
	} else if  ( 'slider' == $screen->post_type ) {
        $title = __( 'Add Slider ...', 'prestasi' );
	} else {
        $title = __( 'Add Title ...', 'prestasi' );
    }
    return $title;
}
add_filter( 'enter_title_here', 'prestasi_title_text' );


// Pencarian Siswa Ajax
add_action('wp_ajax_siswa_fetch' , 'siswa_fetch');
add_action('wp_ajax_nopriv_siswa_fetch','siswa_fetch');

function siswa_fetch(){

    $the_query = new WP_Query( 
        array( 
            'posts_per_page' => -1, 
            's' => esc_attr( $_POST['student'] ), 
            'post_type' => 'siswa' 
        ) 
    );

    if( $the_query->have_posts() ) :
	    echo '<table class="result_siswa">';
		echo '<tr><td>Nama</td><td>Kelas</td></tr>';
        while( $the_query->have_posts() ): $the_query->the_post();
		    global $post;
			$nisn = get_post_meta($post->ID, '_nisn', true);
		    $myquery = esc_attr( $_POST['student'] );
			$a = $myquery;
			$search = get_the_title();
			if( stripos("/{$search}/", $a) !== false) { ?>
			
			    <tr>
                    <td><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></td>
					<td>
					    <?php 
					        $terms = get_the_terms( $post->ID , 'kelas' );
							if ( $terms != null ){
								foreach( $terms as $term ) {
									echo $term->name;
									unset($term); 
								} 
							} 
						?>
					</td>
				</tr>
				
            <?php }
		endwhile;
		echo '</table>';
        wp_reset_postdata();  
    endif;

    die();
}


// the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){

    $the_query = new WP_Query( 
        array( 
            'posts_per_page' => -1, 
            's' => esc_attr( $_POST['keyword'] ), 
            'post_type' => 'download' 
        ) 
    );

    if( $the_query->have_posts() ) :
        while( $the_query->have_posts() ): $the_query->the_post();
		    global $post;
			$strFile = get_post_meta($post -> ID, $key = 'podcast_file', true);
			$sizeFile = get_post_meta($post -> ID, $key = 'size_file', true);
			 
		    $myquery = esc_attr( $_POST['keyword'] );
			$a = $myquery;
			$search = get_the_title();
			if( stripos("/{$search}/", $a) !== false) { ?>
			
			    <div class="ajax_down clear">
				    <div class="ajax_box">
                    <h4><?php the_title();?></h4>
					<?php 
					    echo __('File', 'prestasi'); ?> <?php $terms = get_the_terms( $post->ID , 'type-file' );
						if ( $terms != null ){
							foreach( $terms as $term ) {
								$term_link = get_term_link( $term, 'type-file');
								echo $term->name;
								unset($term); 
							} 
						} 
					?> <?php echo __('Ukuran', 'prestasi'); ?> <?php echo esc_html( $sizeFile ); ?>
				</div>
				
				<a class="down_down" download="<?php echo esc_attr( $strFile ); ?>" href="<?php echo esc_attr( $strFile ); ?>"><i class="fa fa-download"></i></a>
				</div>
            <?php }
		endwhile;
        wp_reset_postdata();  
    endif;

    die();
}

function custom_post_author_archive($query) {
    if ($query->is_author)
        $query->set( 'post_type', array('blog') );
    remove_action( 'pre_get_posts', 'custom_post_author_archive' );
}
add_action('pre_get_posts', 'custom_post_author_archive'); 

/**
 * Role User.
 */
require get_template_directory() . '/include/func/capabilities.php';

function only_show_user_images( $query ) {
	$current_userID = get_current_user_id();
	if ( $current_userID && !current_user_can('manage_options')) {
		$query['author'] = $current_userID;
	}
	return $query; 
}

add_filter( 'ajax_query_attachments_args', 'only_show_user_images' ); 

function press_rest_change_media_context( $result, $server, $request ) {
		// apply only to GET method
		$method = $request->get_method();
		if ( 'GET' !== $method ) {
			return $result;
		}

		$url = $request->get_route();
		if ( ! is_user_logged_in() || ( false === strpos( $url, '/wp/v2/media/' ) ) ) {
			return $result;
		}

		if ( 'edit' === $request->get_param( 'context' ) ) {
			$request->set_param( 'context', 'view' );
		}

		return $result;
	}

add_filter( 'rest_pre_dispatch', 'press_rest_change_media_context', 10, 3 );

function post_publish_after() {
	
	global $post;
	
	$date = get_post_time('G', true, $post);
	
	
	// Array of time period chunks
	$chunks = array(
		array( 60 * 60 * 24 * 365 , __( 'tahun', 'prestasi' ), __( 'tahun', 'prestasi' ) ),
		array( 60 * 60 * 24 * 30 , __( 'bulan', 'prestasi' ), __( 'bulan', 'prestasi' ) ),
		array( 60 * 60 * 24 * 7, __( 'minggu', 'prestasi' ), __( 'minggu', 'prestasi' ) ),
		array( 60 * 60 * 24 , __( 'hari', 'prestasi' ), __( 'hari', 'prestasi' ) ),
		array( 60 * 60 , __( 'jam', 'prestasi' ), __( 'jam', 'prestasi' ) ),
		array( 60 , __( 'menit', 'prestasi' ), __( 'menit', 'prestasi' ) ),
		array( 1, __( 'detik', 'prestasi' ), __( 'detik', 'prestasi' ) )
	);

	if ( !is_numeric( $date ) ) {
		$time_chunks = explode( ':', str_replace( ' ', ':', $date ) );
		$date_chunks = explode( '-', str_replace( ' ', '-', $date ) );
		$date = gmmktime( (int)$time_chunks[1], (int)$time_chunks[2], (int)$time_chunks[3], (int)$date_chunks[1], (int)$date_chunks[2], (int)$date_chunks[0] );
	}
	
	$current_time = current_time( 'mysql', $gmt = 7 ); // waktu Indonesia GMT + 7
	$newer_date = strtotime( $current_time );

	// Jeda waktu dalam detik
	$since = $newer_date - $date;

	// Perhitungan waktu tak tentu.
	if ( 0 > $since )
		return __( 'Beberapa', 'prestasi' );

	//Step one
	for ( $i = 0, $j = count($chunks); $i < $j; $i++) {
		$seconds = $chunks[$i][0];

		if ( ( $count = floor($since / $seconds) ) != 0 )
			break;
	}

	// Set output var
	$output = ( 1 == $count ) ? '1 '. $chunks[$i][1] : $count . ' ' . $chunks[$i][2];
	

	if ( !(int)trim($output) ){
		$output = '0 ' . __( 'Detik', 'prestasi' );
	}
	
	$output .= __(' Yang Lalu', 'prestasi');
	
	return $output;
}

add_filter('the_time', 'post_publish_after');

if( current_user_can( 'siswa' ) ) {
    add_filter( 'show_password_fields', '__return_false' );
}
