<?php
namespace Elex\MultiVendor\Controller;

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

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

class CouponController {

	public static function init() {
		$self = new self();
		add_action( 'elex_mv_coupon_page', array( $self, 'mv_coupon_tab_content' ) );
		add_action( 'wp_ajax_elex_mv_coupon_create', array( $self, 'create' ) );
		add_action( 'wp_ajax_elex_mv_coupon_edit', array( $self, 'edit' ) );
		add_action( 'wp_ajax_elex_mv_coupon_delete', array( $self, 'delete' ) );
		add_action( 'wp_ajax_elex_mv_coupon_search_products', array( $self, 'search_products' ) );
		add_action( 'wp_ajax_elex_mv_coupon_search_categories', array( $self, 'search_categories' ) );
		add_filter( 'manage_edit-shop_coupon_columns', array( $self, 'elex_mv_add_custom_coloumn_coupon' ), 10, 1 );
		add_action( 'manage_shop_coupon_posts_custom_column' , array( $self, 'elex_mv_posts_custom_column_coupons' ), 10, 2 );
		add_action( 'woocommerce_coupon_options', array( $self, 'add_assign_vendor_meta_field' ), 10, 2 );
		add_action( 'woocommerce_coupon_options_save', array( $self, 'save_coupon_meta_field' ), 10, 2 );
		add_filter( 'woocommerce_coupon_is_valid_for_product', array( $self, 'check_validity_for_product' ), 10, 4 ); 
	}

	public function check_validity_for_product( $valid, $product, $coupon, $values ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed

		$valid = true;

		$store_id = $product->get_meta( 'elex_mv_store_id', true );

		if ( ! empty( $coupon->get_meta( 'elex_mv_store_id' ) ) ) {
			if ( (string) $store_id !== (string) $coupon->get_meta( 'elex_mv_store_id' ) ) {
				$valid = false;
			}       
		}

	
		return $valid;
	}

	public function save_coupon_meta_field( $post_id, $coupon ) {

		if ( ! isset( $_POST['_wpnonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), 'woocommerce-save-data' ) ) {
			return;
		}

		if ( isset( $_POST['store_id'] ) ) {
			$coupon->update_meta_data( 'elex_mv_store_id', sanitize_text_field( wp_unslash( $_POST['store_id'] ) ) );
			$coupon->save();
		}    
	}

	public function add_assign_vendor_meta_field( $coupon_id, $coupon_data ) {

		$author_id  = get_post_field( 'post_author', $coupon_id );
		$vendor_id  = ! empty( $coupon_data->get_meta( 'elex_mv_vendor_id' ) ) ? $coupon_data->get_meta( 'elex_mv_vendor_id' ) : '';
		$store_id   = ! empty( $coupon_data->get_meta( 'elex_mv_store_id' ) ) ? $coupon_data->get_meta( 'elex_mv_store_id' ) : '';
		$store_name = ! empty( $coupon_data->get_meta( 'elex_mv_store_id' ) ) ? get_post_field( 'post_title', $store_id ) : '';
		$selected   = false;
		if ( $store_id ) {
			$selected = true;
		}
		if ( $author_id === $vendor_id ) {  
			$username = get_the_author_meta( 'user_nicename' , $vendor_id );

			woocommerce_wp_select( 
				array( 
					'id'                => 'elex_mv_store_id', 
					'label'             => __( 'Assign vendor', 'elex-multi-vendor-for-woocommerce' ),
					'custom_attributes' => array(
						'disabled' => true,
					),
					'options'           => array( $store_id => $store_name ),
				)
			);

			return;
		}
		
		$args = array(
			'role'    => 'elex_mv_vendor',
			'orderby' => 'user_nicename',
			'order'   => 'ASC',
		);
		


		woocommerce_wp_select( 
			array( 
				'id'       => 'elex_mv_store_id',
				'class'    => 'elex_mv_vendors_input',
				'label'    => __( 'Assign vendor', 'elex-multi-vendor-for-woocommerce' ),
				'selected' => $selected,
				'value'    => $store_id,
				'options'  => array( $store_id => $store_name ),
			)
		);
	}

	public function mv_coupon_tab_content() {

		$vendor          = Vendor::load( wp_get_current_user() );
		$store           = $vendor->get_store();
		$store_id        = $store->get_id();
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- filter input only for pagination context.
		$current_page    = ! empty( filter_input( INPUT_GET, 'page_coupon' , FILTER_SANITIZE_NUMBER_INT ) ) ? absint( filter_input( INPUT_GET, 'page_coupon' , FILTER_SANITIZE_NUMBER_INT ) ) : 1;
		$coupon_per_page = 10; // Number of Coupon per page

		$filters = array(
			'numberposts' => $coupon_per_page, // How many per page
			'paged'       => $current_page, // What page to get, starting from 1.
		);

		if ( ! empty( get_query_var( 'search_term' ) ) ) {
			$filters['s'] = get_query_var( 'search_term' );
		}
	
		$coupon_model   = new Coupon();
		$vendor_coupons = $coupon_model->load_coupon_by_store( $store_id, $filters );
		$total_coupons  = $coupon_model->coupon_total_count( $store_id, $filters ); // How many users we have in total (beyond the current page)
		$num_pages      = ceil( $total_coupons / $coupon_per_page );

		include ELEX_MULTI_VENDOR_PLUGIN_PATH . 'templates/coupons/Viewcoupon.php';
		include ELEX_MULTI_VENDOR_PLUGIN_PATH . 'templates/coupons/Editcoupon.php';
		include ELEX_MULTI_VENDOR_PLUGIN_PATH . 'templates/coupons/Createcoupon.php';
	}

	public function search_categories() {
		if ( ! current_user_can( 'elex_mv_vendor' ) && ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( 'Forbidden', 403 );
		}
		if ( ! isset( $_POST['_ajax_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_ajax_nonce'] ) ), 'elex_mv_prod_page_nonce' ) ) {
			wp_send_json_error( 'Security check failed', 403 );
		}
		$product_category_data      = array();
		$product_category_data_temp = array();
		$product_category           = get_terms(
			array(
				'taxonomy' => 'product_cat',
				'search'   => isset( $_POST['search'] ) ? sanitize_text_field( wp_unslash( $_POST['search'] ) ) : '',
			) 
		);
		foreach ( $product_category as $category ) {
			$product_category_data['id']   = $category->term_id;
			$product_category_data['text'] = $category->name;
			$product_category_data_temp[]  = $product_category_data;
		}
		wp_send_json_success( $product_category_data_temp );
	}

	public function search_products() {
		if ( ! current_user_can( 'elex_mv_vendor' ) && ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( 'Forbidden', 403 );
		}
		if ( ! isset( $_POST['_ajax_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_ajax_nonce'] ) ), 'elex_mv_prod_page_nonce' ) ) {
			wp_send_json_error( 'Security check failed', 403 );
		}
		$vendor            = Vendor::load( wp_get_current_user() );
		$store             = $vendor->get_store();
		$store_id          = $store->get_id();
		$product_data      = array();
		$product_data_temp = array();
		$args              = array(
			'meta_key'   => 'elex_mv_store_id', // phpcs:ignore WordPress.DB.SlowDBQuery
			'meta_value' => $store_id, // phpcs:ignore WordPress.DB.SlowDBQuery
			's'          => isset( $_POST['search'] ) ? sanitize_text_field( wp_unslash( $_POST['search'] ) ) : '',
			
		);
		$products = wc_get_products( $args );
		foreach ( $products as $product ) {
			$product_data['id']   = $product->get_id();
			$product_data['text'] = $product->get_name();
			$product_data_temp[]  = $product_data;
		}
		wp_send_json_success( $product_data_temp );
	}

	public function create() {
		if ( ! current_user_can( 'elex_mv_vendor' ) && ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( 'Forbidden', 403 );
		}

		if ( ! isset( $_POST['mv_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['mv_nonce'] ) ), '_ajax_nonce' ) ) {
			wp_send_json_error( 'Security check failed', 403 );
		}

		$coupon_form_fields_data = array();

		if ( isset( $_POST['id'] ) && ! empty( $_POST['id'] ) ) {
			$coupon = new \WC_Coupon( sanitize_text_field( wp_unslash( $_POST['id'] ) ) );
		} else {
			$coupon = new \WC_Coupon();
		}
	
		$coupon_data_array                             = array();
		$coupon_data_array['title']                    = isset( $_POST['title'] ) ? sanitize_text_field( wp_unslash( $_POST['title'] ) ) : '';
		$coupon_data_array['description']              = isset( $_POST['description'] ) ? sanitize_text_field( wp_unslash( $_POST['description'] ) ) : '';
		$coupon_data_array['code']                     = isset( $_POST['code'] ) ? sanitize_text_field( wp_unslash( $_POST['code'] ) ) : '';
		$coupon_data_array['amount']                   = isset( $_POST['amount'] ) ? sanitize_text_field( wp_unslash( $_POST['amount'] ) ) : 0;
		$coupon_data_array['discount_type']            = isset( $_POST['discount_type'] ) ? sanitize_text_field( wp_unslash( $_POST['discount_type'] ) ) : '';
		$coupon_data_array['valid_from']               = isset( $_POST['valid_from'] ) ? sanitize_text_field( wp_unslash( $_POST['valid_from'] ) ) : '';
		$coupon_data_array['valid_till']               = isset( $_POST['valid_till'] ) ? sanitize_text_field( wp_unslash( $_POST['valid_till'] ) ) : '';
		$coupon_data_array['min_cart_spending']        = isset( $_POST['min_cart_spending'] ) ? sanitize_text_field( wp_unslash( $_POST['min_cart_spending'] ) ) : '';
		$coupon_data_array['max_cart_spending']        = isset( $_POST['max_cart_spending'] ) ? sanitize_text_field( wp_unslash( $_POST['max_cart_spending'] ) ) : '';
		$coupon_data_array['individual_coupon_use']    = isset( $_POST['individual_coupon_use'] ) ? true : false;
		$coupon_data_array['exclude_on_sale_item']     = isset( $_POST['exclude_on_sale_item'] ) ? true : false;
		$coupon_data_array['mv-coupon-product']        = isset( $_POST['mv-coupon-product'] ) ? map_deep( wp_unslash( $_POST['mv-coupon-product'] ), 'sanitize_text_field' ) : '';
		$coupon_data_array['exclude_product']          = isset( $_POST['exclude_product'] ) ? map_deep( wp_unslash( $_POST['exclude_product'] ), 'sanitize_text_field' ) : '';
		$coupon_data_array['product_category']         = isset( $_POST['product_category'] ) ? map_deep( wp_unslash( $_POST['product_category'] ), 'sanitize_text_field' ) : '';
		$coupon_data_array['exclude_product_category'] = isset( $_POST['exclude_product_category'] ) ? map_deep( wp_unslash( $_POST['exclude_product_category'] ), 'sanitize_text_field' ) : '';
		$coupon_data_array['allowed_emails']           = isset( $_POST['allowed_emails'] ) ? explode( ',', map_deep( wp_unslash( $_POST['allowed_emails'] ), 'sanitize_text_field' ) ) : '';
		$coupon_data_array['usage_limit_per_coupon']   = isset( $_POST['usage_limit_per_coupon'] ) ? sanitize_text_field( wp_unslash( $_POST['usage_limit_per_coupon'] ) ) : '';
		$coupon_data_array['usage_limit_x_items']      = isset( $_POST['usage_limit_x_items'] ) ? sanitize_text_field( wp_unslash( $_POST['usage_limit_x_items'] ) ) : '';
		$coupon_data_array['usage_limit_per_user']     = isset( $_POST['usage_limit_per_user'] ) ? sanitize_text_field( wp_unslash( $_POST['usage_limit_per_user'] ) ) : '';
		
		$validation_errors = $this->elex_mv_form_coupon_validation( $coupon_data_array );
		if ( isset( $validation_errors['errors'] ) && count( $validation_errors['errors'] ) ) {
			wp_send_json_error( $validation_errors['errors'] );
			die;
		}

		$Couponmodel = new Coupon();
		$vendor      = Vendor::load( wp_get_current_user() );
		$store       = $vendor->get_store();
		$Couponmodel->save( $coupon, $coupon_data_array, $store->get_id() );
		wp_send_json_success( array( $coupon_data_array ) );
	}
	
	public function edit() {
		if ( ! current_user_can( 'elex_mv_vendor' ) && ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( 'Forbidden', 403 );
		}

		if ( ! isset( $_POST['_ajax_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_ajax_nonce'] ) ), 'elex_mv_prod_page_nonce' ) ) {
			wp_send_json_error( 'Security check failed', 403 );
		}

		$coupon_data_array = array(); 

		if ( isset( $_POST['id'] ) && ! empty( $_POST['id'] ) ) { 

		$coupon = new \WC_Coupon( sanitize_text_field( wp_unslash( $_POST['id'] ) ) );

		$Couponmodel                                   = new Coupon();
		$product_ids                                   = $Couponmodel->products( $coupon->get_product_ids() );
		$exclude_product_ids                           = $Couponmodel->products( $coupon->get_excluded_product_ids() );
		$categories                                    = $Couponmodel->categories( $coupon->get_product_categories() );
		$excluded_categories                           = $Couponmodel->categories( $coupon->get_excluded_product_categories() );
		$coupon_data_array['title']                    = $coupon->get_meta( 'elex_mv_coupon_title' );
		$coupon_data_array['description']              = $coupon->get_description();
		$coupon_data_array['code']                     = $coupon->get_code();
		$coupon_data_array['coupon_amount']            = $coupon->get_amount();
		$coupon_data_array['discount_type']            = $coupon->get_discount_type();
		$coupon_data_array['valid_from']               = $coupon->get_meta( 'elex_mv_validity_from' );
		$coupon_data_array['valid_till']               = $coupon->get_date_expires() ? $coupon->get_date_expires()->date( 'Y-m-d' ) : '';
		$coupon_data_array['min_cart_spending']        = $coupon->get_minimum_amount();
		$coupon_data_array['max_cart_spending']        = $coupon->get_maximum_amount();
		$coupon_data_array['individual_coupon_use']    = $coupon->get_individual_use();
		$coupon_data_array['exclude_on_sale_item']     = $coupon->get_exclude_sale_items();
		$coupon_data_array['products']                 = ! empty( $product_ids ) ? map_deep( wp_unslash( $product_ids ), 'sanitize_text_field' ) : '';
		$coupon_data_array['exclude_product']          = ! empty( $exclude_product_ids ) ? map_deep( wp_unslash( $exclude_product_ids ), 'sanitize_text_field' ) : '';
		$coupon_data_array['product_category']         = ! empty( $categories ) ? map_deep( wp_unslash( $categories ), 'sanitize_text_field' ) : '';
		$coupon_data_array['exclude_product_category'] = ! empty( $excluded_categories ) ? map_deep( wp_unslash( $excluded_categories ), 'sanitize_text_field' ) : '';
		$coupon_data_array['allowed_emails']           = $coupon->get_email_restrictions();
		$coupon_data_array['usage_limit_per_coupon']   = ! empty( $coupon->get_usage_limit() ) ? $coupon->get_usage_limit() : '' ;
		$coupon_data_array['usage_limit_x_items']      = ! empty( $coupon->get_limit_usage_to_x_items() ) ? $coupon->get_limit_usage_to_x_items() : '';
		$coupon_data_array['usage_limit_per_user']     = ! empty( $coupon->get_usage_limit_per_user() ) ? $coupon->get_usage_limit_per_user() : '';

		}

		wp_send_json_success( $coupon_data_array );
	}
	

  
	public function delete() {
		if ( ! current_user_can( 'elex_mv_vendor' ) && ! current_user_can( 'manage_woocommerce' ) ) {
			wp_send_json_error( 'Forbidden', 403 );
		}

		if ( ! isset( $_POST['_ajax_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_ajax_nonce'] ) ), 'elex_mv_prod_page_nonce' ) ) {
			wp_send_json_error( 'Security check failed', 403 );
		}

		if ( isset( $_POST['id'] ) && ! empty( $_POST['id'] ) ) {
		
			$ids = explode( ',', map_deep( wp_unslash( $_POST['id'] ), 'sanitize_text_field' ) );
			
			if ( is_array( $ids ) && count( $ids ) > 1 ) {
				foreach ( $ids as $id ) {
					wp_delete_post( $id );
				}    
			} else {
				wp_delete_post( sanitize_text_field( wp_unslash( $_POST['id'] ) ) );
			}
		}
	}

	public function elex_mv_add_custom_coloumn_coupon( $columns ) {   
		// Add new column
		$columns['coupon_author'] = __( 'Author', 'elex-multi-vendor-for-woocommerce' );
		return $columns;
	}
   
	
	// Populate the Column
	public function elex_mv_posts_custom_column_coupons( $column, $post_id ) {

		if ( 'coupon_author' === $column ) {

			$author_id    = get_post_field( 'post_author', $post_id );
			$display_name = get_the_author_meta( 'display_name' , $author_id );

			if ( ! empty( $display_name ) ) {
				echo esc_attr( $display_name );         
			}
		}
	}

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

		if ( ! isset( $coupon_data_array['code'] ) || empty( $coupon_data_array['code'] ) ) {
			$data['errors']['code'][] = __( 'Please enter coupon code', 'elex-multi-vendor-for-woocommerce' );
		}
		if ( isset( $coupon_data_array['code'] ) && ! empty( $coupon_data_array['code'] ) && ! preg_match( '/^[A-Za-z0-9][ A-Za-z0-9_]{0,29}$/', $coupon_data_array['code'] ) ) {
			$data['errors']['code'][] = __( 'Only alphabets and numbers are allowed.', 'elex-multi-vendor-for-woocommerce' );
		}
		if ( ! isset( $coupon_data_array['amount'] ) || empty( $coupon_data_array['amount'] ) ) {
			$data['errors']['amount'][] = __( 'Please enter coupon amount.', 'elex-multi-vendor-for-woocommerce' );
		}
		
		if ( isset( $coupon_data_array['amount'] ) && ! preg_match( '/^[0-9]*$/', $coupon_data_array['amount'] ) ) {
			$data['errors']['amount'][] = __( 'Only numbers are allowed.', 'elex-multi-vendor-for-woocommerce' );
		}
		/**
		 * Fires a hook for validation data
		 * 
		 * @since 1.0.0
		 * @param $data
		 */
		$data = apply_filters( 'elex_mv_form_coupon_validation', $data );
		return $data;
	}
}
