<?php
/**
 * Lightweight WordPress Ajax Process Execution
 *
 * @package WordPress
 */

define( 'DOING_AJAX', true );

/** Load WordPress Bootstrap */
$absolute_path = __FILE__;
$path_to_file  = explode( 'wp-content', $absolute_path );
$path_to_wp    = $path_to_file[0];

require_once( $path_to_wp . 'wp-load.php' );

// Functions with very small requirements, to be used with shortinit
add_action( 'light_ajax_check_live_site_changes_action', 'wpj_check_site_changes' );
if ( ! function_exists( 'wpj_check_site_changes' ) ) {
	function wpj_check_site_changes( $uid = 0 ) {
		$uid = isset( $_POST['uid'] ) ? $_POST['uid'] : $uid;

		if ( ! $uid ) {
			$uid = get_current_user_id();
		}

		$options = get_option( 'jobster_settings' );
		$enabled = $options['wpjobster_enable_live_notifications'];

		$notifications = get_user_meta( $uid, 'notifications_number', true );
		$messages      = get_user_meta( $uid, 'messages_number', true );

		$notification_info = get_user_meta( $uid, 'notification_info', true );

		$response = [
			'enabled'           => $enabled,
			'notifications'     => $notifications,
			'messages'          => $messages,
			'current_time'      => time(),
			'timeout'           => 2000,
			'max_timeout'       => 32000,
			'notification_info' => json_encode( $notification_info )
		];

		// update user last visit
		update_user_meta( $uid, 'last_user_login', current_time( 'timestamp', 1 ) );

		// update user last IP
		if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) $ip = $_SERVER['HTTP_CLIENT_IP'];
		elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
		else $ip = $_SERVER['REMOTE_ADDR'];

		update_user_meta( $uid, 'ip_reg', $ip );

		wp_send_json( $response );
		wp_die();
	}
}

// Require a valid action parameter.
if ( empty( $_REQUEST['action'] ) || ! is_scalar( $_REQUEST['action'] ) ) {
	wp_die( '0', 400 );
}

/** Load Ajax Handlers for WordPress Core */
require_once ABSPATH . 'wp-admin/includes/ajax-actions.php';

nocache_headers();

$core_actions_get = array(
	'fetch-list',
	'ajax-tag-search',
	'imgedit-preview',
	'oembed-cache',
	'autocomplete-user',
	'heartbeat',
);

$core_actions_post = array(
	'oembed-cache',
	'heartbeat',
);

// Register core Ajax calls.
if ( ! empty( $_GET['action'] ) && in_array( $_GET['action'], $core_actions_get, true ) ) {
	add_action( 'light_ajax_' . $_GET['action'], 'light_ajax_' . str_replace( '-', '_', $_GET['action'] ), 1 );
}

if ( ! empty( $_POST['action'] ) && in_array( $_POST['action'], $core_actions_post, true ) ) {
	add_action( 'light_ajax_' . $_POST['action'], 'light_ajax_' . str_replace( '-', '_', $_POST['action'] ), 1 );
}

$action = $_REQUEST['action'];

if ( is_user_logged_in() ) {
	if ( ! has_action( "light_ajax_{$action}" ) ) {
		wp_die( '0', 400 );
	}

	do_action( "light_ajax_{$action}" );
} else {
	if ( ! has_action( "light_ajax_nopriv_{$action}" ) ) {
		wp_die( '0', 400 );
	}

	do_action( "light_ajax_nopriv_{$action}" );
}

wp_die( '0' );