<?php
/**
 * Created by mr2app.
 * User: hani
 * Date: 01/19/19
 * Time: 6:30 PM
 */
class class_vendors
{
	function __construct()
	{
		add_action('init', array($this, 'mr2app_class_vendors_api_regular_url'));
		add_filter('query_vars', array($this, 'mr2app_class_vendors_api_query_vars'));
		add_action('parse_request', array($this, 'mr2app_class_vendors_api_parse_request'));
	}

	function mr2app_class_vendors_api_regular_url()
	{
		add_rewrite_rule('^mr2app/GetVendors', 'index.php?GetSeller=$matches[1]', 'top');
		add_rewrite_rule('^mr2app/GetCatVendors', 'index.php?GetCatVendors=$matches[1]', 'top');
		add_rewrite_rule('^mr2app/GetStoreRating', 'index.php?GetStoreRating=$matches[1]', 'top');
		add_rewrite_rule('^mr2app/GetStoreReview', 'index.php?GetStoreReview=$matches[1]', 'top');
		add_rewrite_rule('^mr2app/SubmitReview', 'index.php?SubmitReview=$matches[1]', 'top');
		flush_rewrite_rules();
	}

	function mr2app_class_vendors_api_query_vars($query_vars)
	{
		$query_vars[] = 'GetSeller';
		$query_vars[] = 'GetCatVendors';
		$query_vars[] = 'GetStoreRating';
		$query_vars[] = 'GetStoreReview';
		$query_vars[] = 'SubmitReview';

		return $query_vars;
	}

	function mr2app_class_vendors_api_parse_request(&$wp)
	{
		if (array_key_exists('GetSeller', $wp->query_vars)) {
			$this->GetSeller();
			exit();
		}
		elseif (array_key_exists('GetCatVendors', $wp->query_vars)) {
			$this->GetCatVendors($_GET['store_id']);
			exit();
		}
		elseif (array_key_exists('GetStoreRating', $wp->query_vars)) {
			$this->replace_rating_value( 0 ,$_GET['store_id']);
			exit();
		}
		elseif (array_key_exists('GetStoreReview', $wp->query_vars)) {
			$this->replace_ratings_list( 0 ,$_GET['store_id']);
			exit();
		}
		elseif (array_key_exists('SubmitReview', $wp->query_vars)) {
			$this->SubmitReview();
			exit();
		}
		return;
	}
	public function get_product_category( $id, $fields = null ) {
		$term = get_term( $id, get_woo2app_taxonomy() );
		if ( is_wp_error( $term ) || is_null( $term ) ) {
			throw new WC_API_Exception( 'woocommerce_api_invalid_product_category_id', __( 'A product category with the provided ID could not be found', 'woocommerce' ), 404 );
		}
		$term_id = intval( $term->term_id );
		// Get category display type
		$display_type = get_woocommerce_term_meta( $term_id, 'display_type' );
		// Get category image ...
		$image = '';
		if ( $image_id = get_woocommerce_term_meta( $term_id, 'thumbnail_id' ) ) {
			//$image = wp_get_attachment_url( $image_id );
			$image2 = wp_get_attachment_image_src( $image_id ,'medium' );
			$image=$image2['0'];
		}
		elseif ( $image_id = get_woocommerce_term_meta( $term_id, 'thumbnail_bid' ) ) {
			//$image = wp_get_attachment_url( $image_id );
			$image2 = wp_get_attachment_image_src( $image_id ,'medium' );
			$image=$image2['0'];
		}
		$product_category = array(
			'id'          => $term_id,
			'name'        => $term->name,
			'slug'        => $term->slug,
			'parent'      => $term->parent,
			'description' => $term->description,
			'display'     => $display_type ? $display_type : 'default',
			'image'       => $image ? esc_url( $image ) : '',
			//'count'       => intval( $term->count )
		);
		return array( 'product_category' => apply_filters( 'woocommerce_api_product_category_response', $product_category, $id, $fields, $term, $this ) );
	}

	public function GetCatVendors($seller_id){
		header('Content-Type: application/json; charset=utf-8');
		global $wpdb;
		$categories = $wpdb->get_results( $wpdb->prepare( "SELECT t.term_id FROM $wpdb->terms as t
                LEFT JOIN $wpdb->term_taxonomy as tt on t.term_id = tt.term_id
                LEFT JOIN $wpdb->term_relationships AS tr on tt.term_taxonomy_id = tr.term_taxonomy_id
                LEFT JOIN $wpdb->posts AS p on tr.object_id = p.ID
                WHERE tt.taxonomy = 'product_cat'
                AND p.post_type = 'product'
                AND p.post_status = 'publish'
                AND p.post_author = %d GROUP BY t.term_id", $seller_id ));
		foreach ($categories as $cat){
			$product_categories[] = current( $this->get_product_category( $cat->term_id, '' ) );
		}
		echo json_encode(array('product_categories' => $product_categories));
	}

	public  function replace_ratings_list( $u_id, $store_id  , $return = false) {
		header('Content-Type: application/json; charset=utf-8');
		$args = array(
			'post_type'      => 'dokan_store_reviews',
			'meta_key'       => 'store_id',
			'meta_value'     => $store_id,
			'post_status'    => 'publish',
			//'author__not_in' => array( $u_id, $store_id )
		);

		$query = new WP_Query( $args );
		$array = array();
		foreach ($query->posts as $review){
			$array['store_review'][] = array(
				'ID' => $review->ID,
				'title' => $review->post_title,
				'content' => $review->post_content,
				'guid' => $review->guid,
				'author' => get_user_meta($review->post_author , 'nickname', true),
				'rating' => get_post_meta($review->ID,'rating', true),
			);
		}
		$array['store_rating'] = $this->replace_rating_value(0,$store_id);
		if($return) return $array;
		echo json_encode($array);
	}

	function SubmitReview() {

		ob_start();
		header('Content-Type: application/json; charset=utf-8');
		if(isset($_POST['in'])) {
			$in = $_POST['in'];
			$slashless = stripcslashes($in);
			$url_json = urldecode($slashless);
			$json = (array)json_decode($url_json);
			//check if valid customer to proceed
			if ( !$this->check_if_valid_customer( $json['store_id'], $json['u_id'] ) ) {
				wp_send_json( array(
					'success' => false,
					'msg'     => __( 'Sorry, user id  ! something went wrong!.', 'dokan' ),
				) );
			}

			if ( !dokan_get_vendor($json['store_id'])->id ) {
				wp_send_json( array(
					'success' => false,
					'msg'     => __( 'Sorry, store id  ! something went wrong!.', 'dokan' ),
				) );
			}
			$rating = intval ( $json['rating'] );

			$my_post = array(
				'post_title'     => $json['dokan-review-title'],
				'post_content'   => $json['dokan-review-details'],
				'post_author'         => $json['u_id'],
				'post_type'      => 'dokan_store_reviews',
				'post_status'    => 'publish'
			);

			if ( isset( $json[ 'post_id' ] ) ) {

				$post_id = intval( $json[ 'post_id' ] );
				$post    = get_post( $post_id );
				//wp_send_json($post);
				if ( $json['u_id'] == $post->post_author ) {
					$my_post[ 'ID' ] = $post->ID;
					$post_id = wp_update_post( $my_post );
				} else {
					$post_id = 0;
				}

			} else {
				if ( $this->check_if_review_repeat($json['store_id'],$json['u_id'])) {
					wp_send_json( array(
						'success' => false,
						'msg'     => __( 'Sorry, store review repeated  ! something went wrong!.', 'dokan' ),
					) );
				}
				$post_id = wp_insert_post( $my_post );
			}

			if ( $post_id ) {

				update_post_meta( $post_id, 'store_id', $json['store_id'] );
				update_post_meta( $post_id, 'rating', $rating );

				//$this->send_email_to_seller( $postdata['store_id'], $post_id );

				wp_send_json( array(
					'success' => true,
					'msg'     => __( 'Thanks for your review', 'dokan' ),
				) );

			} else {
				wp_send_json( array(
					'success' => false,
					'msg'     => __( 'Sorry, something went wrong!.', 'dokan' ),
				) );
			}
		}
		wp_send_json( array(
			'success' => false,
			'msg'     => __( 'Sorry, something went wrong!.', 'dokan' ),
		) );
	}


	function check_if_review_repeat( $seller_id, $customer_id ) {

		$args = array(
			'post_type'           => 'dokan_store_reviews',
			'author'              => $customer_id,
			'meta_key'            => 'store_id',
			'meta_value'          => $seller_id,
		);

		$query = new WP_Query( $args );

		if( $query->posts ) {
			return true;
		}

		return false;
	}

	function check_if_valid_customer( $seller_id, $customer_id ) {

		// comment by Hani !!!
//        if ( !is_user_logged_in() ) {
//            return false;
//        }
		$user = get_user_by('id' , $customer_id);
		if(!$user) return false;


		if ( get_option( 'woocommerce_review_rating_verification_required' ) === 'no' ) {
			return true;
		}

		$args = array(
			'post_type'           => 'shop_order',
			'author'              => $seller_id,
			'meta_key'            => '_customer_user',
			'meta_value'          => $customer_id,
			'post_status'         => 'wc-completed'
		);

		$query = new WP_Query( $args );

		if( $query->posts ) {
			return true;
		}

		return false;
	}

	public function replace_rating_value( $rating , $store_id ) {

		$args = array(
			'post_type'      => 'dokan_store_reviews',
			'meta_key'       => 'store_id',
			'meta_value'     => $store_id,
			'post_status'    => 'publish',
		);

		$query = new WP_Query( $args );

		$review_count = $query->post_count;

		if ( $review_count ) {

			$rating = 0;
			foreach ( $query->posts as $review ) {
				$rating += intval( get_post_meta( $review->ID, 'rating', true ) );
			}

			$rating = floatval( $rating / $review_count );
		} else {
			$rating = __( 'No Ratings found yet', 'dokan' );
		}

		return $result = array(
			'rating' => $rating,
			'count'  => $review_count
		);
	}
	public function GetSeller($return = false){
		header('Content-Type: application/json; charset=utf-8');
		$result = array();
		$vendors = dokan_get_sellers( array(
			'number' => -1,
		));
		$i = -1;
		foreach ($vendors['users'] as $v){
			$woo2app_info = get_user_meta($v->ID , 'woo2app_store_info' , true );
			if(!is_array($woo2app_info)){
				$woo2app_info = array(
					'woo2app_send_state' => '',
					'woo2app_description_state' => '',
					'lat' => '',
					'lng' => '',
					'slider' => [],
				);
			}
			$i++;
			$result['vendors'][$i] = array(
				'info' => get_user_meta($v->ID , 'dokan_profile_settings' , true ),
				'woo2app_info' => $woo2app_info,
				'rating' => dokan_get_seller_rating($v->ID)
			);
			$result['vendors'][$i]['info']['store_name'] =  $result['vendors'][$i]['info']['store_name'] != "" ? $result['vendors'][$i]['info']['store_name'] : '[بدون نام]';
			$result['vendors'][$i]['info']['store_id'] =  $v->ID;
			$result['vendors'][$i]['info']['banner'] =  $result['vendors'][$i]['info']['banner'] != 0 ? get_post($result['vendors'][$i]['info']['banner'])->guid : '';
			$result['vendors'][$i]['info']['icon'] =  $result['vendors'][$i]['info']['icon'] != 0 ? get_post($result['vendors'][$i]['info']['icon'])->guid : '';
			$result['vendors'][$i]['info']['gravatar'] =  $result['vendors'][$i]['info']['gravatar'] != 0 ? get_post($result['vendors'][$i]['info']['gravatar'])->guid : '';
			if(isset($result['vendors'][$i]['info']['social'])){
				unset($result['vendors'][$i]['info']['social']);
			}
			if(isset($result['vendors'][$i]['info']['payment'])){
				unset($result['vendors'][$i]['info']['payment']);
			}
			if(isset($result['vendors'][$i]['info']['profile_completion'])){
				unset($result['vendors'][$i]['info']['profile_completion']);
			}
			if(isset($result['vendors'][$i]['info']['show_more_ptab'])){
				unset($result['vendors'][$i]['info']['show_more_ptab']);
			}
			if(isset($result['vendors'][$i]['info']['store_ppp'])){
				unset($result['vendors'][$i]['info']['store_ppp']);
			}
			if(isset($result['vendors'][$i]['info']['enable_tnc'])){
				unset($result['vendors'][$i]['info']['enable_tnc']);
			}
			if(isset($result['vendors'][$i]['info']['store_tnc'])){
				unset($result['vendors'][$i]['info']['store_tnc']);
			}
			if(isset($result['vendors'][$i]['info']['show_min_order_discount'])){
				unset($result['vendors'][$i]['info']['show_min_order_discount']);
			}
			if(isset($result['vendors'][$i]['info']['store_seo'])){
				unset($result['vendors'][$i]['info']['store_seo']);
			}
			if(isset($result['vendors'][$i]['info']['find_address'])){
				unset($result['vendors'][$i]['info']['find_address']);
			}
			if(isset($result['vendors'][$i]['info']['dokan_store_time'])){
				unset($result['vendors'][$i]['info']['dokan_store_time']);
			}
		}
		$result['vendors_count'] = $vendors['count'];
		if($return) return $result;
		echo json_encode($result);
	}
}