<?php

use GPLoker\Inc\Bookmark;
use GPLoker\Inc\Company;
use GPLoker\Inc\Job;

function default_notice() {
	$class   = 'notice notice-error';
	$message = __( 'Irks! An error has occurred.', 'sample-text-domain' );

	printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( $message ) );
}

function GPLokerOption($name, $default = null) {
    return GPLoker\Inc\Option::get($name, $default);
}

/** Loker Function Helper */
function GPLokerGetCurrentJob() {
	global $post;
    
    if ( empty($_GLOBAL['jobs']) ) {
        $_GLOBAL['jobs'] = Job::get( $post );
    }
    
	return $_GLOBAL['jobs'];
}

function GPLokerSearchForm() {
	get_template_part( 'template-part/form-search' );
}

function GPLokerGetRecentJobs( $posts_per_page = 10, $showSticky = false ) {
    
    $args = [
		'post_type'      => 'lowongan',
		'posts_per_page' => $posts_per_page
	];
	
	$args['meta_query']     = [
        'relation' => 'OR',
        [
            'key'     => 'gplokerpro_is_sticky',
            'compare' => 'NOT EXISTS'
        ],
        [
            'key'     => 'gplokerpro_is_sticky',
            'value'   => 'on',
            'compare' => '!='
        ]
    ];
    
	if ( $showSticky ) {
	    
	    $stickiesId = \GPLoker\Inc\Hooks::getAllStickyJobsId();
    
        if ( ! empty($stickiesId) && is_array($stickiesId) ) {
            $posts_per_page = $posts_per_page - count($stickiesId);
            $args['post__not_in'] = $stickiesId;
            $args['posts_per_page'] = $posts_per_page;
        }
    
	}
	
    
	$loker = new WP_Query( $args );

	if ( $loker->have_posts() ) {
	    
	    if ($showSticky) {
	        
	        global $post;
            $originPosts = $post;
            
            foreach ($stickiesId as $postId) {
                $post = get_post($postId);
                get_template_part( 'template-part/content', 'job-item' );
            }
            
            $GLOBALS['post'] = $originPosts;
	        
	    }
	    
		while ( $loker->have_posts() ) {
			$loker->the_post();
			get_template_part( 'template-part/content', 'job-item' );
		}
	}

	wp_reset_postdata();
}

function GPLokerJobsByCategories( $slug, $posts_per_page = 10 ) {
	$loker = new WP_Query( [
		'post_type'      => 'lowongan',
		'posts_per_page' => $posts_per_page,
		'tax_query' => array(
			array(
				'taxonomy' => 'loker-category',
				'field' => 'slug',
				'terms' => explode(',', $slug),
			),
		),
	] );

	if ( $loker->have_posts() ) {
		while ( $loker->have_posts() ) {
			$loker->the_post();
			get_template_part( 'template-part/content', 'job-item' );
		}
	}

	wp_reset_postdata();
}

function GPLokerJobsByTags( $slug, $posts_per_page = 10 ) {
	$loker = new WP_Query( [
		'post_type'      => 'post',
		'posts_per_page' => $posts_per_page,
		'tax_query' => array(
			array(
				'taxonomy' => 'loker-tags',
				'field' => 'slug',
				'terms' => explode(',', $slug),
			),
		),
	] );

	if ( $loker->have_posts() ) {
		while ( $loker->have_posts() ) {
			$loker->the_post();
			get_template_part( 'template-part/content', 'job-item' );
		}
	}

	wp_reset_postdata();
}

function GPLokerJobsByLocations( $slug, $posts_per_page = 10 ) {
	$loker = new WP_Query( [
		'post_type'      => 'lowongan',
		'posts_per_page' => $posts_per_page,
		'tax_query' => array(
			array(
				'taxonomy' => 'location',
				'field' => 'slug',
				'terms' => explode(',', $slug),
			),
		),
	] );

	if ( $loker->have_posts() ) {
		while ( $loker->have_posts() ) {
			$loker->the_post();
			get_template_part( 'template-part/content', 'job-item' );
		}
	}

	wp_reset_postdata();
}

function GPLokerFeaturedJobs( $posts_per_page = 10 ) {
	$loker = new WP_Query( [
		'post_type'      => 'lowongan',
		'posts_per_page' => $posts_per_page,
        'meta_key' => 'featured_jobs',
        'meta_value' => '1',
        'meta_compare' => '=',
	] );

	if ( $loker->have_posts() ) {
		while ( $loker->have_posts() ) {
			$loker->the_post();
			get_template_part( 'template-part/content', 'job-item' );
		}
	}

	wp_reset_postdata();
}

function GPLokerJobsByBookmark( $posts_per_page = 10 ) {
	$bookmark = Bookmark::get();

	if ( ! empty($bookmark) ) {
		$loker = new WP_Query( [
			'post_type'      => 'lowongan',
			'posts_per_page' => $posts_per_page,
			'post__in'       => $bookmark
		] );

		if ( $loker->have_posts() ) {
			while ( $loker->have_posts() ) {
				$loker->the_post();
				get_template_part( 'template-part/content', 'job-item' );
			}
		}

		wp_reset_postdata();
	}
}

function GPLokerRelatedJobs() {
	$html = '';
	if ( is_singular('lowongan') ) {
		global $post;
		$categories = get_the_terms($post, 'loker-category');

		$cat_ids = [];
		if ( $categories && ! is_wp_error($categories) ) {
			foreach ( $categories as $cat ) {
				$cat_ids[] = $cat->term_id;
			}

			$query = new WP_Query( [
				'post_type' => 'lowongan',
				'post__not_in' => [ $post->ID ],
				'tax_query' => array(
					array(
						'taxonomy' => 'loker-category',
						'field' => 'term_id',
						'terms' => $cat_ids,
					),
				),
			] );

			if ( $query->have_posts() ) {

				while ( $query->have_posts() ) {
					$query->the_post();
					get_template_part( 'template-part/content', 'job-item' );
				}

				wp_reset_postdata();
			}
		}

	}
}

function GPLokerGetCompanyById( $company_id ) {
	return Company::get( $company_id );
}

function GPLokerJobsByCurrentCompany( $posts_per_page = 10 ) {
	global $post;
	$loker = new WP_Query( [
		'post_type'      => 'lowongan',
		'posts_per_page' => $posts_per_page,
		'meta_key'       => 'company',
		'meta_value'     => $post->ID
	] );

	if ( $loker->have_posts() ) {
		while ( $loker->have_posts() ) {
			$loker->the_post();
			get_template_part( 'template-part/content', 'job-item' );
		}
	}

	wp_reset_postdata();
}

function GPLokerGetJobsCountByCompany( $company_id ) {
    global $wpdb;
    
    return (int) $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->postmeta WHERE meta_key = 'company' AND meta_value = '{$company_id}'" );
}

/**
 * Blogpost Function Helper
 */
function GPLokerGetFeaturedBlogposts( $posts_per_page = 10 ) {
	$posts = new WP_Query( [
		'post_type'      => 'post',
		'posts_per_page' => $posts_per_page,
	] );

	if ( $posts->have_posts() ) {
		while ( $posts->have_posts() ) {
			$posts->the_post();
			the_title();

		}

		wp_reset_postdata();
	}
}

/**
 * Taxonomies Function Helper
 */
function GPLokerGetTaxonomies( $taxonomy = 'loker-category', $number = 0, $parent_only = false ) {
	$args = array(
		'taxonomy' => $taxonomy,
	);

	if ( $parent_only ) {
		$args['parent'] = 0;
	}

	if ( $number ) {
		$args['number'] = (int) $number;
	}

	$terms      = get_terms( $args );
	$taxonomies = [];

	if ( ! is_wp_error( $terms ) ) {
		foreach ( $terms as $term ) {
			$taxonomies[] = [
				'ID'        => $term->term_id,
				'slug'      => $term->slug,
				'name'      => $term->name,
				'icon'      => GPLokerGetCategoryIcon( $term->term_id ),
				'link'      => get_term_link( $term ),
				'parent_id' => $term->parent,
				'count'     => $term->count
			];
		}
	}


	return $taxonomies;
}

/**
 * Categories Function Helper
 */

function GPLokerGetCategoryIcon( $term_id ) {
	return get_term_meta( $term_id, 'icon', true );
}

function GPLokerGetCategories($number = 0) {
	return GPLokerGetTaxonomies( 'loker-category', $number );
}

function GPLokerSelectCategories( $selected = '', $placeholder = 'Kategori', $class = '' ) {
	$categories = GPLokerGetCategories();
	$options    = '<option value="">' . $placeholder . "</option>";

	if ( $categories ) {
		$format = '<option value="%s" %s>%s</option>';
		foreach ( $categories as $category ) {
			$options .= sprintf( $format, $category['slug'], $selected == $category['slug'] ? ' selected' : '', $category['name'] );
		}

		if ( $options ) {
			$options = '<select class="' . $class . '" name="category">' . $options . '</select>';
		}
	}

	echo $options;
}

/**
 * Location Function Helper
 */
function GPLokerGetLocation() {
	static $location;
	if ( empty( $location ) ) {
		$args = array(
			'taxonomy' => 'location',
			'orderby'  => 'parent',
			'order'    => 'asc'
		);

		$terms = get_terms( $args );

		$location = [];
		if ( ! is_wp_error( $terms ) ) {
			foreach ( $terms as $term ) {
				$location[ $term->term_id ]       = $term;
				$location[ $term->term_id ]->link = get_term_link( $term );
			}
		}

		if ( ! empty( $location ) ) {
			foreach ( $location as $term ) {
				if ( $term->parent ) {
					$parent                           = $location[ $term->parent ];
					$location[ $term->term_id ]->name = $parent->name . '&raquo;' . $term->name;
				}
			}
		}

	}

	return $location;
}

function GPLokerSelectLocation( $selected = '', $placeholder = 'Lokasi', $class = '' ) {
	$locations = GPLokerGetLocation();
	$options   = '<option value="">' . $placeholder . '</option>';

	$format = '<option value="%s"%s>%s</option>';
	foreach ( $locations as $location ) {
		$options .= sprintf( $format, $location->slug, $location->slug == $selected ? ' selected' : '', $location->name );
	}

	echo '<select name="location" class="' . $class . '">' . $options . '</select>';
}

/**
 * Tags Function Helper
 */
function GPLokerGetRandomLokerTags( $term, $hidden_empty = false ) {
	global $wpdb;
	$sql = "SELECT terms.term_id, name, slug, description, count FROM {$wpdb->terms} as terms 
			INNER JOIN {$wpdb->term_taxonomy} as term_taxonomy ON terms.term_id = term_taxonomy.term_id
			WHERE taxonomy = '{$term}'";

	if ( $hidden_empty ) {
		$sql .= " AND count > 0 ";
	}

	return $wpdb->get_results( $sql );
}

function GPLokerTags() {
	$tag_loker = GPLokerGetRandomLokerTags( 'loker-tags', true );
	foreach ( $tag_loker as $loker ) {
		printf( '<span><a href="%s">%s</a></span>', get_term_link( $loker->slug ), $loker->name );
	}
}

/**
 * Companies Function Helper
 */
function GPLokerCompanies( $posts_per_page = '-1') {
	echo GPLokerGetCompanies( $posts_per_page );
}

function GPLokerGetCompanies( $posts_per_page = 10 ): string {
	$html = '';

	$companies = new WP_Query( [
		'post_type'      => 'companies',
		'posts_per_page' => $posts_per_page
	] );

	if ( $companies->have_posts() ) {
		$default_thumb = '//placehold.co/300';

		$html .= '<div class="company-listing">';
		$html .= '<div class="gploker-companies-lists">';
		while ( $companies->have_posts() ) {
			$companies->the_post();
			$html .= '<div class="company-item">';
			$html .= '<a href="' . get_permalink() . '">';

			$html .= '<div class="company-logo">';
			
			$thumbanil_url = get_the_post_thumbnail_url(get_the_ID(), 'thumbnail');
			
			$html .= sprintf('<img src="%s" alt="Lowongan Kerja di %s">', $thumbanil_url
				? $thumbanil_url
				: $default_thumb, get_the_title());
				
			$html .= '</div>';

			$html .= '<div class="company-name">' . get_the_title() . '</div>';
			
			$html .= '<div class="jobs-by-company">(' . GPLokerGetJobsCountByCompany( get_the_ID() ) . ') Lowongan</div>';

			$html .= '</a></div>';
		}

		$html .= '</div></div>';
		wp_reset_postdata();
	}

	return $html;
}

/**
 * Social Media Share Function Helper
 */
function GPLokerSocialMediaShare( $echo = true ) {

	if ( shortcode_exists('addtoany') ) {
		if ( $echo ) {
			echo do_shortcode('[addtoany]');
		} else {
			return do_shortcode('[addtoany]');
		}
	}

	return '';
}

function GPLokerCurrency( $float ) {
	return 'Rp ' . number_format($float, 0,',', '.');
}

if ( ! function_exists( 'neon_pagination' ) ) {
	function neon_pagination( $query = null ) {
		if ( empty( $query ) ) {
			global $wp_query;
			$query = $wp_query;
		}

		$total = $query->max_num_pages;

		if ( $total > 1 ) {
			$is_static_page = get_query_var( 'page' );
			if ( empty( $is_static_page ) ) {
				$current_page = get_query_var( 'paged' ) ?: 1;
			} else {
				$current_page = $is_static_page;
			}

			// Structure of “format” depends on whether we’re using pretty permalinks
			$format = empty( get_option( 'permalink_structure' ) ) ? '&page=%#%' : 'page/%#%/';

			return paginate_links( array(
				'base'      => get_pagenum_link( 1 ) . '%_%',
				'format'    => $format,
				'current'   => $current_page,
				'total'     => $total,
				'prev_text' => apply_filters( 'neon_prev_nav', '&laquo; Sebelumnya' ),
				'next_text' => apply_filters( 'neon_next_nav', 'Berikutnya &raquo;' ),
				'mid_size'  => 4,
				'type'      => 'list'
			) );
		}
	}
}

function GPLokerGetAds1() {
    return do_shortcode( GPLokerOption( 'place_ads1' ) );
}

function GPLokerGetAds2() {
    return do_shortcode( GPLokerOption( 'place_ads2' ) );
}

/**
 * Digunakan untuk menerjemahkan variable :
 * <code>{{JOB_POSITION}}</code>, <code>{{COMPANY_NAME}}</code> dan <code>{{EXPIRED_DATE}}</code>
 * <code>{{LINK_APPLY}}</code>
 * 
 * @return string
 */ 
function GPLokerVaribleDynamic($string, $post = null) {
    $job = Job::get( $post ); 
    
	$link_apply = 'Belum Disetting';
	if ( $links = $job->getApplyLinks() ) {
	    $link_apply = '<div class="link-apply-wrap"><ul class="link-apply">';
	    
	    foreach ( $links as $link ) {
	        $link_apply .= sprintf('<li><a target="_blank" href="%s">%s</a></li>', $link['link_content'], $link['link_title']);
	    }
	    
		$link_apply .= '</ul></div>';
	}
    
    $parse_job_variables = [
        'LINK_APPLY'   => $link_apply,
        'EXPIRED_DATE' => $job->getValidThrough( 'd M Y 23:59' ) ?: '--',
        'JOB_POSITION' => $job->getPosition(),
        'COMPANY_NAME' => $job->getCompanyName()
     ];
     
    foreach($parse_job_variables as $variable => $value) {
        $string = str_replace('{{'. $variable .'}}', $value, $string);
    }
    
    return $string;
}

/**
 * Digunakan untuk menampilkan Notes 
 * 
 * @return string|HTML
 */ 
function GPLokerGetNotes( $post = null ) {
    $message = '';
 
    if ( GPLokerOption('show_notes') ) {
        $message = GPLokerOption('notes');
        $message = GPLokerVaribleDynamic($message);
    }
    
    return $message;
}

/**
 * Digunakan untuk menampilkan hasil GPlokerGetNotes
 * 
 */ 
function GPLokerNotes( $before='<div class="gploker-notes-wrap">', $after = '</div>' ) {
    if ( $message = GPLokerGetNotes() ) {
        echo $before . $message . $after; 
    }
}

function GPLokerTimeAgo() {

    global $post;
    $timestamp = strtotime($post->post_date);

    $currentTime    = current_time('timestamp');
    $timeDifference = $currentTime - $timestamp;

    $seconds      = $timeDifference;
    $minutes      = round($seconds / 60);
    $hours        = round($seconds / 3600);
    $days         = round($seconds / 86400);
    $weeks        = round($seconds / 604800);
    $months       = round($seconds / 2629440);
    $years        = round($seconds / 31553280);

    if ($seconds <= 60) {
        return "Baru saja";
    } else if ($minutes <= 60) {
        if ($minutes == 1) {
            return "1 Menit yang lalu";
        } else {
            return "$minutes Menit yang lalu";
        }
    } else if ($hours <= 24) {
        if ($hours == 1) {
            return "1 Jam yang lalu";
        } else {
            return "$hours Jam yang lalu";
        }
    } else if ($days <= 7) {
        if ($days == 1) {
            return "Kemarin";
        } else {
            return "$days Hari yang lalu";
        }
    } else if ($weeks <= 4.3) {
        if ($weeks == 1) {
            return "1 Minggu yang lalu";
        } else {
            return "$weeks Minggu yang lalu";
        }
    } else if ($months <= 12) {
        if ($months == 1) {
            return "1 Bulan yang lalu";
        } else {
            return "$months Bulan yang lalu";
        }
    } else {
        if ($years == 1) {
            return "1 Tahun yang lalu";
        } else {
            return "$years Tahun yang lalu";
        }
    }

    return get_the_date();
}