<?php


namespace Elex\MultiVendor\Controller;

if ( ! defined( 'ABSPATH' ) ) {
exit;
}

use Elex\MultiVendor\Model\Reviews;
use Elex\MultiVendor\Model\Store;
use Elex\MultiVendor\Model\Vendor;

class ReviewController {

	public static  $rating_count = array(
		'1_star'     => 0,
		'2_star'     => 0,
		'3_star'     => 0,
		'4_star'     => 0,
		'5_star'     => 0,
		'total_star' => 0,
	);

	public static function init() {

		$self = new self();
		add_action( 'elex_mv_reviews_page', array( $self, 'elex_mv_review_content' ) );
		add_action( 'wp_ajax_elex_mv_review_reply', array( $self, 'elex_mv_add_comment_details' ) );
		add_action( 'wp_ajax_elex_mv_approve_review', array( $self, 'elex_mv_approve_review' ) );
		add_action( 'wp_ajax_elex_mv_review_edit', array( $self, 'elex_mv_edit_comment_details' ) );
		add_action( 'wp_ajax_elex_mv_review_delete', array( $self, 'elex_mv_delete_comment_details' ) );
		add_filter( 'pre_get_comments', array( $self, 'filter_comments_by_author' ) );
	}

	public function filter_comments_by_author( $query ) {


		$current_user = wp_get_current_user();
		$user_id      = $current_user->ID;


		$user_meta = get_userdata( $user_id );
		if ( empty( $user_meta ) ) {
			return;
		}
		$user_roles = $user_meta->roles;


		if ( ! ( in_array( 'administrator', $user_roles, true ) ) && $query->is_main_query() && $user_id && $query->get( 'post_type' ) === 'shop_order_review' ) {
	
			$query->query_vars['user_id'] = $user_id;
		}
		return $query;
	}
	public function elex_mv_approve_review() {
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'elex_mv_review_page_nonce' ) ) {
			return;
		}
		$parent_id = isset( $_POST['comment_id'] ) ? sanitize_text_field( wp_unslash( $_POST['comment_id'] ) ) : '';
		if ( empty( $parent_id ) ) {
			wp_send_json_error();
			die;
		}

		wp_set_comment_status( $parent_id, 'approve' );
		wp_send_json_success();
		die;
	}
	public function elex_mv_delete_comment_details() {
	   
		if ( ! isset( $_POST['nonce'] ) || 
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'elex_mv_review_page_nonce' ) 
		) {
		return;
		}

		$comment_id = isset( $_POST['reply_id'] ) ? sanitize_text_field( wp_unslash( $_POST['reply_id'] ) ) : '';

		$add_comment_to_review = new Reviews();
		$elex_mv_comment_id    = $add_comment_to_review->delete_comment( $comment_id );
		
		if ( ! $elex_mv_comment_id ) {
			wp_send_json_error();
			die;
		}

		wp_send_json_success();    
		die;
	}


	public function elex_mv_edit_comment_details() {
	   
		if ( ! isset( $_POST['elex-nonce'] ) || 
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['elex-nonce'] ) ), 'elex_mv_review_edit' ) 
		) {
		return;
		}
		$comment_id = isset( $_POST['reply_id'] ) ? sanitize_text_field( wp_unslash( $_POST['reply_id'] ) ) : '';

		$comment_content = isset( $_POST['comment_edit'] ) ? sanitize_text_field( wp_unslash( $_POST['comment_edit'] ) ) : '';

		$validation_errors = $this->elex_mv_comment_validation( $comment_content );
		
		if ( isset( $validation_errors['errors'] ) && count( $validation_errors['errors'] ) ) {
			wp_send_json_error( $validation_errors['errors'], 422 );
			die;
		}

		$add_comment_to_review = new Reviews();
		$elex_mv_comment_id    = $add_comment_to_review->edit_comment( $comment_id, $comment_content );

		wp_send_json_success( $elex_mv_comment_id, 200 );    
		die;
	}



	public function elex_mv_add_comment_details() {

		if ( ! isset( $_POST['elex-nonce'] ) || 
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['elex-nonce'] ) ), 'elex_mv_review_reply' ) 
		) {
		return;
		}
		$parent_id = isset( $_POST['comment_id'] ) ? sanitize_text_field( wp_unslash( $_POST['comment_id'] ) ) : '';

		$comment_post_id = isset( $_POST['comment_post_id'] ) ? sanitize_text_field( wp_unslash( $_POST['comment_post_id'] ) ) : '';


		$comment_content = isset( $_POST['comment_reply'] ) ? sanitize_text_field( wp_unslash( $_POST['comment_reply'] ) ) : '';

		$validation_errors = $this->elex_mv_comment_validation( $comment_content );
		
		if ( isset( $validation_errors['errors'] ) && count( $validation_errors['errors'] ) ) {
			wp_send_json_error( $validation_errors['errors'], 422 );
			die;
		}

		$add_comment_to_review = new Reviews();
		$elex_mv_comment_id    = $add_comment_to_review->add_comment( $parent_id, $comment_content, $comment_post_id );
		wp_send_json_success( $elex_mv_comment_id, 200 );    
		die;
	}

	public function elex_mv_comment_validation( $comment ) {

		$data = array(
			'message' => __( 'Empty Fields' , 'elex-multi-vendor-for-woocommerce' ),
			'errors'  => array(),
		);

		if ( ! isset( $comment ) || empty( $comment ) ) {
			$data['errors']['product_description'][] = __( 'Please enter description.', 'elex-multi-vendor-for-woocommerce' );
		}
		/** 
		 * Fire a filter hook for adding aditional validation
		 *
		 * @since 1.0.0
		 * @param $data
		 */
		$data = apply_filters( 'elex_mv_form_product_validation', $data );
		return $data;
	}

	public function elex_mv_review_content() {
	   
		$reviews = self::get_review_details();

		$avg_review = self::get_average_rating( self::$rating_count );
		
		$rating_count = self::$rating_count;

		$comment_per_page = 7;
		$total_review     = count( $reviews );
		$num_pages        = ceil( $total_review / $comment_per_page );
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only GET param for review pagination on a public store page; no write operation.
		$current_page     = ! empty( filter_input( INPUT_GET, 'page_review' , FILTER_SANITIZE_NUMBER_INT ) ) ? max( 1, intval( filter_input( INPUT_GET, 'page_review' , FILTER_SANITIZE_NUMBER_INT ) ) ) : 1;
		$offset           = ( $current_page - 1 ) * $comment_per_page;
		$reviews          = array_slice( $reviews, $offset, $comment_per_page );

		include ELEX_MULTI_VENDOR_PLUGIN_PATH . 'templates/review/review.php';
	}

	public static function get_review_details() {
		
		$vendor_info    = Vendor::load( wp_get_current_user() );
		$store          = new Store();
		$review_details = array();
		$store_id       = '';
		if ( $vendor_info->has_store() ) {
			$store    = $vendor_info->get_store();
			$store_id = $store->get_id();
		}
		
		$args     = array(
			'meta_key'   => 'elex_mv_store_id', // phpcs:ignore WordPress.DB.SlowDBQuery
			'meta_value' => $store->get_id(), // phpcs:ignore WordPress.DB.SlowDBQuery
		);
		$products = wc_get_products( $args );
		
		
		$arg = array( 
			'post_type' => 'product', 
		);
	
		$comments     = get_comments( $arg );
		$reply_id     = 0;
		$reply        = null;
		$reply_author = null;

	
		
		
		foreach ( $comments as $comment ) {  
		
			$avatar = get_avatar_url( $comment->comment_author_email );

	
			$verification = self::verify_owner( $comment, $store_id );
	   
		   
			foreach ( $products as $product ) {

				$comment_post_ID = intval( $comment->comment_post_ID );
				
				if ( ( $comment_post_ID === $product->get_id() ) && ( 'review' === $comment->comment_type || 'comment' === $comment->comment_type ) ) {
					$rating = get_comment_meta( $comment->comment_ID, 'rating', true );

					self::count_stars( $rating );

					
					$values           = array( 
						'product_name'     => $product->get_name(),
						'author_name'      => $comment->comment_author,
						'aurhor_email'     => $comment->comment_author_email,
						'date'             => $comment->comment_date,
						'content'          => $comment->comment_content,
						'comment_id'       => $comment->comment_ID,
						'image'            => $avatar,
						'comment_type'     => $comment->comment_type,
						'comment_post_ID'  => $comment->comment_post_ID,
						'comment_reply_id' => $reply_id,
						'user_id'          => $comment->user_id,
						'reply_author'     => $reply_author,
						'comment_approved' => $comment->comment_approved,
						'reply_content'    => $reply,
						'verified_owner'   => $verification,
						'rating'           => $rating,
					);
					$reply_id         = 0;
					$reply            = null;
					$reply_author     = null;
					$review_details[] = $values;
				  
				}
			}
		}

		
		return $review_details; 
	}

	public static function count_stars( $star ) {

		switch ( $star ) {
			case 1:
				++self::$rating_count['1_star'];
					++self::$rating_count['total_star'];
				break;
			case 2:
				++self::$rating_count['2_star'];
					++self::$rating_count['total_star'];
				break;
			case 3:
				++self::$rating_count['3_star'];
					++self::$rating_count['total_star'];
				break;
			case 4:
				++self::$rating_count['4_star'];
					++self::$rating_count['total_star'];
				break;
			case 5:
				++self::$rating_count['5_star'];
					++self::$rating_count['total_star'];
				break;
			default:
				return;
		}
	} 

	public static function get_average_rating( $rating ) {

		$numerator = ( ( 1 * $rating['1_star'] ) + ( 2 * $rating['2_star'] ) + ( 3 * $rating['3_star'] ) + ( 4 * $rating['4_star'] ) + ( 5 * $rating['5_star'] ) );

		$denominator = $rating['total_star'];

		$average_rating = 0;

		if ( 0 !== $rating['total_star'] ) {
			$average_rating = $numerator / $denominator;
			$average_rating = number_format( (float) $average_rating, 1, '.', '' );
		}
		
		return $average_rating;
	}

	public static function verify_owner( $comment, $store_id ) {
	

		if ( 0 === $comment->user_id ) {
			return false;
		}
		if ( isset( $store_id ) && 'on' === get_post_meta( $store_id, 'elex_mv_verify_user_review', true ) ) {
			$verify = wc_customer_bought_product( $comment->comment_author_email, $comment->user_id, $comment->comment_post_ID );
		
			return $verify;

		} else {
			
			return false;

		}
	}

	/**
	 * Get the value of comment_post_ID
	 */ 
	public function getComment_post_ID() {
		return $this->comment_post_ID;
	}

	/**
	 * Set the value of comment_post_ID
	 *
	 * @return  self
	 */ 
	public function setComment_post_ID( $comment_post_ID ) {
					$this->comment_post_ID = $comment_post_ID;

		return $this;
	}
}
