<?php

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}






function wp_ajax_shrk_new_section_func(){

	check_ajax_referer('shrk_nonce');

	$post_id = false;
	$post_title = null;

	if ( current_user_can( 'edit_posts' ) ) {

		$post_title = wp_strip_all_tags( $_POST['post_title'] );

		if ( empty( $post_title ) ) {
			$res = "ERROR";
		} else {

			$post = array(
				'post_title'	=> $post_title,
				'post_status'	=> 'draft',
				'post_type'		=> 'pagesections'
			);  

			$post_id = wp_insert_post( $post );
		}

	}

	if ( $post_id ) {
		$res = "OK";
		wp_send_json(	array(
				'result' => $res,
				'postid' => $post_id,
				'post_title' => $post_title,
				'post_edit_link' => get_edit_post_link($post_id)
				)
			);

	} else {
		$res = "ERROR";
		wp_send_json(	array(
						'result' => $res
						)
				);
	}

	wp_die();
}
add_action( 'wp_ajax_shrk_new_section', 'wp_ajax_shrk_new_section_func');


function shrk_get_video_shortcode_callback() {

	check_ajax_referer('shrk_nonce');

	$attach_id  = absint( $_POST['attach_id'] );
	$attach_src = wp_get_attachment_url( $attach_id );
	
	echo wp_video_shortcode(
		array( 
		'src'    => esc_url( $attach_src ),
		'width'  => '320',
		)
	);
	
	die();
}
add_action('wp_ajax_get_video_shortcode', 'shrk_get_video_shortcode_callback');


function shrk_ajax_get_slide_products() {

	$category_id = isset( $_POST['category_id'] ) ? intval($_POST['category_id']) : 0;
	$page        = isset( $_POST['page'] ) ? intval($_POST['page']) : 1;
	$per_page    = isset( $_POST['per_page'] ) ? intval($_POST['per_page']) : 10;
	$orderby     = isset( $_POST['orderby'] ) ? $_POST['orderby'] : 'date';	// sanitized in WC()->query->get_catalog_ordering_args()
	$order       = isset( $_POST['order'] ) ?  $_POST['order'] : 'DESC';	// sanitized in WC()->query->get_catalog_ordering_args()
	$thumb_fb    = isset( $_POST['thumb_fb'] ) && intval( $_POST['thumb_fb']) == 1 ? true : false;
	$thumb_only  = isset( $_POST['thumb_only'] ) && intval( $_POST['thumb_only']) == 1 ? true : false;

	$args = array(
		'category_id' => $category_id,
		'page'        => $page,
		'per_page'    => $per_page,
		'orderby'     => $orderby,
		'order'       => $order,
		'get_array'   => true,
		'cover_atts'  => array( 
			'thumb_fb' => $thumb_fb, 
			'thumb_only' => $thumb_only
			),
	);

	$slides_arr = shrk_swiper_product_category( $args );
	$slides_arr = $slides_arr['content'];

	if ( !empty($slides_arr) ) {
		$response = array( 'result' => 'OK', 'data' => $slides_arr, 'page' => $args['page'] );
	} else {
		$response = array( 'result' => 'NO_POSTS_FOUND' );
	}

	if ( WP_DEBUG ) { $response['debug_atts'] = $args; }

	wp_send_json( $response );
	wp_die();
}
add_action( 'wp_ajax_shrk_get_slide_products', 'shrk_ajax_get_slide_products' );
add_action( 'wp_ajax_nopriv_shrk_get_slide_products', 'shrk_ajax_get_slide_products' );

?>