<?php
/**
 * Ajax function to get posts that haven't been checked yet.
 *
 * @package dvic\admin\actions
 */

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

/**
 * Update options of a given camsite_id.
 *
 * @return void
 */
function dvic_get_posts() {
	check_ajax_referer( 'ajax-nonce', 'nonce' );
	if ( ! isset( $_POST['scan_type'] ) ) {
		wp_send_json_error( array( 'message' => 'scan_type parameter is missing' ) );
	}
	if ( ! isset( $_POST['posts_per_page'] ) ) {
		wp_send_json_error( array( 'message' => 'posts_per_page parameter is missing' ) );
	}
	if ( ! isset( $_POST['offset'] ) ) {
		wp_send_json_error( array( 'message' => 'offset parameter is missing' ) );
	}
	if ( ! isset( $_POST['post_type'] ) ) {
		wp_send_json_error( array( 'message' => 'post_type parameter is missing' ) );
	}
	$scan_type      = sanitize_text_field( wp_unslash( $_POST['scan_type'] ) );
	$posts_per_page = intval( $_POST['posts_per_page'] );
	$offset         = intval( $_POST['offset'] );
	$post_type      = sanitize_text_field( wp_unslash( $_POST['post_type'] ) );
	$taxonomy       = isset( $_POST['taxonomy'] ) ? sanitize_text_field( wp_unslash( $_POST['taxonomy'] ) ) : '';
	$term           = isset( $_POST['term'] ) ? sanitize_text_field( wp_unslash( $_POST['term'] ) ) : '';

	// Base args.
	$args = array(
		'fields'         => 'ids',
		'offset'         => $offset,
		'post_status'    => 'publish',
		'post_type'      => $post_type,
		'posts_per_page' => $posts_per_page,
	);

	// Scan only posts in Taxonomy.
	if ( '' !== $taxonomy && '' === $term ) {
		$args['tax_query'] = array(
			array(
				'taxonomy' => $taxonomy,
				'operator' => 'EXISTS',
				'field'    => 'term_id',
			),
		);
	}
	// Scan only posts in Taxonomy and Term.
	if ( '' !== $taxonomy && '' !== $term ) {
		$args['tax_query'] = array(
			array(
				'taxonomy' => $taxonomy,
				'field'    => 'slug',
				'terms'    => $term,
			),
		);
	}

	// Check only posts that haven't been scanned yet.
	if ( 'new' === $scan_type ) {
		$args['meta_query'] = array(
			array(
				'key'     => 'DVIC_checked_date',
				'compare' => 'NOT EXISTS',
			),
		);
	}

	$query           = new WP_Query( $args );
	$formatted_posts = array();
	foreach ( $query->posts as $post_id ) {
		$formatted_posts[] = \DVIC\Checker::get_formatted_post( $post_id );
	}
	wp_send_json_success(
		array(
			'found_posts' => $query->found_posts,
			'posts'       => $formatted_posts,
		)
	);
	wp_die();
}
add_action( 'wp_ajax_dvic_get_posts', 'dvic_get_posts' );
