<?php
class NBT_PriceMatrix_Admin{
	public $available_tabs = array();
	
	protected $args;
	public $tab_price_matrix = 'price_matrix';
	
	function __construct() {
		add_action( 'admin_enqueue_scripts', array($this, 'price_matrix_scripts_method') );

		add_filter('woocommerce_product_data_tabs', array($this, 'woocommerce_product_tabs_price_matrix'), 50, 1);
		add_action( 'woocommerce_product_data_panels', array($this, 'woocommerce_product_panels_price_matrix') );
		add_action('save_post', array($this, 'pm_woocommerce_process_product_meta_variable'), 10, 1);

		add_action( 'wp_ajax_nopriv_pm_load_variations', array($this, 'pm_load_variations') );
		add_action( 'wp_ajax_pm_load_variations', array($this, 'pm_load_variations') );
		add_action( 'wp_ajax_nopriv_pm_save_variations', array($this, 'pm_save_variations') );
		add_action( 'wp_ajax_pm_save_variations', array($this, 'pm_save_variations') );
		add_action( 'wp_ajax_nopriv_pm_enter_price', array($this, 'pm_enter_price') );
		add_action( 'wp_ajax_pm_enter_price', array($this, 'pm_enter_price') );
		add_action( 'wp_ajax_nopriv_pm_save_price', array($this, 'pm_save_price') );
		add_action( 'wp_ajax_pm_save_price', array($this, 'pm_save_price') );
		add_action( 'wp_ajax_nopriv_pm_load_table', array($this, 'pm_load_table') );
		add_action( 'wp_ajax_pm_load_table', array($this, 'pm_load_table') );

		add_filter( 'product_type_options', array( $this, 'admin_toggle_option' ), 10, 1  );

        add_action('admin_notices', array($this, 'general_admin_notice'));
		
		if( !class_exists('NBT_Plugins') ){
			require_once NBT_PRICEMATRIX_PATH . 'inc/plugins.php';
		}
			
        if( !defined('PREFIX_NBT_SOL') && class_exists('NBT_Plugins') ){
            add_action( 'admin_menu', array( $this, 'register_panel' ), 5 );
        }



		if(!did_action( 'woocommerce_before_single_product' ) === 1 ){
			add_action( 'admin_notices', array( $this, 'add_disable_hooks_notice') );
		}

	}
    public function disable_hooks_notice() {?>
        <div class="error">
            <p><?php _e( 'WooCommerce plugin is not activated. Please install and activate it to use for plugin <strong>Ajax Drop Down Cart for WooCommerce Wordpress</strong>.', 'nbt-ajax-cart' ); ?></p>
        </div>
        <?php    
    }
	

    public function register_panel(){
        $args = array(
            'create_menu_page' => true,
            'parent_slug'   => '',
            'page_title'    => __( 'Price Matrix', 'nbt-plugins' ),
            'menu_title'    => __( 'Price Matrix', 'nbt-plugins' ),
            'capability'    => apply_filters( 'nbt_cs_settings_panel_capability', 'manage_options' ),
            'parent'        => '',
            'parent_page'   => 'ntb_plugin_panel',
            'page'          => NBT_Solutions_Price_Matrix::$plugin_id,
            'admin-tabs'    => $this->available_tabs,
            'functions'     => array(__CLASS__ , 'ntb_cs_page')
        );

        $this->_panel = new NBT_Plugins($args);
    }

    public static function ntb_cs_page(){
    	include(NBT_PRICEMATRIX_PATH .'tpl/admin/admin.php');
    }

    function general_admin_notice() {
    	global $post;
    	if(isset($post->post_type) && $post->post_type == 'product'){
    		if(get_post_meta($post->ID, '_enable_price_matrix', true) == 'on' && !get_post_meta($post->ID, '_pm_num', true)){
	        ?>
	        <div class="error">
	            <p><?php printf('It seems Price Matrix has been <strong>activated</strong> but you didn\'t set any attributes and prices for this product. You can see <a href="%s" target="_blank">this guide</a> for more details.', home_url() ); ?></p>
	        </div>
    		<?php
    		}
    	}
    }

	/**
	 * Add admin option
	 */
	public function admin_toggle_option( $options ) {
		global $post;
		$default = 'no ';
		if(get_post_meta($post->ID, '_enable_price_matrix', true) == 'on'){
			$default = 'yes ';
		}
		$options['enable_price_matrix'] = array(
			'id'            => '_enable_price_matrix',
			'wrapper_class' => $default.'show_if_variable',
			'label'         => __( 'Price Matrix', 'WooCommerce Price Matrix' ),
			'description'   => __( 'Replace front-end dropdowns with a price matrix. This option limits "Used for varations" to 2.', 'WooCommerce Price Matrix' ),
			'default'       => trim($default),
		);


		return $options;
	}

    public function remove_variations($post_id){
    	global $wpdb;

    	$product = wc_get_product($post_id);

    	$_pm_table_attr = get_post_meta($post_id, '_product_attributes', true);

    	$get_attributes = $product->get_attributes( 'edit' );

    	$meta_array = array();
    	$results =  $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE post_type = 'product_variation' AND post_parent = '%s'", $post_id), OBJECT);
    	if($results && $_pm_table_attr){
    		
    		foreach ($results as $key => $p) {

    			$new_count = 0;
    			foreach ($get_attributes as $k_attr => $attribute) {
    				/* Check no set value */
    				$check_post_meta = get_post_meta($p->ID, 'attribute_'.$k_attr, true);
    				if($check_post_meta){
    					$new_count += 1; 
    				}

    				/* Select other value */
					if ( $attribute->is_taxonomy() ) :
						$attr_new = array();
						foreach ( $attribute->get_terms() as $option ) :
							$attr_new[] = esc_attr( $option->slug );
						endforeach;

						if(!in_array($check_post_meta, $attr_new)):
							$meta_array[$p->ID] = $p->ID;
						endif;

					else :
						$attr_new = array();
						foreach ( $attribute->get_options() as $option ) :
							$attr_new[] = esc_attr( $option );
						endforeach;

						if(!in_array($check_post_meta, $attr_new)):
							$meta_array[$p->ID] = $p->ID;
						endif;
					endif;

    			}
    			if($new_count != count($_pm_table_attr)){
    				$meta_array[$p->ID] = $p->ID;
    			}
    		}
    	}

    	if( isset($meta_array) && !empty($meta_array) ){
    		$ids = implode( ',', array_map( 'absint', $meta_array ) );
    		$wpdb->query( "DELETE FROM $wpdb->posts WHERE ID IN($ids)" );
    	}
    }

	public function pm_load_variations(){
		$nonce = $_REQUEST['security'];

		if ( ! wp_verify_nonce( $nonce, 'load-variations' ) ) {

		     die( 'Security check' ); 

		} else {
			$json = array();
			global $wpdb, $post, $woocommerce;

			$product_id = isset( $_POST['product_id'] ) ? wc_clean( $_POST['product_id'] ) : '';
			$attributes = isset( $_POST['attributes'] ) ? wc_clean( $_POST['attributes'] ) : '';


			$html = '';
			if( !empty($attributes) && count( $attributes ) >= 2):
				$json['complete'] = true;
	
				$attr_parent = '<option value="0" selected>(Select an Attributes)</option>';
				foreach ($attributes as $key => $attribute) :
					if($attribute['is_taxonomy']){
						$attribute_id = intval($attribute['id']);
						$attribute_label = $wpdb->get_var( "SELECT attribute_label FROM {$wpdb->prefix}woocommerce_attribute_taxonomies WHERE attribute_id = $attribute_id" );
						if($attribute_label){
							$attr_parent .= '<option value="'.$attribute['name'].'">'.$attribute_label.'</option>';
						}
					}else{
						$check_key = get_post_meta($product_id, '_product_attributes', TRUE);
						$attribute_key = '';
						foreach ($check_key as $k_c => $value) {
							if($value['name'] == $attribute['name']){
								$attribute_key = $k_c;
							}
						}
						$attr_parent .= '<option value="'.$attribute_key.'">'.$attribute['name'].'</option>';
					}


				endforeach;
				$json['attr'] = $attr_parent;

				/* Check if data price matrix exists */
				$check_data = get_post_meta($product_id, '_pm_table_attr', true);
	
				if( ! $check_data || isset($check_data[0]) && !empty($check_data[0]) ):
					$json['return'] = false;
				else:
					$json['return'] = true;
				endif;
			endif;

			echo json_encode($json, TRUE);
		}
		wp_die();
	}

	public function pm_save_variations(){
		global $wpdb;
		$error = false;
		$nonce = $_REQUEST['security'];

		if ( ! wp_verify_nonce( $nonce, '_price_matrix_save' ) ) {
		     die( 'Security check' ); 
		} else {
			$product_id = $_REQUEST['product_id'];
			$pm_attr = $_REQUEST['pm_attr'];
			$pm_direction = $_REQUEST['pm_direction'];

			$max_direction = array_count_values($pm_direction);
			$max_direction_key = array_search(max($max_direction), $max_direction);

			
				$new_array = array();
				foreach ($pm_attr as $key => $value) {
					if(empty($value)){
						$json['msg'] = 'Please select an attribute!';
						$error = true;
					}
					$new_array[$pm_direction[$key]][] = $value; 
				}

				$count_vertical = count($new_array['vertical']);
				$count_horizontal = count($new_array['horizontal']);

				if(count($pm_attr) == 3){

					if($max_direction_key == 'vertical'){
						if($count_horizontal != 1){
							$json['msg'] = 'Please select the Horizontal direction!';
							$error = true;
						}
					}else{
						if($count_vertical != 1){
							$json['msg'] = 'Please select the Vertical direction!';
							$error = true;
						}
					}
				}elseif(count($pm_attr) == 2){
						if($count_vertical <= 0 ){
							$json['msg'] = 'Please select the Vertical direction!';
							$error = true;
						}

						if($count_horizontal <= 0){
							$json['msg'] = 'Please select the Horizontal direction!';
							$error = true;
						}
				}elseif(count($pm_attr) == 4){
						if($count_vertical != 2 ){
							$json['msg'] = 'Please select the Vertical direction!';
							$error = true;
						}

						if($count_horizontal != 2){
							$json['msg'] = 'Please select the Horizontal direction!l';
							$error = true;
						}
				}


				if(!$error){

					if(count($pm_attr) <= 1){
							$json['msg'] = 'Please select more Attributes!';
							$error = true;
					}

					if(!$error){
						$this->remove_variations($product_id);
						$json['complete'] = true;

						$count_parent =  $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM ".$wpdb->prefix."posts WHERE post_parent = '%s' AND post_status = 'publish'", $product_id), OBJECT);
						$total_var = count($pm_attr) * count($pm_attr) * count($pm_attr);
						if(!$count_parent || $count_parent < $total_var){
						$json['notice'] = $count_parent.'<div id="message" class="inline notice woocommerce-message msg-enter-price">
							<p>Press the <strong>Input Price</strong> button to input price for this product before saving!</p>
						</div>';
						}

						update_post_meta($product_id, '_pm_table_attr', $pm_attr);
						update_post_meta($product_id, '_pm_table_direction', $pm_direction);
						update_post_meta($product_id, '_pm_attr', $new_array);
						update_post_meta($product_id, '_pm_direction', $max_direction_key);
						update_post_meta($product_id, '_pm_num', count($pm_attr));
					}
				}
	

			echo json_encode($json, TRUE);
		}
		wp_die();
	}

	public function pm_enter_price($product_id = false, $deprived = false, $load = false){
		if(!$product_id){
			$product_id = $_REQUEST['product_id'];
		}
		$product = wc_get_product($product_id);


		$_pm_table_attr = get_post_meta($product_id, '_pm_table_attr', true);
		$_pm_direction = get_post_meta($product_id, '_pm_direction', true);
		$_pm_num = get_post_meta($product_id, '_pm_num', true);

		$symbol = get_woocommerce_currency_symbol(get_option('woocommerce_currency'));

		$json['complete'] = true;
		$html = '';
		if(empty($deprived)){
			$html .= '<div id="price-matrix-popup" class="white-popup mfp-hide">
			<h2>Price Matrix: Input Price</h2><div class="enter-price-wrap">';
		}
		ob_start();
		$attr = $_POST['attr'];
		foreach ($attr as $key => $value) {
			if(in_array($key, $_pm_table_attr)){
				unset($attr[$key]);
			}
		}

		$total_real_attr = count($_POST['attr']);

		$suffix = '';
		if($_pm_num == 3){
			$suffix = '-'.$_pm_direction.'-'.$_pm_num;
		}elseif($_pm_num == 4){
			$suffix = '-'.$_pm_num;
		}
		$khuyet = false;
		if($total_real_attr != $_pm_num){
			$khuyet = true;
		}

		if(file_exists(NBT_PRICEMATRIX_PATH .'tpl/admin/table-matrix' . $suffix.'.php')){
			
			$_pm_table_direction = get_post_meta($product_id, '_pm_table_direction', true);
			$_pm_attr = get_post_meta($product_id, '_pm_attr', true);

			if($khuyet && empty($deprived) ){
			

				foreach ($attr as $key => $value) {
					$attribute = pm_attribute_label($key, $product_id);
					$tax = pm_attribute_tax($key, $product_id);

					$deprived[] = array('name' => $key, 'value' => $attribute[0]->slug);
					?>
			        <div class="select-wrap">
			        	<label><?php echo $tax;?></label>
			        	<select id="<?php echo $key;?>" name="attr[<?php echo $key;?>]" class="attr-select">
			        		<?php foreach ($attribute as $key => $attr):
			        			printf('<option value="%s">%s</option>', $attr->slug, $attr->name);
			        		endforeach;?>
			        	</select>
			        </div>
				<?php }

				echo '<p class="attribute-p"><strong>Note:</strong> When you finish enter the price for this attribute, please press the Save Price Matrix button before choosing another attribute. Double click to input the price!</p><p>To input the sale price, please use the "-" characters between prices. Eg: original price is $5, sale price is $2, the convention is 5-2</p>';

			}

			if(!$khuyet && !$load){
				echo '<p class="attribute-p nopadding"><strong>Note:</strong> Double click to input the price!</p><p>To input the sale price, please use the "-" characters between prices. Eg: original price is $5, sale price is $2, the convention is 5-2</p>';
			}
			include(NBT_PRICEMATRIX_PATH .'tpl/admin/table-matrix' . $suffix.'.php');
		}else{
			echo 'Sorry, this options not available for enter price';
		}
		
		$html .= ob_get_clean();
		$html .= '</div></div>';
		$json['html'] = $html;

		echo json_encode($json, TRUE);
		wp_die();
	}

	public function pm_load_table(){
		$product_id = $_REQUEST['product_id'];
		$attr = $_REQUEST['attr'];
		$load = $_REQUEST['load'];
		$deprived = array();
		if(is_array($attr)){
			foreach ($attr as $key => $value) {
				$deprived[] = array('name' => $key, 'value' => $value);
			}

		}
		
		ob_start();
		$this->pm_enter_price($product_id, $deprived, $load);
		$out = ob_get_clean();
		$json['complete'] = true;
		$json['return'] = $out;

		echo json_encode($json, TRUE);
		wp_die();
	}

	public function pm_save_price(){
		global $wpdb;
		$product_id = $_REQUEST['product_id'];
		$attr = $_REQUEST['attr'];
		$price = $_REQUEST['price'];


		$post = get_post($product_id);
		if($post && is_array($attr)){
			$_pm_num = count(get_post_meta($product_id, '_product_attributes', TRUE));

			foreach ($attr as $k_main => $array) {
				if(is_array($array) && !empty($array) && $_pm_num == count($array)){

					$sql = "SELECT posts.ID as id, posts.post_parent as parent FROM {$wpdb->posts} as posts";
					if(is_array($array) && !empty($array)){
						foreach ($array as $k => $value) {
							$sql .= " INNER JOIN {$wpdb->postmeta} AS postmeta".$k." ON posts.ID = postmeta".$k.".post_id";
						}
					}
					$sql .= " WHERE posts.post_parent = '".$product_id."' AND posts.post_type IN ( 'product', 'product_variation' ) AND posts.post_status = 'publish'";
					$i = 1;
					foreach ($array as $key => $val_attr) {
						$sql .= " AND postmeta".$key.".meta_key = 'attribute_".sanitize_text_field($val_attr['name'])."' AND postmeta".$key.".meta_value = '". sanitize_text_field($val_attr['value']) ."'";
						$i++;
					}


					$items = $wpdb->get_row($sql);

					if(!$items){
						$my_post = array(
						  'post_title'    => wp_strip_all_tags( $post->post_title ),
						  'post_comment'  => 'closed',
						  'post_status'   => 'publish',
						  'ping_status'   => 'closed',
						  'post_author'   => $post->post_author,
						  'post_name'   => $post->post_name,
						  'post_parent'   => $post->ID,
						  'guid'   => get_permalink($post->ID),
						  'post_type' => 'product_variation'
						);
						$post_id = wp_insert_post( $my_post );
					}else{
						$post_id = $items->id;
					}
					foreach ($array as $key => $postmeta_attr) {

						if($key == 0 && isset($price[$k_main]['price']) && !empty($price[$k_main]['price'])){
							if(is_numeric($price[$k_main]['price'])){
								$_regular_price = $price[$k_main]['price'];
								$_sale_price = '';
								$_price = $_regular_price;
							}else{
								$product_price = explode('-', $price[$k_main]['price']);
								if(count($product_price) == 2){
									$_regular_price = trim($product_price[0]);
									$_sale_price = trim($product_price[1]);
									$_price = $_sale_price;
								}
							}
							update_post_meta($post_id, '_regular_price', $_regular_price);
							update_post_meta($post_id, '_sale_price', $_sale_price);
							update_post_meta($post_id, '_price', $_price);
						}
						update_post_meta($post_id, 'attribute_'.$postmeta_attr['name'], $postmeta_attr['value']);
					}
				}
			}
		}
		$json['error'] = true;
		
		$json['complete'] = true;
		echo json_encode($json, TRUE);
		wp_die();
	}
	public function woocommerce_product_tabs_price_matrix($product_data_tabs){
		$product_data_tabs['price_matrix'] = array(
			'label' => __( 'Price Matrix', 'nbt-woocommerce-price-matrix' ),
			'target' => 'price_matrix',
			'class'  => array( 'hide show_if_variable' ),
		);
		return $product_data_tabs;
	}

	public function woocommerce_product_panels_price_matrix(){
		global $woocommerce, $post;

		$adding_to_cart     	= wc_get_product( $post->ID );
		$variation_attributes	= $adding_to_cart->get_attributes();
		$_pm_table_attr = get_post_meta($post->ID, '_pm_table_attr', true);
		$_pm_table_direction = get_post_meta($post->ID, '_pm_table_direction', true);
		$count_attr = get_post_meta($post->ID, '_pm_num', true);

		include(NBT_PRICEMATRIX_PATH .'tpl/admin/price-matrix-product.php');
	}

	public function pm_woocommerce_process_product_meta_variable($post_id){
		if(isset($_POST['_pm_type'])){
			update_post_meta( $post_id, '_pm_type', stripslashes( $_POST['_pm_type'] ) );
		}
		if(isset($_POST['_pm_vertical'])){
			update_post_meta( $post_id, '_pm_vertical', stripslashes( $_POST['_pm_vertical'] ) );
		}

		if(isset($_POST['_enable_price_matrix'])){
			update_post_meta( $post_id, '_enable_price_matrix', $_POST['_enable_price_matrix']);
			if(is_admin()){
				$this->remove_variations($post_id);
			}
		}else {
			update_post_meta( $post_id, '_enable_price_matrix', false);
		}

	}

	public function price_matrix_scripts_method($hooks){
		$screen = get_current_screen();
		
		if( $screen->post_type == 'product' && $hooks == 'post.php' || $screen->post_type == 'product' && $hooks == 'post-new.php') {
			wp_enqueue_style( 'price-matrix-context.standalone', NBT_PRICEMATRIX_URL . 'assets/css/context.standalone.css'  );
			wp_enqueue_style( 'price-matrix-magnific', NBT_PRICEMATRIX_URL . 'assets/css/magnific-popup.css'  );
			wp_enqueue_style( 'price-matrix-product', NBT_PRICEMATRIX_URL . 'assets/css/admin.css'  );
			wp_enqueue_script( 'price-matrix-context', NBT_PRICEMATRIX_URL . 'assets/js/context.js', null, null, true );
			wp_enqueue_script( 'price-matrix-magnific', NBT_PRICEMATRIX_URL . 'assets/js/jquery.magnific-popup.min.js', null, null, true );
			wp_enqueue_script( 'price-matrix-product', NBT_PRICEMATRIX_URL . 'assets/js/admin.js', null, null, true );
		}
	}
}
new NBT_PriceMatrix_Admin();