<?php
if ( ! function_exists( 'wpj_insert_feature_purchase_order' ) ) {
	function wpj_insert_feature_purchase_order( $args = [] ) {
		// Payment info
		$payment_status  = ! empty( $args['payment_status'] ) ? $args['payment_status'] : 'pending';
		$payment_gateway = ! empty( $args['payment_gateway'] ) ? $args['payment_gateway'] : WPJ_Form::get( 'pay_for_item' );

		// Currency
		$currency = ! empty( $args['currency'] ) ? $args['currency'] : apply_filters( 'wpjobster_take_allowed_currency_' . $payment_gateway, '' );

		if ( empty( $currency ) ) $currency = wpj_get_site_currency();

		// Featured pages
		$feature_pages = ! empty( $args['feature_pages'] ) ? $args['feature_pages'] : WPJ_Form::get( 'feature_pages');

		// Job info
		$jobid = ! empty( $args['jobid'] ) ? $args['jobid'] : WPJ_Form::get( 'jobid' );

		if ( ! $jobid ) {
			global $wp_query;

			$jobid = isset( $wp_query->query_vars['jobid'] ) ? $wp_query->query_vars['jobid'] : '';
		}

		$jobid = wpj_get_post_id( $jobid );

		// User info
		$user_id = ! empty( $args['user_id'] ) ? $args['user_id'] : get_current_user_id();

		// Featured amount
		$featured_amount = 0;

		if ( strpos( $feature_pages ,'h' ) !== false )
			$featured_amount += wpj_get_option( 'wpjobster_featured_price_homepage' );

		if ( strpos( $feature_pages ,'c' ) !== false )
			$featured_amount += wpj_get_option( 'wpjobster_featured_price_category' );

		if ( strpos( $feature_pages ,'s' ) !== false )
			$featured_amount += wpj_get_option( 'wpjobster_featured_price_subcategory' );

		$featured_amount_exchanged = wpj_number_format_special_exchange( $featured_amount, '1', $currency );

		// Date info
		$added_on = ! empty( $args['added_on'] ) ? $args['added_on'] : current_time( 'timestamp', 1 );

		// Date start
		$h_date_start = ! empty( $args['h_date_start'] ) ? $args['h_date_start'] : WPJ_Form::get( 'h_date_start' );
		$c_date_start = ! empty( $args['c_date_start'] ) ? $args['c_date_start'] : WPJ_Form::get( 'c_date_start' );
		$s_date_start = ! empty( $args['s_date_start'] ) ? $args['s_date_start'] : WPJ_Form::get( 's_date_start' );

		// Buyer Fee
		$processing_fees = ! empty( $args['processing_fees'] ) ? $args['processing_fees'] : '';

		if ( ! $processing_fees )
			$processing_fees = wpj_get_site_processing_fee_by_amount( $featured_amount, 0, 0 );

		$processing_fees_exchanged = wpj_number_format_special_exchange( $processing_fees, '1', $currency );

		// Tax
		$tax = ! empty( $args['tax'] ) ? $args['tax'] : '';

		if ( ! $tax )
			$tax = wpj_get_site_tax_by_amount( $featured_amount, 0, 0, $processing_fees );

		$tax_exchanged = wpj_number_format_special_exchange( $tax, '1', $currency );

		// Final order price
		$payable_amount = ! empty( $args['payable_amount'] ) ? $args['payable_amount'] : '';

		if ( ! $payable_amount )
			$payable_amount = $featured_amount + $tax + $processing_fees;

		$payable_amount_exchanged = $featured_amount_exchanged + $processing_fees_exchanged + $tax_exchanged;

		// Decrease credits if payment method is Account Balance
		if ( $payment_gateway == 'credits' ) {
			$user_credit = wpj_get_user_credit( $user_id );

			if ( $payable_amount > $user_credit ) {
				wp_redirect( wpj_get_payment_link() . 'topup?no_credits=1' ); exit;
			}

			wpj_update_user_credit( $user_id, $user_credit - $payable_amount );
		}

		// Insert order to database
		$orderid = wpj_insert_feature_order(
			[
				'feature_pages'        => $feature_pages,
				'job_id'               => $jobid,
				'user_id'              => $user_id,
				'featured_amount'      => $featured_amount,
				'added_on'             => $added_on,
				'payment_status'       => $payment_status,
				'payment_gateway_name' => $payment_gateway,
				'h_date_start'         => $h_date_start,
				'c_date_start'         => $c_date_start,
				's_date_start'         => $s_date_start,
				'tax'                  => $tax_exchanged,
				'payable_amount'       => $payable_amount_exchanged,
				'currency'             => $currency,
			],
			['%s', '%d', '%d', '%f', '%d', '%s', '%s', '%d', '%d', '%d', '%f', '%f', '%s']
		);

		do_action( 'wpj_after_insert_feature_order', $orderid );

		// Insert payment to database
		wpj_insert_payment(
			[
				'payment_status'         => $payment_status == 'completed' ? 1 : 0,
				'payment_gateway'        => $payment_gateway,
				'payment_type'           => 'feature',
				'payment_type_id'        => $orderid,
				'fees'                   => $processing_fees,
				'amount'                 => $featured_amount,
				'datemade'               => current_time( 'timestamp', 1 ),
				'tax'                    => $tax,
				'currency'               => wpj_get_site_default_currency(),
				'final_amount'           => $payable_amount,
				'final_amount_exchanged' => $payable_amount_exchanged,
				'final_amount_currency'  => $currency,
			],
			['%d', '%s', '%s', '%d', '%f', '%f', '%d', '%f', '%s', '%f', '%f', '%s']
		);

		return $orderid;
	}
}

if ( ! function_exists( 'wpj_is_featured_available' ) ) {
	function wpj_is_featured_available( $pid = '', $type = false ) {
		$pid = wpj_get_post_id( $pid );

		$home_featured        = get_post_meta( $pid, 'home_featured_until', true );
		$category_featured    = get_post_meta( $pid, 'category_featured_until', true );
		$subcategory_featured = get_post_meta( $pid, 'subcategory_featured_until', true );

		if ( ( ! $type || $type == 'h' ) && ( $home_featured == 'z' || $home_featured == false ) )
			return true;

		if ( ( ! $type || $type == 'c' ) && ( $category_featured == 'z' || $category_featured == false ) )
			return true;

		if ( ( ! $type || $type == 's' ) && ( $subcategory_featured == 'z' || $subcategory_featured == false ) )
			return true;

		return false;
	}
}

if ( ! function_exists( 'wpj_featured_category_enabled_exist' ) ) {
	function wpj_featured_category_enabled_exist() {
		if ( wpj_get_option( 'wpjobster_homepage_featured_enable' ) == 'yes' )
			return true;

		if ( wpj_get_option( 'wpjobster_category_featured_enable' ) == 'yes' )
			return true;

		if ( wpj_get_option( 'wpjobster_subcategory_featured_enable' ) == 'yes' )
			return true;

		return false;
	}
}

if ( ! function_exists( 'wpj_get_feature_keys_by_page' ) ) {
	function wpj_get_feature_keys_by_page( $page, $pid ) {
		$until_key        = '';
		$featured_now_key = '';
		$terms            = get_the_terms( $pid, 'job_cat' );

		if ( $terms ) {
			$term  = get_term_by( 'id', $terms[0]->term_id, 'job_cat' );

			$p = get_term( $term->parent, 'job_cat' );

			if ( empty( $p->term_id ) ) {
				$category_id    = ! empty( $terms[0] ) ? $terms[0]->term_id : '';
				$subcategory_id = ! empty( $terms[1] ) ? $terms[1]->term_id : '';

			} else {
				$category_id    = ! empty( $terms[1] ) ? $terms[1]->term_id : '';
				$subcategory_id = ! empty( $terms[0] ) ? $terms[0]->term_id : '';

			}

			if ( ! empty( $page ) ) {
				if ( $page == 'homepage' ) {
					$max_number_key   = 'wpjobster_featured_homepage';
					$until_key        = 'home_featured_until';
					$featured_now_key = 'home_featured_now';

				} elseif ( $page == 'category' ) {
					$max_number_key   = 'wpjobster_featured_category';
					$until_key        = 'category_featured_until';
					$featured_now_key = 'category_featured_now';

				} elseif ( $page == 'subcategory' ) {
					$max_number_key   = 'wpjobster_featured_subcategory';
					$until_key        = 'subcategory_featured_until';
					$featured_now_key = 'subcategory_featured_now';

				}

				if ( empty( $max_number_key ) ) {
					return false;
				}

				return [
					'taxonomy'         => 'job_cat',
					'category_id'      => $category_id,
					'subcategory_id'   => $subcategory_id,
					'max_number_key'   => $max_number_key,
					'until_key'        => $until_key,
					'featured_now_key' => $featured_now_key
				];
			}
		}

		return false;
	}
}

if ( ! function_exists( 'wpj_get_feature_info_for_email' ) ) {
	function wpj_get_feature_info_for_email( $pid, $info = '' ) {
		if ( get_post_meta( $pid, 'home_featured_until', true ) != 'z' && get_post_meta( $pid, 'home_featured_until', true ) ) {
			$info .= sprintf( __( "Featured on homepage between: %s - %s", "wpjobster" ), wpj_date( wpj_get_option( 'date_format' ), wpj_get_featured_start_date_from_end_date( get_post_meta( $pid, 'home_featured_until', true ) ) ), wpj_date( wpj_get_option( 'date_format' ), get_post_meta( $pid, 'home_featured_until', true ) ) );
		}

		if ( get_post_meta( $pid, 'category_featured_until', true ) != 'z' && get_post_meta( $pid, 'category_featured_until', true ) ) {
			$info .= sprintf( __( "Featured on category page between: %s - %s", "wpjobster" ), wpj_date( wpj_get_option( 'date_format' ), wpj_get_featured_start_date_from_end_date( get_post_meta( $pid, 'category_featured_until', true ) ) ), wpj_date( wpj_get_option( 'date_format' ), get_post_meta( $pid, 'category_featured_until', true ) ) );
		}

		if ( get_post_meta( $pid, 'subcategory_featured_until', true ) != 'z' && get_post_meta( $pid, 'subcategory_featured_until', true ) ) {
			$info .= sprintf( __( "Featured on subcategory page between: %s - %s", "wpjobster" ), wpj_date( wpj_get_option( 'date_format' ), wpj_get_featured_start_date_from_end_date( get_post_meta( $pid, 'subcategory_featured_until', true ) ) ), wpj_date( wpj_get_option( 'date_format' ), get_post_meta( $pid, 'subcategory_featured_until', true ) ) );
		}

		return $info;
	}
}

if ( ! function_exists( 'wpj_get_feature_title_by_pages' ) ) {
	function wpj_get_feature_title_by_pages( $feature_pages = '', $order = '' ) {
		if ( ! $feature_pages && isset( $_GET['feature_pages'] ) )
			$feature_pages = $_GET['feature_pages'];

		if ( ! $feature_pages && isset( $order->feature_pages ) )
			$feature_pages = $order->feature_pages;

		if ( strpos( $feature_pages, 'h' ) !== false && strpos( $feature_pages, 'c' ) !== false && strpos( $feature_pages, 's' ) !== false )
			$title = __( 'Featured on homepage, category and subcategory', 'wpjobster' );

		elseif ( strpos( $feature_pages, 'h' ) !== false && strpos( $feature_pages, 'c' ) !== false )
			$title = __( 'Featured on homepage and category', 'wpjobster' );

		elseif ( strpos( $feature_pages, 'c' ) !== false && strpos( $feature_pages, 's' ) !== false )
			$title = __( 'Featured on category and subcategory', 'wpjobster' );

		elseif ( strpos( $feature_pages, 's' ) !== false && strpos( $feature_pages, 'h' ) !== false )
			$title = __( 'Featured on homepage and subcategory', 'wpjobster' );

		elseif ( strpos( $feature_pages, 'h' ) !== false )
			$title = __( 'Featured on homepage', 'wpjobster' );

		elseif ( strpos( $feature_pages, 'c' ) !== false )
			$title = __( 'Featured on category', 'wpjobster' );

		elseif ( strpos( $feature_pages, 's' ) !== false )
			$title = __( 'Featured on subcategory' ,'wpjobster' );

		else
			$title = '';

		return $title;
	}
}

if ( ! function_exists( 'wpj_get_featured_start_date' ) ) {
	function wpj_get_featured_start_date( $page, $pid ) {
		$f_info = wpj_get_feature_keys_by_page( $page, $pid );

		if ( $f_info ) {
			$featured_query = new WP_Query([
				'posts_per_page' => '-1',
				'post_type'      => 'job',
				'post_status'    => 'publish',
				'meta_query'     => [
					[
						'key'     => ( $page == 'homepage' ? 'home' : $page ) . '_featured_now',
						'value'   => 'y',
						'type'    => 'meta_value',
						'compare' => '='
					],
				],
			]);

			$featured_count = $featured_query->have_posts() ? $featured_query->post_count : 0;

			if ( $featured_count < wpj_get_option( $f_info['max_number_key'] ) ) {
				return wpj_get_midnight_date_timestamp( current_time( 'timestamp', 1 ) );

			} else {
				$tax_query = [];

				if ( $page == 'category' ) {
					$tax_query = [['taxonomy' => $f_info['taxonomy'], 'terms' => $f_info['category_id'], 'field' => 'term_id']];

				} elseif ( $page == 'subcategory' ) {
					$tax_query = [['taxonomy' => $f_info['taxonomy'], 'terms' => $f_info['subcategory_id'], 'field' => 'term_id']];

				}

				$meta_query = [['key' => $f_info['until_key'], 'value' => 'z', 'compare' => '!=']];

				$loop = new WP_Query([
					'post_type'      => 'job',
					'posts_per_page' => $f_info['max_number_key'],
					'tax_query'      => $tax_query,
					'meta_query'     => $meta_query,
					'meta_key'       => $f_info['until_key'],
					'orderby'        => 'meta_value_num',
					'order'          => 'DESC',
				]);

				$loop_posts = $loop->posts;

				if ( $loop->have_posts() ) {
					// Avoid setting up postdata with $loop->the_post(), because reset doesn't work in admin!
					foreach ( $loop_posts as $loop_post ) {
						$start_date = wpj_get_midnight_date_timestamp( strtotime( "+1 day", get_post_meta( $loop_post->ID, $f_info['until_key'], true ) ) );
					}
				}

				return isset( $start_date ) ? $start_date : strtotime( date( 'Y-m-d H:i:s' ) );
			}

		} else {
			return strtotime( date( 'Y-m-d H:i:s' ) );

		}
	}
}

if ( ! function_exists( 'wpj_get_featured_end_date' ) ) {
	function wpj_get_featured_end_date( $start_date ) {
		return wpj_get_midnight_date_timestamp( strtotime( '+' . ( wpj_get_option( 'wpjobster_featured_interval' ) - 1 ) . ' day', intval( $start_date ) ) );
	}
}

if ( ! function_exists( 'wpj_get_featured_start_date_from_end_date' ) ) {
	function wpj_get_featured_start_date_from_end_date( $end_date ) {
		return wpj_get_midnight_date_timestamp( strtotime( '-' . ( wpj_get_option( 'wpjobster_featured_interval' ) - 1 ) . ' day', intval( $end_date ) ) );
	}
}

if ( ! function_exists( 'wpj_cancel_featured_order' ) ) {
	function wpj_cancel_featured_order( $order_id = '' ) {
		if ( ! $order_id ) $order_id = $_REQUEST['order_id'];

		wpj_update_feature_order( ['payment_status' => 'cancelled'], ['id' => $order_id] );

		do_action( 'wpj_after_order_is_cancelled', $order_id, 'feature' );

		if ( wpj_is_ajax_call() ) wp_die();
	}
}

if ( ! function_exists( 'wpj_mark_job_as_featured' ) ) {
	function wpj_mark_job_as_featured( $page, $pid ) {
		$f_info       = wpj_get_feature_keys_by_page( $page, $pid );
		$h_start_date = wpj_get_featured_start_date( $page, $pid );

		$interval = wpj_get_option( 'wpjobster_featured_interval' ) - 1;
		$new_date = strtotime( '+' . $interval . ' day', $h_start_date );

		update_post_meta( $pid, $f_info['until_key'], $new_date );

		if ( $h_start_date == wpj_get_midnight_date_timestamp( time() ) ) {
			update_post_meta( $pid, $f_info['featured_now_key'], 'y' );
		}
	}
}