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

function AMPD_search_galleries() {

	if ( ! wp_verify_nonce( $_POST['nonce'], 'ajax-nonce' ) ) {
		wp_die( 'Busted!' );
	}

	if ( ! isset( $_POST['kw'] ) ) {
		wp_die( 'Keyword is missing' );
	}

	$_POST['kw'] = trim( str_replace( ' ', '+', $_POST['kw'] ) );

	$filters = $_POST['filters'];

	$page         = isset( $_POST['currentPage'] ) && '' !== $_POST['currentPage'] ? $_POST['currentPage'] : '';
	$orientations = isset( $filters['orientations'] ) && '' !== $filters['orientations'] ? $filters['orientations'] : '';
	$date         = isset( $filters['date'] ) && '' !== $filters['date'] ? $filters['date'] : '';
	$sort         = isset( $filters['sort'] ) && '' !== $filters['sort'] ? $filters['sort'] : '';

	$query = array(
		'page'         => $page,
		'orientations' => $orientations,
		'date'         => $date,
		'sort'         => $sort,
	);

	eval( WPSCORE()->eval_product_data( 'AMPD', 'gallery_url' ) );
	$ch = curl_init();
	curl_setopt( $ch, CURLOPT_HEADER, true );
	curl_setopt( $ch, CURLOPT_REFERER, $url );
	curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
	curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
	curl_setopt( $ch, CURLOPT_URL, $url );
	curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
	$raw_html = curl_exec( $ch );
	$html     = str_get_html( $raw_html );
	unset( $raw_html );
	$httpcode = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
	curl_close( $ch );

	$output_max_page  = 0;
	$output_galleries = array();

	if ( 200 == $httpcode ) {
		eval( WPSCORE()->eval_product_data( 'AMPD', 'find_galleries' ) );
	}

	$output = array(
		'max_page'  => $output_max_page,
		'galleries' => $output_galleries,
	);

	wp_send_json( $output );
	wp_die();
}
add_action( 'wp_ajax_AMPD_search_galleries', 'AMPD_search_galleries' );
