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

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

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

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

function monza_get_image_src( $image_id, $size = 'full' ) {
	$img_attr = wp_get_attachment_image_src( intval( $image_id ), $size );
	if ( ! empty( $img_attr[0] ) ) {
		return $img_attr[0];
	}
}

function monza_excerpt_length( $length ) {
        if ( is_admin() ) {
            return $length;
        }
        
        if ( get_theme_mod('monza_custom_excerpt', true) ) {
            return get_theme_mod('monza_custom_excerpt_length', 23);
        }
}
add_filter( 'excerpt_length', 'monza_excerpt_length', 999 );


/** Pagination */
function monza_pagination()
{
    global $wp_query;
    if ( (int)$wp_query->found_posts > (int)get_option('posts_per_page') ) : ?>
    <div class="monza-pagination"><?php
        $args = array(
            'prev_text' => '<span class="fa fa-angle-left"></span>',
            'next_text' => '<span class="fa fa-angle-right"></span>'
        );
        the_posts_pagination($args);
    ?>
    </div>
    <?php
    endif;
}

/**
 * @author AZ-Team
 * @param int $attach_id
 * @param string $img_url
 * @param int $width
 * @param int $height
 * @param bool $crop
 * @param bool $place_hold  Using place hold image if the image does not exist
 * @since 1.0
 * @return array
 */
function monza_resize_image( $attach_id = null, $img_url = null, $width, $height, $crop = false, $place_hold = true )
{
	// this is an attachment, so we have the ID
	$image_src = array();
	if ( $attach_id ) {
		$image_src			= wp_get_attachment_image_src( $attach_id, 'full' );
		$actual_file_path 	= get_attached_file( $attach_id );
		// this is not an attachment, let's use the image url
	} else if ( $img_url ) {
		$file_path 			= parse_url( $img_url );
		$actual_file_path 	= str_replace( get_site_url(), rtrim( ABSPATH, '/' ), $img_url );
		$orig_size 			= getimagesize( $actual_file_path );
		$image_src[0] 		= $img_url;
		$image_src[1] 		= $orig_size[0];
		$image_src[2] 		= $orig_size[1];
	}
	
	if ( ! empty( $actual_file_path ) && file_exists( $actual_file_path ) )
	{
		$file_info = pathinfo( $actual_file_path );
		$extension = '.' . $file_info['extension'];

		// the image path without the extension
		$no_ext_path 		= $file_info['dirname'] . '/' . $file_info['filename'];
		$cropped_img_path 	= $no_ext_path . '-' . $width . 'x' . $height . $extension;

		// checking if the file size is larger than the target size
		// if it is smaller or the same size, stop right here and return
		if ( $image_src[1] > $width || $image_src[2] > $height )
		{
			// the file is larger, check if the resized version already exists (for $crop = true but will also work for $crop = false if the sizes match)
			if ( file_exists( $cropped_img_path ) ) {
				$cropped_img_url 	= str_replace( basename( $image_src[0] ), basename( $cropped_img_path ), $image_src[0] );
				$vt_image 			= array( 'url' => $cropped_img_url, 'width' => $width, 'height' => $height );
				return $vt_image;
			}

			if ( $crop == false )
			{
				// calculate the size proportionaly
				$proportional_size 	= wp_constrain_dimensions( $image_src[1], $image_src[2], $width, $height );
				$resized_img_path 	= $no_ext_path . '-' . $proportional_size[0] . 'x' . $proportional_size[1] . $extension;

				// checking if the file already exists
				if ( file_exists( $resized_img_path ) ) {
					$resized_img_url 	= str_replace( basename( $image_src[0] ), basename( $resized_img_path ), $image_src[0] );
					$vt_image 			= array( 'url' => $resized_img_url, 'width' => $proportional_size[0], 'height' => $proportional_size[1] );
					return $vt_image;
				}
			}

			// no cache files - let's finally resize it
			$img_editor = wp_get_image_editor( $actual_file_path );

			if ( is_wp_error( $img_editor ) || is_wp_error( $img_editor->resize( $width, $height, $crop ) ) ) {
				return array('url' => '', 'width' => '', 'height' => '');
			}

			$new_img_path = $img_editor->generate_filename();

			if ( is_wp_error( $img_editor->save( $new_img_path ) ) ) {
				return array('url' => '', 'width' => '', 'height' => '');
			}
			if ( ! is_string( $new_img_path ) ) {
				return array('url' => '', 'width' => '', 'height' => '');
			}

			$new_img_size 	= getimagesize( $new_img_path );
			$new_img 		= str_replace( basename( $image_src[0] ), basename( $new_img_path ), $image_src[0] );

			// resized output
			$vt_image = array( 'url' => $new_img, 'width' => $new_img_size[0], 'height' => $new_img_size[1] );

			return $vt_image;
		}

		$vt_image = array('url' => $image_src[0],'width' => $image_src[1],'height' => $image_src[2]);

		return $vt_image;
	}
	else {
		if ( $place_hold ) {
			$width 		= intval( $width );
			$height 	= intval( $height );
			$color 		= str_pad( dechex( mt_rand( 1, 255 ) ), 2, '0', STR_PAD_LEFT ) . str_pad( dechex( mt_rand( 1, 255 ) ), 2, '0', STR_PAD_LEFT ) . str_pad( dechex( mt_rand( 1, 255 ) ), 2, '0', STR_PAD_LEFT );
			$vt_image 	= array(
				'url' 		=> 'http://placehold.it/' . $width . 'x' . $height . '/' . $color . '/ffffff/',
				'width' 	=> $width,
				'height' 	=> $height
			);
			return $vt_image;
		}
	}
    
	return false;
}

/**
 * List Comments
 */
function monza_list_comments($comment, $args, $depth)
{
	$GLOBALS['comment'] = $comment;
	extract($args, EXTR_SKIP);

	if ( 'div' == $args['style'] ) {
		$tag = 'div';
		$add_below = 'comment';
	} else {
		$tag = 'li';
		$add_below = 'div-comment';
	} ?>
	<<?php echo esc_attr($tag); ?> <?php comment_class( empty( $args['has_children'] ) ? '' : 'parent' ) ?> id="comment-<?php comment_ID() ?>">
	<?php if ( 'div' != $args['style'] ) : ?>
	<div id="div-comment-<?php comment_ID() ?>" class="comment-body">
	<?php endif; ?>
		<div class="comment-author">
		<?php if ( $args['avatar_size'] != 0 ) echo get_avatar( $comment, $args['avatar_size'] ); ?>
		</div>
		<div class="comment-content">
			<?php printf( __( '<h4 class="author-name">%s</h4>', 'monza' ), get_comment_author_link() ); ?>
			<span class="date-comment">
				<a href="<?php echo htmlspecialchars( get_comment_link( $comment->comment_ID ) ); ?>">
				<?php printf( __('%1$s at %2$s', 'monza'), get_comment_date(),  get_comment_time() ); ?></a>
			</span>
			<div class="reply">
				<?php edit_comment_link( esc_html__( '(Edit)', 'monza' ), '  ', '' );?>
				<?php comment_reply_link( array_merge( $args, array( 'add_below' => $add_below, 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?>
			</div>
			<?php if ( $comment->comment_approved == '0' ) : ?>
				<em class="comment-awaiting-moderation"><?php esc_html_e( 'Your comment is awaiting moderation.', 'monza' ); ?></em>
				<br />
			<?php endif; ?>
			<div class="comment-text"><?php comment_text(); ?></div>
		</div>	
	<?php if ( 'div' != $args['style'] ) : ?>
	</div>
	<?php endif; ?>
<?php
}

/**
 * Custom styling
 *
 * @return string
 */
function monza_custom_style(){
    $css = '';
    $accent_color = esc_attr( get_theme_mod( 'monza_accent_color' ) );
    if ( $accent_color )
    {
        $css .= '
        a {
        	color: '.$accent_color.';
        }
        a:hover, a:focus, a:active {
        	color: '.$accent_color.';
        }
        .entry-cat a {
        	color: '.$accent_color.';
        }
        .entry-more a {
        	color: '.$accent_color.';
        }
        .entry-more a:hover, .entry-share .social-icon:hover {
            background: '.$accent_color.';
            border-color: '.$accent_color.';
        }
        .monza-pagination .page-numbers.current {
        	background: '.$accent_color.';
        }
        button, input[type="button"], input[type="reset"], input[type="submit"] {
        	background: '.$accent_color.';
        }
        .widget-area .widget a {
            color: '.$accent_color.';
        }
        .site-footer a {
        	color: '.$accent_color.';
        }
        .post-navigation .nav-links a {
            color: '.$accent_color.';
        }
        .page.type-page a {
            color: '.$accent_color.';
        }';
    }

    return $css;
}