<?php
namespace Elex\MultiVendor\Controller;

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

use Elex\MultiVendor\Model\Product;
use Elex\MultiVendor\Model\Store;

class AdminProductController {

	public static $nonce_error_msg = 'Wrong Nonce';

	public static function init() {
		$self = new self();
		add_action( 'elex_mv_admin_product_controller_page', array( $self, 'elex_mv_admin_product_controller_page' ) );
		add_action( 'wp_ajax_elex_mv_add_admin_vendor_product_details', array( $self, 'elex_mv_add_admin_vendor_product_details' ) );
		add_action( 'wp_ajax_elex_mv_approval_product_from_admin_side', array( $self, 'elex_mv_approval_product_from_admin_side' ) ); 
		add_action( 'wp_ajax_elex_mv_bulk_action_for_product_vendor_admin', array( $self, 'bulk_action_for_product_vendor_admin' ) ); 
	}



	public function bulk_action_for_product_vendor_admin() {

		if ( ! isset( $_POST['nonce'] ) || 
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'elex_mv_prod_page_nonce' ) 
		) {
			wp_send_json_error( self::$nonce_error_msg, 200 );
		}

		$products = isset( $_POST['product_ids'] ) ? map_deep( wp_unslash( $_POST['product_ids'] ), 'sanitize_text_field' ) : array();

		foreach ( $products as $product_id ) {
			$product = wc_get_product( $product_id );

			if ( isset( $_POST['status'] ) && ( 'visible' === $_POST['status'] || 'hidden' === $_POST['status'] ) ) {
				$product->set_catalog_visibility( sanitize_text_field( wp_unslash( $_POST['status'] ) ) );
			} elseif ( isset( $_POST['status'] ) ) {

				$prod_status = $product->get_status();
				if ( 'reject' !== $prod_status ) {


					if ( 'publish' === sanitize_text_field( wp_unslash( $_POST['status'] ) ) ) {
						$product->set_status( sanitize_text_field( wp_unslash( $_POST['status'] ) ) );
						$prod_store_id = $product->get_meta( 'elex_mv_store_id', true );
						$store_post    = get_post( $prod_store_id );
						$store_obj     = Store::load_by_store( $store_post );
						$date_fomat    = get_option( 'date_format' );
						$to            = ! empty( $store_obj->get_email() ) ? $store_obj->get_email() : '' ;
					  
						$subject = 'Product Approved by Site Administrator';
						$body    = 'Dear ' . $store_obj->get_title() . ',<br>
		
							   We hope this message finds you well.<br>
							   
							   We would like to inform you about the status of the product you recently submitted for publication on Your Multi-Vendor Site. The product review process has been completed, and we have the following update for you:<br>
							   
							   Product Name: ' . $product->get_name() . '
							   Submission Date: ' . gmdate( $date_fomat, strtotime( $product->get_date_modified() ) ) . '
							   Review Status: Approved
							   
							   Congratulations! Your product has met our quality and content guidelines and is now live on ' . get_bloginfo( 'name' ) . ', available for customers to browse and purchase. We appreciate your dedication to delivering excellent products to our platform.<br>
							   
							   Thank you for your contribution to ' . get_bloginfo( 'name' ) . ', and we appreciate your commitment to maintaining the quality and integrity of our platform. We look forward to seeing your products thrive on our platform.<br>';
					 
							 
		
						$headers   = array();
						$headers[] = 'Content-type: text/html; charset=utf-8';
						$headers[] = 'From:' . get_bloginfo( 'admin_email' );
						// Send email using wp_mail() function
						$result = wp_mail( $to, $subject, $body, $headers );
		
					
					}
					if ( 'reject' === sanitize_text_field( wp_unslash( $_POST['status'] ) ) && 'publish' !== $prod_status ) {
						$product->set_status( sanitize_text_field( wp_unslash( $_POST['status'] ) ) );        
						$prod_store_id = $product->get_meta( 'elex_mv_store_id', true );
						$store_post    = get_post( $prod_store_id );
		
		
						$store_obj  = Store::load_by_store( $store_post );
						$date_fomat = get_option( 'date_format' );
						$to         = ! empty( $store_obj->get_email() ) ? $store_obj->get_email() : '' ;
					  
						$subject = 'Product Rejected by Site Administrator';
						$body    = 'Dear ' . $store_obj->get_title() . ',<br>
		
								We hope this message finds you well.<br>
							   
								We would like to inform you about the status of the product you recently submitted for publication on ' . $store_obj->get_title() . ' Site. The product review process has been completed, and we have the following update for you:<br>
							   
								Product Name: ' . $product->get_name() . '
								Submission Date: ' . gmdate( $date_fomat, strtotime( $product->get_date_modified() ) ) . "
								Review Status: Rejected<br>
							   		
								We regret to inform you that your product did not meet our guidelines for publication. We have provided specific feedback and reasons for the rejection below:<br>
		
								You make certain required changes to the product & resubmit it for approval through your vendor dashboard. We are here to support you in ensuring your product aligns with our platform's standards.<br>
									
								Thank you for your contribution to " . get_bloginfo( 'name' ) . ', and we appreciate your commitment to maintaining the quality and integrity of our platform. We look forward to seeing your products thrive on our platform.<br>';
					 
							 
		
						$headers   = array();
						$headers[] = 'Content-type: text/html; charset=utf-8';
						$headers[] = 'From:' . get_bloginfo( 'admin_email' );
						// Send email using wp_mail() function
						$result = wp_mail( $to, $subject, $body, $headers );
		
		
					}
				}           
			}
			
			$product->save();
		}

		/**
		 * Hook to change admin statuses
		 *
		 * @since 1.0.0
		 */
		do_action( 'elex_mv_on_update_product_vendor_admin_status', $new_status, $vendors );

		wp_send_json_success( array( 'message' => __( 'Updated successfully', 'elex-multi-vendor-for-woocommerce' ) ), 200 );
	}

	public function elex_mv_approval_product_from_admin_side() {

		if ( ! isset( $_POST['nonce'] ) || 
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'elex_mv_prod_page_nonce' ) 
		) {
			wp_send_json_error( self::$nonce_error_msg, 200 );
		}

		if ( isset( $_POST['status'] ) && isset( $_POST['prod_id'] ) ) {

			$id = sanitize_text_field( wp_unslash( $_POST['prod_id'] ) );

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

			$product = wc_get_product( $id );

			$product->set_status( sanitize_text_field( wp_unslash( $_POST['status'] ) ) );

			if ( 'publish' === sanitize_text_field( wp_unslash( $_POST['status'] ) ) ) {
			  
			

				$prod_store_id = $product->get_meta( 'elex_mv_store_id', true );
				$store_post    = get_post( $prod_store_id );


				$store_obj  = Store::load_by_store( $store_post );
				$date_fomat = get_option( 'date_format' );
				$to         = ! empty( $store_obj->get_email() ) ? $store_obj->get_email() : '' ;
			  
				$subject = 'Product Approved by Site Administrator';
				$body    = 'Dear ' . $store_obj->get_title() . ',<br>

					   We hope this message finds you well.<br>
					   
					   We would like to inform you about the status of the product you recently submitted for publication on Your Multi-Vendor Site. The product review process has been completed, and we have the following update for you:<br>
					   
					   Product Name: ' . $product->get_name() . '
					   Submission Date: ' . gmdate( $date_fomat, strtotime( $product->get_date_modified() ) ) . '
					   Review Status: Approved<br>
					   
					   Congratulations! Your product has met our quality and content guidelines and is now live on ' . get_bloginfo( 'name' ) . ', available for customers to browse and purchase. We appreciate your dedication to delivering excellent products to our platform.<br>
					   
					   Thank you for your contribution to ' . get_bloginfo( 'name' ) . ', and we appreciate your commitment to maintaining the quality and integrity of our platform. We look forward to seeing your products thrive on our platform.<br>';
			 
				

				$headers   = array();
				$headers[] = 'Content-type: text/html; charset=utf-8';
				$headers[] = 'From:' . get_bloginfo( 'admin_email' );
				// Send email using wp_mail() function
				$result = wp_mail( $to, $subject, $body, $headers );

			

			}

			if ( 'reject' === sanitize_text_field( wp_unslash( $_POST['status'] ) ) ) {
			  

				$product->update_meta_data( 'elex_mv_rejection_message', $message_inp );
				$prod_store_id = $product->get_meta( 'elex_mv_store_id', true );
				$store_post    = get_post( $prod_store_id );


				$store_obj  = Store::load_by_store( $store_post );
				$date_fomat = get_option( 'date_format' );
				$to         = ! empty( $store_obj->get_email() ) ? $store_obj->get_email() : '' ;
			  
				$subject = 'Product Rejected by Site Administrator';
				$body    = 'Dear ' . $store_obj->get_title() . ',<br>

						We hope this message finds you well.<br>
					   
						We would like to inform you about the status of the product you recently submitted for publication on ' . $store_obj->get_title() . ' Site. The product review process has been completed, and we have the following update for you:<br>
					   
						Product Name: ' . $product->get_name() . '
						Submission Date: ' . gmdate( $date_fomat, strtotime( $product->get_date_modified() ) ) . "
						Review Status: Rejected<br>
					   
						We regret to inform you that your product did not meet our guidelines for publication. We have provided specific feedback and reasons for the rejection below:<br>

						You make certain required changes to the product & resubmit it for approval through your vendor dashboard. We are here to support you in ensuring your product aligns with our platform's standards.<br>
							
						Thank you for your contribution to " . get_bloginfo( 'name' ) . ', and we appreciate your commitment to maintaining the quality and integrity of our platform. We look forward to seeing your products thrive on our platform.<br>';
			 
					

				$headers   = array();
				$headers[] = 'Content-type: text/html; charset=utf-8';
				$headers[] = 'From:' . get_bloginfo( 'admin_email' );
				// Send email using wp_mail() function
				$result = wp_mail( $to, $subject, $body, $headers );

			}

			$product->save();


			wp_send_json_success( 'succesful', 200 );
			die();

		} else {
			wp_send_json_error( 'failed', 200 );

		}
	} 

	public static function admin_product_statuses() {

		$statuses = array(
			'pending',
			'publish',
			'reject',
			'draft',
		);


		/**
		 * To add custom statuses for products.
		 *
		 * @since 1.0.0
		 */
		return apply_filters( 'elex_mv_product_statuses', $statuses );
	}

   
	private function fetch_admin_product_page_data() {
		$nonce = isset( $_GET['admin_product_page_nonce'] ) ? sanitize_text_field( wp_unslash( $_GET['admin_product_page_nonce'] ) ) : '';
		if ( ! wp_verify_nonce( $nonce, 'admin_product_page_nonce' ) ) {
			return array();
		}

		return array(
			'menu_tab'    => isset( $_GET['menu_tab'] ) ? sanitize_text_field( wp_unslash( $_GET['menu_tab'] ) ) : '',
			'page_num'    => isset( $_GET['page_num'] ) ? absint( $_GET['page_num'] ) : 1,
			'status'      => isset( $_GET['status'] ) ? sanitize_text_field( wp_unslash( $_GET['status'] ) ) : '',
			'vendor'      => isset( $_GET['vendor'] ) ? absint( $_GET['vendor'] ) : '',
			'enabled'     => isset( $_GET['enabled'] ) ? sanitize_text_field( wp_unslash( $_GET['enabled'] ) ) : '',
			'search_term' => isset( $_GET['search_term'] ) ? sanitize_text_field( wp_unslash( $_GET['search_term'] ) ) : '',
			'from_date'   => isset( $_GET['from_date'] ) ? sanitize_text_field( wp_unslash( $_GET['from_date'] ) ) : '',
			'to_date'     => isset( $_GET['to_date'] ) ? sanitize_text_field( wp_unslash( $_GET['to_date'] ) ) : '',
		);
	}

	public function elex_mv_admin_product_controller_page() {
		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			return;
		}

		$filters = $this->fetch_admin_product_page_data();

		// Default Used in template file
		$GET_search_term = ! empty( $filters['search_term'] ) ? $filters['search_term'] : '';
		$GET_status      = ! empty( $filters['status'] ) ? $filters['status'] : '';
		$GET_enabled     = ! empty( $filters['enabled'] ) ? $filters['enabled'] : '';
		$GET_vendor      = ! empty( $filters['vendor'] ) ? $filters['vendor'] : '';
		$menuu           = ! empty( $filters['menu_tab'] ) ? $filters['menu_tab'] : '';
		$page_number     = ! empty( $filters['page_num'] ) ? $filters['page_num'] : 1;
		$from_date       = ! empty( $filters['from_date'] ) ? $filters['from_date'] : '';
		$to_date         = ! empty( $filters['to_date'] ) ? $filters['to_date'] : '';

		$product_statuses = self::admin_product_statuses();
		global $wp_post_statuses;

		$args = array(
			'limit'    => 10,
			'paginate' => true,
			'status'   => array( 'reject', 'publish', 'pending', 'draft' ),
			'meta_key' => 'elex_mv_store_id', // phpcs:ignore WordPress.DB.SlowDBQuery
		);

		$args['page'] = $page_number;

		if ( ! empty( $GET_status ) ) {
			$args['post_status'] = $GET_status;
		}
		if ( ! empty( $GET_vendor ) ) {
			$args['meta_key']   = 'elex_mv_store_id' ; // phpcs:ignore WordPress.DB.SlowDBQuery
			$args['meta_value'] = $GET_vendor ; // phpcs:ignore WordPress.DB.SlowDBQuery
		}
		if ( ! empty( $GET_enabled ) ) {
			$args['visibility'] = $GET_enabled;
		}
		if ( ! empty( $GET_search_term ) ) {
			$args['s'] = $GET_search_term;
		}

		if ( ! empty( $from_date ) ) {
			$date_query         = array(
				array(
					'after'     => $from_date,
					'before'    => $to_date,
					'inclusive' => true,
				),
			);
			$args['date_query'] = $date_query;
		} else {
			$args['date_query'] = '';
		}
	   
		$products_query = new \WC_Product_Query( $args );

		$products_elex_mv = wc_get_products( $args );
		
		// $total_pages = ceil( $products_elex_mv->total  / $args['limit'] );
		// $wc_products->total
		$total_pages = $products_elex_mv->max_num_pages;

		$next = null;

		if ( $total_pages > $page_number ) {
			$next = $page_number + 1;
		}

		$prev = null;

		if ( $page_number > 1 ) {
			$prev = $page_number - 1;
		}

		$map_product_with_store = array();

	   
			 
		$products_elex_mv = $products_elex_mv->products;
		foreach ( $products_elex_mv as $product ) {
		  
			$store_id = $product->get_meta( 'elex_mv_store_id', true );

		

			$map_product_with_store[ $product->get_id() ] = array(
				'title' => get_post_meta( $store_id, 'elex_mv_title', true ),
				'email' => get_post_meta( $store_id, 'elex_mv_email', true ),
			);


		}

			$product_count_by_status = array();
		foreach ( $product_statuses as $status ) {
			$products = wc_get_products(
				array(
					'status'   => $status,
					'limit'    => -1,
					'meta_key' => 'elex_mv_store_id', // phpcs:ignore WordPress.DB.SlowDBQuery
				)
			);

		$product_count_by_status[ $status ] = count( $products );

	

		}
				
		$count_of_mv_product = count( $products_elex_mv );
		

		$site_settings = get_option( 'elex_mv_admin_installation_params', false );

		include ELEX_MULTI_VENDOR_PLUGIN_PATH . '/templates/admin-products/admin-products.php';
	}

	public function elex_mv_add_admin_vendor_product_details() {

	

		if ( ! isset( $_POST['nonce'] ) || 
		! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'elex_mv_prod_page_nonce' ) 
		) {
			wp_send_json_error( self::$nonce_error_msg, 200 );
		}
		$new_product_array = array();


		$new_product_array['product_name']           = isset( $_POST['name'] ) ? sanitize_text_field( wp_unslash( $_POST['name'] ) ) : '';
		$new_product_array['product_category_admin'] = isset( $_POST['product_category'] ) ? map_deep( wp_unslash( $_POST['product_category'] ), 'sanitize_text_field' ) : '';
		$new_product_array['regular_price']          = isset( $_POST['price'] ) ? sanitize_text_field( wp_unslash( $_POST['price'] ) ) : '';
		$new_product_array['sale_price']             = isset( $_POST['sale_price'] ) ? sanitize_text_field( wp_unslash( $_POST['sale_price'] ) ) : '';

		$new_product_array['vendor_store']    = isset( $_POST['vendor_name'] ) ? sanitize_text_field( wp_unslash( $_POST['vendor_name'] ) ) : '';
		$new_product_array['commission_type'] = isset( $_POST['commission_type'] ) ? sanitize_text_field( wp_unslash( $_POST['commission_type'] ) ) : 'percent';
		$new_product_array['commission']      = isset( $_POST['commission'] ) ? sanitize_text_field( wp_unslash( $_POST['commission'] ) ) : '';


		$new_product_array['image_name'] = isset( $_FILES['elex-multi-vendor-for-woocommerce-filetag-admin-image']['name'] ) ? sanitize_text_field( $_FILES['elex-multi-vendor-for-woocommerce-filetag-admin-image']['name'] ) : '';
		$new_product_array['image_path'] = isset( $_FILES['elex-multi-vendor-for-woocommerce-filetag-admin-image']['tmp_name'] ) ? sanitize_text_field( $_FILES['elex-multi-vendor-for-woocommerce-filetag-admin-image']['tmp_name'] ) : '';
		$new_product_array['image_type'] = isset( $_FILES['elex-multi-vendor-for-woocommerce-filetag-admin-image']['type'] ) ? sanitize_text_field( $_FILES['elex-multi-vendor-for-woocommerce-filetag-admin-image']['type'] ) : '';
	
		

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


	
		$add_product_var = new Product();
		$elex_mv_prod_id = $add_product_var->create_product( $new_product_array );

	

		wp_send_json_success( $elex_mv_prod_id, 200 );
		die;
	}

	public function elex_mv_form_product_validation( $new_product_array ) {
		$data = array(
			'message' => __( 'Empty Fields' , 'elex-multi-vendor-for-woocommerce' ),
			'errors'  => array(),
		);
	
		if ( ! isset( $new_product_array['product_name'] ) || empty( $new_product_array['product_name'] ) ) {
			$data['errors']['product_name'][] = __( 'Please enter name.', 'elex-multi-vendor-for-woocommerce' );
		}
		if ( isset( $new_product_array['product_name'] ) && ! preg_match( '/^[a-zA-z][ a-zA-z_0-9]*$/', $new_product_array['product_name'] ) ) {
		$data['errors']['product_name'][] = __( 'Only alphabets and whitespace are allowed.', 'elex-multi-vendor-for-woocommerce' );
		}
		
	

		if ( ! empty( $new_product_array['sale_price'] ) ) {
	
			if ( ! is_numeric( $new_product_array['sale_price'] ) ) {
				$data['errors']['sale_price'][] = __( 'Enter Only Numbers. ', 'elex-multi-vendor-for-woocommerce' );
				
			}
			if ( $new_product_array['sale_price'] > $new_product_array['regular_price'] ) {
				$data['errors']['sale_price'][] = __( 'Should not be greater than regular price. ', 'elex-multi-vendor-for-woocommerce' );

			}
		} 

	

		/**
		 * To add custom statuses for products validation.
		 *
		 * @since 1.0.0
		 */
		$data = apply_filters( 'elex_mv_form_product_validation', $data );
		return $data;
	}
}
