<?php
/**
 * Created by PhpStorm.
 * User: marco
 * Date: 25/06/18
 * Time: 14.55
 */


/**
 * @param string $url
 * @param string $text
 * @param string $fa_tag
 * @param string $custom_attributes_string
 */

function o66fpwp_a_button( $url = '#', $text = 'Click me!', $fa_tag = 'fa-arrow-circle-o-right', $is_icon_before = false, $custom_attributes_string = '' ) {
	//<a href="#" class="a--button">Tutti gli eventi nel <?php echo$year;
	//<i class="fa fa-arrow-circle-o-right"></i></a>
	$icon_before = '';
	$icon_after  = "  ${fa_tag}";
	//TODO RIFARE + PURO
	$targetBlankString = '';
	$findPdf = strtolower(substr($url, -3));
	if ($findPdf === 'pdf') {
	    $targetBlank = true;
	    $targetBlankString = ' target="_blank"';
	}


	if ( $is_icon_before === true ) {
		$icon_before = "${fa_tag} ";
		$icon_after  = '';
	}
	echo "<a class='a--button' ${custom_attributes_string} href='${url}'$targetBlankString>${icon_before}${text}${icon_after}</a>";

}


function print_var_name($var) {
    foreach($GLOBALS as $var_name => $value) {
        if ($value === $var) {
            return $var_name;
        }
    }

    return false;
}

function console_log($value){

    $return_type = gettype($value);
    $return = $value;
    $return_name = print_var_name($return);
    $return_string = "<script>console.log('php ${return_type} $${return_name} :')</script>";
    $return_second_line_content = '';
    $backtrace = debug_backtrace();
    $backtraceCount = count($backtrace);
    $backtraceFile = '\n'.'in: '.$backtrace[0]['file'].'';
        $return_file = '\n [ in file : '.basename(__FILE__, '.php').' ]';
     // $return_second_line_content = $return;
    if ($return_type === 'array' || $return_type === 'object' || $return_type === 'resource')
    {
        $array_count = count($return);
        $return_second_line_content .= 'total items: '.$array_count.' \n';
        foreach ($return as $key => $item) {
        $return_second_line_content .= $key;
        $return_second_line_content .= ' -> ';
        $return_second_line_content .= $item ;

        }
    }
    else {
        $return_second_line_content = $return;
    }

    $return_second_line = "<script>console.log('${return_second_line_content}${backtraceFile}')</script>";
    $return_third_line = "<script>console.log('--------------------------------------');</script>";
 echo $return_string.$return_second_line.$return_third_line;
 var_dump($backtrace[0]);
}

function o66fpwp_a_button_accordion_action_trigger(
	$text_open = 'Open', $text_close = 'Close',
	$fa_tag_open = '<i class="fa fa-arrow-circle-o-down"></i>',
	$fa_tag_close = '<i class="fa fa-arrow-circle-o-down"></i>', $is_icon_before = false, $accordion_name = 'mario', $is_opened = false
) {
	//<a href="#" class="a--button">Tutti gli eventi nel <?php echo$year;
	//<i class="fa fa-arrow-circle-o-right"></i></a>


	$icon_before_open  = '';
	$icon_before_close = '';

	$icon_after_open  = " ${fa_tag_open}";
	$icon_after_close = " ${fa_tag_close}";
	if ( $is_icon_before === true ) {
		$icon_before_open  = "${fa_tag_open}' ";
		$icon_before_close = "${fa_tag_close}' ";
		$icon_after_open   = '';
		$icon_after_close  = '';
	}

	$is_opened_attribute = " data-is-opened='false' ";
	if ( $is_opened === true ) {
		$is_opened_attribute = " data-is-opened='true' ";
	}
	echo "<a class='a--button ${accordion_name}-accordion-button js-accordion-action-trigger' data-accordion-name='${accordion_name}' ${is_opened_attribute} data-text-close='${icon_before_close}${text_close}${icon_after_close}'>${icon_before_open}${text_open}${icon_after_open}</a>";


}

function o66fswp_acf_image( $image_size = 'rect', $responsive = true, $postID = null, $acf_field = 'image' ) {

	$acf_image = '';
	$wp_image  = '';
	global $post;
	//$postObject          = $post;
	if (empty($postID)){
	$postID              = $post->ID;
	}
	//$pagePostThumbnailID = $postID;
	$post_title          = $post->post_title;
	$class_responsive = '';
	if ($responsive === true){
	    $class_responsive = ' class="img-responsive" ';
	}


	if ( class_exists( 'acf' ) ) {

		$acf_image = get_field( $acf_field, $postID );

		if ( ! empty( $acf_image ) ) {

//			$desktopImageSize = $image_size;
//			$mobileImageSizes = 'quad';


			if ($image_size = 'full') {
			    $image = $acf_image['url'];
			} else {
			    $image = $acf_image['sizes'][ $image_size ];
			}
			//$immagine_sfondo_mobile = $slide['immagine_sfondo_mobile'];

//			if ( empty( $immagine_sfondo_mobile ) ) {
//				$immagine_sfondo_mobile = $immagine_sfondo;
//			}
//
//			$widthDesktop  = $immagine_sfondo['sizes'][ $desktopImageSize . '-width' ];
//			$heightDesktop = $immagine_sfondo['sizes'][ $desktopImageSize . '-height' ];
//
//			$widthMobile  = $immagine_sfondo_mobile['sizes'][ $mobileImageSizes . '-width' ];
//			$heightMobile = $immagine_sfondo_mobile['sizes'][ $mobileImageSizes . '-height' ];
//
//			$ratioWidthHeight = [ $widthDesktop, $heightDesktop, $widthMobile, $heightMobile ];
//
//			$immagine        = $immagine_sfondo['sizes'][ $desktopImageSize ];
//			$immagine_mobile = $immagine_sfondo_mobile['sizes'][ $mobileImageSizes ];
//			$alt             = $immagine_sfondo['alt'];
//			var_dump( $image );

		}

	}

	//fine model, se presente vai di view:
	if ( ! empty( $image ) ) : ?>
        <div class="image-acf">

                <img src="<?php echo $image; ?>" alt="<?php echo $post_title; ?>" <?php echo $class_responsive;?>>

        </div>
	<?php endif;

}

/**
 * @param string $image_size
 */

function o66fswp_main_image( $image_size = 'rect' ) {

	$acf_image = '';
	$wp_image  = '';
	global $post;
	$postObject          = $post;
	$postID              = $post->ID;
	$pagePostThumbnailID = $postID;
	$post_title          = $post->post_title;

	if ( class_exists( 'acf' ) ) {
		$acf_image = get_field( 'main_image' );

		if ( ! empty( $acf_image ) ) {

//			$desktopImageSize = $image_size;
//			$mobileImageSizes = 'quad';

			$image = $acf_image['sizes'][ $image_size ];
			//$immagine_sfondo_mobile = $slide['immagine_sfondo_mobile'];

//			if ( empty( $immagine_sfondo_mobile ) ) {
//				$immagine_sfondo_mobile = $immagine_sfondo;
//			}
//
//			$widthDesktop  = $immagine_sfondo['sizes'][ $desktopImageSize . '-width' ];
//			$heightDesktop = $immagine_sfondo['sizes'][ $desktopImageSize . '-height' ];
//
//			$widthMobile  = $immagine_sfondo_mobile['sizes'][ $mobileImageSizes . '-width' ];
//			$heightMobile = $immagine_sfondo_mobile['sizes'][ $mobileImageSizes . '-height' ];
//
//			$ratioWidthHeight = [ $widthDesktop, $heightDesktop, $widthMobile, $heightMobile ];
//
//			$immagine        = $immagine_sfondo['sizes'][ $desktopImageSize ];
//			$immagine_mobile = $immagine_sfondo_mobile['sizes'][ $mobileImageSizes ];
//			$alt             = $immagine_sfondo['alt'];
//			var_dump( $image );

		}

	}

	//fine model, se presente vai di view:
	if ( ! empty( $image ) ) : ?>
        <div class="main-image">
            <div class="main-image__image-container img-responsive-container">
                <img src="<?php echo $image; ?>" alt="<?php echo $post_title; ?>">
            </div>
        </div>
	<?php endif;

}

/**
 * @param string $field_name
 * @param null $post_id
 *
 * @return string the html content
 */
function _echo_the_content_block( $field_name = 'content_block', $post_id = null ) {
	//$the_content_to_return = '';
	; ?>
	<?php while ( have_rows( $field_name ) ) : the_row(); ?>
		<?php if ( get_row_layout() == 'text_editor_block' ) : ?>
			<?php the_sub_field( 'text_editor' ); ?>
			<?php // endif; ?>
		<?php elseif ( get_row_layout() == 'gallery_block' ) : ?>
			<?php $gallery_images = get_sub_field( 'gallery' ); ?>
			<?php if ( $gallery_images ) : ?>
                <div class="entry-content__gallery">
                    <div class="row">
						<?php foreach ( $gallery_images as $gallery_image ): ?>
                            <div class="col-lg-2 col-md-3 col-sm-4 col-xs-6">
                                <div class="entry-content__gallery__image">
                                    <a href="<?php echo $gallery_image['url']; ?>">
                                        <img src="<?php echo $gallery_image['sizes']['quad']; ?>"
                                             alt="<?php echo $gallery_image['alt']; ?>" class="img-responsive"/>
                                    </a>
                                </div>
                            </div>
						<?php endforeach; ?>
                    </div>
                </div>
			<?php endif; ?>
		<?php endif; ?>
	<?php endwhile; ?>
	<?php //return $the_content_to_return;
}

/**
 * @param string $field_name
 * @param null $post_id
 */
function o66fswp_the_content_block( $field_name = 'content_block', $post_id = null ) {
	global $post;

	if ( $post_id === null ) {
		$post_id = $post->ID;
	}
	if ( class_exists( 'acf' ) ) {

		if ( have_rows( $field_name ) ) : ?>
            <section class="entry-content__section">
				<?php _echo_the_content_block( $field_name, $post_id ); ?>
            </section>

		<?php endif;
	}
}

function o66fswp_the_extended_title( $field_name = 'extended_title', $heading_level = '2', $post_id = null ) {
	global $post;
	$current_post_id = null;
	$wp_title        = null;
	$acf_title       = null;
	$echo_title      = null;

	if ( $post_id === null ) {
		$current_post_id = $post->ID;
		$wp_title        = $post->post_title;
	}

	if ( $post_id !== null ) {
		$current_post_id = $post_id;
		$wp_title        = get_the_title( $post_id );
	}

	if ( class_exists( 'acf' ) ) {
		$acf_title = get_field( 'extended_title', $current_post_id );
	}

	if ( ! empty( $acf_title ) ) {
		$echo_title = $acf_title;
	}
	if ( empty( $acf_title ) ) {
		$echo_title = $wp_title;
	}

	echo "<h{$heading_level}>{$echo_title}</h{$heading_level}>";

}

/**
 * @param string $repeater_field_name
 * @param string $content_block_field_name
 * @param string $title_field_name
 * @param null $post_id
 */
function o66fswp_the_section_repeater_block( $repeater_field_name = 'content_sections', $content_block_field_name = 'content_block', $title_field_name = 'section_title', $post_id = null ) {
	global $post;
	$sectCount = 0;
	$sectClass = '';

	if ( $post_id === null ) {
		$post_id = $post->ID;
	}
	if ( class_exists( 'acf' ) ) {

		if ( have_rows( $repeater_field_name ) ) : ?>

			<?php while ( have_rows( $repeater_field_name ) ) : the_row();
			if ($sectCount === 0) {
			    $sectClass = 'mar-bot';
			}
			?>
                <section class="entry-content__section <?php echo $sectClass;?>">
					<?php $section_title = get_sub_field( $title_field_name );
					if ( ! empty( $section_title ) ) : ?>
                        <div class="entry-content__section__header"><h2><?php echo $section_title; ?></h2></div>
					<?php endif; ?>
                    <div class="entry-content__section__blocks">
						<?php _echo_the_content_block( $content_block_field_name, $post_id ); ?>
                    </div>
                </section>
			<?php endwhile; ?>


		<?php endif;
	}
}


function o66fswp_the_posts_acf_filtered($post_type, $meta_key_acf_field, $icon_tag = '<i class="fa fa-arrow-circle-o-down"></i>', $link = 'single') {

	$args        = array(
		//'posts_per_page'   => 5,
		'offset'           => 0,
		//	'category'         => '',
		//	'category_name'    => '',
		'orderby'          => 'meta_value',
		'order'            => 'ASC',
		'include'          => '',
		'exclude'          => '',
		'meta_key'         => $meta_key_acf_field,
		//'meta_value'       => 'gestionale',
		'post_type'        => $post_type,
		'post_mime_type'   => '',
		'post_parent'      => '',
		'author'           => '',
		'author_name'      => '',
		'post_status'      => 'publish',
		'suppress_filters' => true,
		'fields'           => '',
	);
	$posts_array = get_posts( $args );
	$cat_array   = array();

	foreach ( $posts_array as $item ) {
		array_push( $cat_array, get_field( 'team_category', $item->ID ) );
	}
	$cat_array_unique       = array_unique( $cat_array );
	//var_dump($cat_array_unique);
	if ( ! empty( $cat_array_unique ) ) : ?>
        <div class="aside--press">
		<?php

		foreach ( $cat_array_unique as $cat_item ) :
			//echo $cat_item;

			$args = array(
				//'posts_per_page'   => 5,
				'offset'           => 0,
				//	'category'         => '',
				//	'category_name'    => '',
				'orderby'          => 'title',
				'order'            => 'ASC',
				'include'          => '',
				'exclude'          => '',
				'meta_key'         => $meta_key_acf_field,
				'meta_value'       => $cat_item,
				'post_type'        => $post_type,
				'post_mime_type'   => '',
				'post_parent'      => '',
				'author'           => '',
				'author_name'      => '',
				'post_status'      => 'publish',
				'suppress_filters' => true,
				'fields'           => '',
			);
			$this_cat_posts = get_posts( $args );
			//var_dump($this_cat_posts[0]->post_title);

			?>

            <div class="aside__media-year-list">
<div class="media-year-list__heading">
    			<h3><?php echo $cat_item; ?></h3>
    			</div>
                <ul>
			        <?php foreach ( $this_cat_posts as $post_item ) :
			        if ($link === 'single') {$aTagStart = '<a href="'.get_the_permalink($post_item->ID).'">'; $aTagEnd = '</a>';}
			        ?>
                    <li><?php echo $aTagStart.$icon_tag;?> <?php echo $post_item->post_title.$aTagEnd;?></li>
		            <?php endforeach; ?>
            </ul>
		<?php endforeach; ?>
        </div>
        <?php endif;
}

function o66fswp_acf_fields_filtered_by_year($acf_repeater, $acf_category, $acf_date, $icon_tag = '<i class="fa fa-arrow-circle-o-down"></i>') {

		global $post;

//	if ( $post_id === null ) {
//		$post_id = $post->ID;
//	}

	//$posts_array = get_field( $post_type );
//	var_dump($posts_array);
	$cat_array   = array();
	//$year_array   = array();
	$cat_and_sub = array();
	$count = 0;
	while ( have_rows( $acf_repeater ) ) : the_row();
	    $date = get_sub_field($acf_date);
	    $year          = substr( $date, 0, 4 );
	    array_push($cat_array, get_sub_field($acf_category));
	    array_push($year_array, $year);
	endwhile;




$cat_array_unique = array_unique($cat_array);
sort($cat_array_unique);
	if ( ! empty( $cat_array_unique ) ) : ?>
        <div class="aside-post-list__container">
    <?php foreach ($cat_array_unique as $cat_item) :
     $thisCatYears = array();
     ?>
        <div class="aside-post-list__container">
            			<h3><?php echo $cat_item; ?></h3>
            			<ul>
            			<?php while ( have_rows( $acf_repeater ) ) : the_row();
	    $date = get_sub_field($acf_date);
	    $year          = substr( $date, 0, 4 );
	    if (get_sub_field($acf_category) === $cat_item) {array_push($thisCatYears, $year);}

	  //  array_push($year_array, $year);
	endwhile;
	    sort($thisCatYears);
	foreach (array_unique($thisCatYears) as $thisYear) :
		    $aTagStart = '<a href="'.get_the_permalink($post->ID).'?'.$acf_category.'='.$cat_item.'&year='.$thisYear.'">';
	    $aTagEnd = '</a>';
	?>
        <li><?php echo $aTagStart.$icon_tag;?> <?php echo $thisYear.$aTagEnd;?></li>
	<?php endforeach; ?>
	</ul>
        </div>

    <?php endforeach; ?>
</div>
<?php endif;





}

function o66fswp_events_timeline(
	$repeater_field_name = 'events', $event_title_field_name = 'event_title',
	$event_date_field_name = 'event_date', $event_content_field_name = 'event_content', $post_id = null
) {
	global $post;

	if ( $post_id === null ) {
		$post_id = $post->ID;
	}
	if ( class_exists( 'acf' ) ) {
		if ( have_rows( $repeater_field_name ) ) : ?>
			<?php
			//Events Array Model
			$eventArray        = array();
			$yearsArray        = array();
			$datesArray        = array();
			$eventsByYearArray = array();

			//TODO:done PROCEDERE DA QUI FUNCTIONAL/MIDDLEWARE E GERETAI GLI ARRAY

			while ( have_rows( $repeater_field_name ) ) : the_row();
				// singlebyte strings
				//$result = substr($myStr, 0, 5);
				//setlocale(LC_TIME, 'it_IT.UTF8');
				$date          = get_sub_field( $event_date_field_name );
				$year          = substr( $date, 0, 4 );
				$eventArrayRow = array(
					'title'          => get_sub_field( $event_title_field_name ),
					'date'           => get_sub_field( $event_date_field_name ),
					// 'date-it' => date('d F Y',get_sub_field($event_date_field_name)),
					// $the_date = mysql2date( get_option( 'date_format' ), $post->post_date )
					'date-formatted' => mysql2date( get_option( 'date_format' ), get_sub_field( $event_date_field_name ) ),
					'content'        => get_sub_field( $event_content_field_name ),
					'year'           => $year
				);
				array_push( $eventArray, $eventArrayRow );
				array_push( $yearsArray, $year );
				array_push( $datesArray, $date );
			endwhile;
			$yearsArrayUnique = array_unique( $yearsArray );
			rsort( $yearsArrayUnique );
			//array_multisort($vc_array_value, SORT_DESC, $vc_array_order, SORT_DESC, $vc_array_name, SORT_ASC, $vc_array);
			array_multisort( $datesArray, SORT_DESC, $eventArray );
			array_multisort( $yearsArray, SORT_DESC, $eventArray );
			$totalEvents = count( $eventArray );
			function filter_events_by_year_array( $item ) {

			}


			//var_dump( $yearsArrayUnique );
			//TODO sistemare titoli a sinistra lunghezza scale ecc. come mobile magari
			?>
            <section class="entry-content__section entry-content__section--events-timeline-container">
                <div class="entry-content__section__header"><h2><?php echo 'La Storia'; ?></h2></div>
                <div class="blok">
					<?php
					$yearCount = 0;
					foreach ( $yearsArrayUnique as $year ) :
						//$thisYearsArray = array_fill( 0, $totalEvents, $year );
						$thisYearEventsArray = array_filter( $eventArray, function ( $item ) use ( $year ) {
							if ( $item['year'] === $year ) {
								return $item;
							} else {
								return null;
							}
						} );

						//	$eventsCurrentYear = array();


						?>
                        <div class="entry-content__section__row">
                            <div class="row">
                                <div class="col-md-3">
                                    <div class="events-timeline__year-title">
                                        <h4><i class="fa fa-calendar-o"></i> <?php echo $year; ?></h4>
                                    </div>
                                </div>
                                <div class="col-md-9">
									<?php
									//TODO SPOSTAMI NELLA MIA FUNZIONE APPENA FINISCI TIMELINE
									//accordion default a tipo load more
									//collegato con il js o66fs-template-tags.js
									//valutare css, magari da js
									//accordion-always
									//accordion-more
									//accordion-action-trigger che avrà un attributo opened, default false
									$accordionCount  = 0;
									$totalYearEvents = count( $thisYearEventsArray );
									foreach ( $thisYearEventsArray as $itemEvent ) :
										if ( $accordionCount === 0 ) {
											$data_accordion_always = 'true';
										}
										if ( $accordionCount > 0 ) {
											$data_accordion_always = 'false';
										}


										?>
                                        <div class="events-timeline__event_container"
                                             data-accordion-content="events-timeline-<?php echo $year; ?>"
                                             data-accordion-always="<?php echo $data_accordion_always; ?>">
                                            <p class="events-timeline_event-date"><i
                                                        class="fa fa-square"></i> <?php echo $itemEvent['date-formatted']; ?>
                                            </p>
                                            <h3 class="events-timeline_event-title"><?php echo $itemEvent['title']; ?></h3>
											<?php echo $itemEvent['content']; ?>
											<?php // var_dump( $itemEvent );
											?>
                                        </div>
										<?php $accordionCount ++; endforeach; ?>
                                    <div class="events-timeline__open-accordion-button-container">
										<?php
										$isOpened = false;
										if ( $yearCount === 0 ) {
											$isOpened = true;
										}
										if ( $yearCount !== 0 ) {
											$isOpened = false;
										}
										if ( $totalYearEvents > 1 ) {
											o66fpwp_a_button_accordion_action_trigger( 'Apri ' . $year, 'Chiudi ' . $year,
												'<i class="fa fa-arrow-circle-o-down"></i>', '<i class="fa fa-arrow-circle-o-up"></i>', false,
												'events-timeline-' . $year, $isOpened );
										}
										?>
                                    </div>
                                </div>
                            </div>
                        </div>
						<?php $yearCount ++; endforeach; ?>
                </div>
            </section>
			<?php //endwhile; ?>


		<?php endif;
	}
}
class o66_FieldSorter {
    public $field;

    function __construct($field) {
        $this->field = $field;
    }

    function cmp($a, $b) {
        if ($a[$this->field] == $b[$this->field]) return 0;
        return ($a[$this->field] > $b[$this->field]) ? 1 : -1;
    }
}