<?php
if ( ! function_exists( 'wpj_create_job_post_id' ) ) {
	function wpj_create_job_post_id() {
		// Init new post
		if ( ! isset( $_GET['jobid'] ) ) {
			$pid = wpj_get_auto_draft_post( get_current_user_id(), 'job' );

			update_post_meta( $pid, 'home_featured_now', 'z' );
			update_post_meta( $pid, 'category_featured_now', 'z' );
			update_post_meta( $pid, 'subcategory_featured_now', 'z' );

			$args = ['jobid' => $pid];

			if ( ! empty( $_GET['category'] ) ) {
				$args['category'] = $_GET['category'];
			}

			wp_redirect(
				add_query_arg(
					$args,
					get_permalink( wpj_get_option( 'wpjobster_post_new_page_id' ) )
				)
			);

			exit;
		}

		// Double check that we are on the right page
		$pid = WPJ_Form::get( 'jobid' );

		if ( WPJ_Form::get( 'action' ) != 'edit-job' ) {
			$last_draft = wpj_get_post( 'ID', ['post_type' => 'job', 'post_status' => 'auto-draft', 'post_author' => get_current_user_id()], 'row', 'ID DESC' );

			if ( ( isset( $last_draft->ID ) && $last_draft->ID > $pid ) || get_current_user_id() != get_post_field( 'post_author', $pid ) ) {
				$args = ['jobid' => $last_draft->ID];

				if ( ! empty( $_GET['category'] ) ) {
					$args['category'] = $_GET['category'];
				}

				wp_redirect(
					add_query_arg(
						$args,
						get_permalink( wpj_get_option( 'wpjobster_post_new_page_id' ) )
					)
				);

				exit;
			}
		}
	}
}

if ( ! function_exists( 'wpj_activate_job' ) ) {
	function wpj_activate_job( $pid = '', $reason = '' ) {
		if ( is_user_logged_in() ) {
			if ( ! $reason ) $reason = 'by_user';

			$pid = WPJ_Form::post( 'post_id', $pid );

			if ( ! $pid ) $pid = wpj_get_post_id();

			$post = get_post( $pid );

			$active_jobs_enabled = wpj_get_user_feature_status( 'wpjobster_enable_active_jobs', 'wpjobster_subscription_active_jobs_enabled' );
			$active_jobs_max     = wpj_get_user_feature_value( 'active_jobs', 'active_jobs' );
			$active_jobs_cnt     = intval( wpj_get_user_jobs_count( get_current_user_id(), 'active' ) );

			if ( $post->post_author == get_current_user_id() || current_user_can( 'administrator' ) ) {
				if ( wpj_is_user_allowed_post_job( $post->post_author, get_post_meta( $pid, 'price', true ) ) || current_user_can( 'administrator' ) ) {
					if ( ( $active_jobs_enabled == 'yes' && $active_jobs_cnt < $active_jobs_max ) || $active_jobs_enabled == 'no' ) {
						update_post_meta( $pid, 'active', 1 );
						update_post_meta( $pid, 'activate_reason', $reason );
						delete_post_meta( $pid, 'deactivation_reason' );

						if ( wpj_is_ajax_call() ) echo 1;

					} elseif ( wpj_is_ajax_call() ) echo 'active_jobs_exceeded';

				} elseif ( wpj_is_ajax_call() ) echo 'no_credits';

			} elseif ( wpj_is_ajax_call() ) echo 'not_your_post';

		} elseif ( wpj_is_ajax_call() ) echo 'not_logged_in';

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

if ( ! function_exists( 'wpj_activate_all_jobs' ) ) {
	function wpj_activate_all_jobs( $user_id = '', $reason = '' ) {
		$reason  = isset( $_POST['reason'] ) ? $_POST['reason'] : $reason;
		$user_id = isset( $_POST['user_id'] ) ? $_POST['user_id'] : $user_id;

		if ( ! $user_id ) $user_id = get_current_user_id();

		$args = [
			'post_type'      => 'job',
			'posts_per_page' => -1,
			'post_status'    => ['publish', 'pending', 'draft', 'auto-draft', 'future', 'private', 'inherit', 'trash'],
			'meta_query'     => [
				[
					'key'     => 'active',
					'value'   => '0',
					'compare' => '=',
				],
			],
		];

		if ( $user_id && $user_id != 'all' ) $args['author'] = $user_id;

		$posts = get_posts( $args );

		if ( $posts && is_user_logged_in() && ( get_current_user_id() == $user_id || current_user_can( 'administrator' ) ) ) {
			$active_jobs_enabled = wpj_get_user_feature_status( 'wpjobster_enable_active_jobs', 'wpjobster_subscription_active_jobs_enabled' );
			$active_jobs_max     = wpj_get_user_feature_value( 'active_jobs', 'active_jobs' );
			$active_jobs_cnt     = intval( wpj_get_user_jobs_count( get_current_user_id(), 'active' ) );

			foreach ( $posts as $key ) {
				if ( ( $active_jobs_enabled == 'yes' && $active_jobs_cnt < $active_jobs_max ) || $active_jobs_enabled == 'no' ) {
					update_post_meta( $key->ID, 'active', '1' );

					if ( $reason ) {
						update_post_meta( $key->ID, 'activate_reason', $reason );
						delete_post_meta( $key->ID, 'deactivation_reason' );
					}
				}
			}
		}
	}
}

if ( ! function_exists( 'wpj_deactivate_job' ) ) {
	function wpj_deactivate_job( $pid = '', $reason = '' ) {
		if ( is_user_logged_in() ) {
			if ( ! $reason ) $reason = 'by_user';

			$pid = WPJ_Form::post( 'post_id', $pid );

			if ( ! $pid ) $pid = wpj_get_post_id();

			$post = get_post( $pid );

			if ( $post->post_author == get_current_user_id() || current_user_can( 'administrator' ) ) {
				update_post_meta( $pid, 'active', 0 );
				update_post_meta( $pid, 'deactivation_reason', $reason );
				delete_post_meta( $pid, 'activate_reason' );

				if ( wpj_is_ajax_call() ) echo 1;

			} elseif ( wpj_is_ajax_call() ) echo 'not_your_post';

		} elseif ( wpj_is_ajax_call() ) echo 'not_logged_in';

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

if ( ! function_exists( 'wpj_deactivate_all_jobs' ) ) {
	function wpj_deactivate_all_jobs( $user_id = '', $reason = '' ) {
		$reason  = isset( $_POST['reason'] ) ? $_POST['reason'] : $reason;
		$user_id = isset( $_POST['user_id'] ) ? $_POST['user_id'] : $user_id;

		if ( ! $user_id ) $user_id = get_current_user_id();

		$args = [
			'post_type'      => 'job',
			'posts_per_page' => -1,
			'post_status'    => ['publish', 'pending', 'draft', 'auto-draft', 'future', 'private', 'inherit', 'trash'],
			'meta_query'     => [
				[
					'key'     => 'active',
					'value'   => "1",
					'compare' => '=',
				],
			],
		];

		if ( $user_id && $user_id != 'all' ) $args['author'] = $user_id;

		$posts = get_posts( $args );

		if ( $posts && is_user_logged_in() && ( get_current_user_id() == $user_id || current_user_can( 'administrator' ) ) ) {
			foreach ( $posts as $key ) {
				update_post_meta( $key->ID, 'active', '0' );

				if ( $reason ) {
					update_post_meta( $key->ID, 'deactivation_reason', $reason );
					delete_post_meta( $key->ID, 'activate_reason' );
				}
			}
		}
	}
}

if ( ! function_exists( 'wpj_delete_job' ) ) {
	function wpj_delete_job( $pid = '' ) {
		if ( is_user_logged_in() ) {
			$pid = WPJ_Form::post( 'post_id', $pid );

			if ( ! $pid ) $pid = wpj_get_post_id();

			$post = get_post( $pid );

			if ( $post->post_author == get_current_user_id() ) {
				wp_trash_post( $post->ID );

				if ( wpj_is_ajax_call() ) echo 1;

			} elseif ( wpj_is_ajax_call() ) echo 'not_your_post';

		} elseif ( wpj_is_ajax_call() ) echo 'not_logged_in';

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

if ( ! function_exists( 'wpj_delete_all_jobs' ) ) {
	function wpj_delete_all_jobs( $user_id ) {
		$user_id = isset( $_POST['user_id'] ) ? $_POST['user_id'] : $user_id;

		if ( ! $user_id ) $user_id = get_current_user_id();

		$args = [
			'post_type'      => 'job',
			'posts_per_page' => -1,
			'post_status'    => ['draft', 'publish', 'pending'],
			'author'         => $user_id
		];

		$posts = get_posts( $args );

		if ( $posts && is_user_logged_in() && get_current_user_id() == $user_id ) {
			foreach ( $posts as $post ) {
				if ( $post->post_author == get_current_user_id() ) {
					wp_trash_post( $post->ID );
				}
			}
		}
	}
}

if ( ! function_exists( 'wpj_activate_no_credits_jobs_on_job_purchase' ) ) {
	function wpj_activate_no_credits_jobs_on_job_purchase( $order_id = '' ) {
		$current_post = get_post( wpj_get_job_order( 'pid', ['id' => $order_id], 'var' ) );

		$posts = wpj_get_deactivated_jobs_by_reason( $current_post->post_author, 'no_credits' );

		if ( $posts ) {
			foreach ( $posts as $post ) {
				if ( wpj_is_user_allowed_post_job( $post->post_author, get_post_meta( $post->ID, 'price', true ) ) ) {
					update_post_meta( $post->ID, 'active', 1 );
					delete_post_meta( $post->ID, 'deactivation_reason' );
				}
			}
		}

	}
}

if ( ! function_exists( 'wpj_get_deactivated_jobs_by_reason' ) ) {
	function wpj_get_deactivated_jobs_by_reason( $uid = '', $reason = '' ) {
		return get_posts( [
			'post_type'      => 'job',
			'posts_per_page' => -1,
			'post_status'    => ['draft', 'publish', 'pending'],
			'author'         => $uid,
			'meta_query'     => [
				'relation' => 'AND',
				[
					'key'     => 'active',
					'value'   => "0",
					'compare' => '=',
				],
				[
					'key'     => 'deactivation_reason',
					'value'   => $reason,
					'compare' => '=',
				],
			],
		] );
	}
}

if ( ! function_exists( 'wpj_get_user_jobs_count' ) ) {
	function wpj_get_user_jobs_count( $uid = '', $order_status = 'active' ) {
		if ( $order_status ) {
			if ( $order_status == 'active' ) {
				$args = [
					'posts_per_page' => '-1',
					'post_type'      => 'job',
					'meta_query'     => [[
						'key'     => 'active',
						'value'   => '1',
						'compare' => '='
					]]
				];

			} elseif ( $order_status == 'inactive' ) {
				$args = [
					'posts_per_page' => '-1',
					'post_status'    => ['draft','publish'],
					'post_type'      => 'job',
					'meta_query'     => [[
						'key'     => 'active',
						'value'   => '0',
						'compare' => '='
					]]
				];

			} elseif ( $order_status == 'under-review' ) {
				$args = [
					'posts_per_page' => '-1',
					'post_status'    => 'draft',
					'post_type'      => 'job',
					'meta_query'     => [[
						'key'     => 'under_review',
						'value'   => '1',
						'compare' => '='
					]]
				];

			} elseif ( $order_status == 'rejected' ) {
				$args = [
					'posts_per_page' => '-1',
					'post_status'    => 'pending',
					'post_type'      => 'job'
				];

			}

			if ( isset( $args ) ) {
				if ( ! $uid ) $uid = get_current_user_id();

				if ( $uid && $uid != 'all' ) $args['author'] = $uid;

				$result = new WP_Query( $args );

				return apply_filters( 'wpj_user_jobs_' . $order_status . '_count_filter', $result->post_count );
			}

			if ( $order_status == 'in-queue' ) {
				$where_args = [
					'p.ID'                          => wpj_get_post_id( $uid ),
					'o.date_finished'               => 0,
					'o.request_cancellation'        => 0,
					'o.force_cancellation'          => 0,
					'o.accept_cancellation_request' => 0,
					'o.closed'                      => 0,
					'o.payment_status'              => 'completed'
				];

				return apply_filters( 'wpj_user_jobs_in_queue_count_filter', wpj_get_job_order_post( 'COUNT( * )', $where_args, 'var' ) );
			}
		}

		return 0;

	}
}

if ( ! function_exists( 'wpj_get_site_jobs_count' ) ) {
	function wpj_get_site_jobs_count( $order_status = 'all' ) {
		if ( $order_status == 'open' ) {
			$query = new WP_Query( "meta_key=closed&meta_value=0&post_type=job" );

		} elseif ( $order_status == 'closed' ) {
			$query = new WP_Query( "meta_key=closed&meta_value=1&post_type=job" );

		} else {
			$query = new WP_Query( "post_type=job" );

		}

		// save transient for 24h
		if ( ! get_transient( 'wpj_jobs_count_' . $order_status ) ) {
			set_transient( 'wpj_jobs_count_' . $order_status, $query->found_posts, ( 60 * 60 * 24 ) );
		}

		return get_transient( 'wpj_jobs_count_' . $order_status );
	}
}

if ( ! function_exists( 'wpj_get_total_posted_jobs' ) ) {
	function wpj_get_total_posted_jobs() {
		return wp_count_posts( 'job' )->publish;
	}
}

if ( ! function_exists( 'wpj_delete_site_jobs_count_transients' ) ) {
	function wpj_delete_site_jobs_count_transients() {
		delete_transient( 'wpj_jobs_count_all' );
		delete_transient( 'wpj_jobs_count_open' );
		delete_transient( 'wpj_jobs_count_closed' );
	}
}

if ( ! function_exists( 'wpj_get_job_rejected_input' ) ) {
	function wpj_get_job_rejected_input( $input = '', $i = '' ) {
		$pid = wpj_get_post_id();

		${ 'rejected_' . $input } = get_post_meta( $pid, 'rejected_' . $input, true );

		$rejected = get_post_status( $pid ) == 'pending' && ${ 'rejected_' . $input } == 1 ? 'rejected-input' : '';

		// For packages
		if ( is_array( ${ 'rejected_' . $input } ) ) {
			foreach ( ${ 'rejected_' . $input } as $rejected_p_key => $rejected_p_val ) {
				if ( $i == $rejected_p_key ) {
					$rejected = get_post_status( $pid ) == 'pending' &&  $rejected_p_val != '' ? 'rejected-input' : '';
				}
			}
		}

		return $rejected;
	}
}