<?php
	add_action('admin_head', 'woie_admin_head_func');
	function woie_admin_head_func(){
		
		global $woie_url;
		
?>
	<style type="text/css">
	
		
		li.current a[href="admin.php?page=woie-settings"], 
		li.current a[href="admin.php?page=woie-settings"]:hover {
			background-color: #fff !important;
			color: #32373c !important;
			background-image:url("<?php echo $woie_url; ?>img/woo.png") !important;
			background-size: 18px !important;
			background-repeat: no-repeat !important;
			background-position: 4px 10px !important;
			text-indent: 14px !important;
			font-size: 12px !important;
		}
				
		li.current a[href="admin.php?page=woie-settings"]:hover {
			background-color: #EFEFEF !important;
			color: #1B1B1B !important;
		}
		
		@media only screen and (max-device-width: 480px) {
			
			
		}			
		
		/* ipad */
		@media only screen 
		and (min-device-width : 768px) 
		and (max-device-width : 1024px)  {
		}
		
		@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {

		}
		@supports (-ms-accelerator:true) {
		  /* IE Edge 12+ CSS styles go here */ 
		}				
	</style>
    
<?php        
	}


	if(!function_exists('sanitize_woie_data')){
		function sanitize_woie_data( $input ) {
			if(is_array($input)){		
				$new_input = array();	
				foreach ( $input as $key => $val ) {
					$new_input[ $key ] = (is_array($val)?sanitize_woie_data($val):sanitize_text_field( $val ));
				}			
			}else{
				$new_input = sanitize_text_field($input);			
				if(stripos($new_input, '@') && is_email($new_input)){
					$new_input = sanitize_email($new_input);
				}
				if(stripos($new_input, 'http') || wp_http_validate_url($new_input)){
					$new_input = sanitize_url($new_input);
				}			
			}	
			return $new_input;
		}	
	}
	
	
	function woie_admin_enqueue_script()
	{
		global $woie_pro, $woie_options, $woie_settings_url, $wpdb, $woie_filter_meta_keys;
		
		$current_screen = get_current_screen();
		
		$is_orders_list = ($current_screen->post_type=='shop_order');
		$is_edit_order = ($is_orders_list && isset($_GET['post']) && isset($_GET['action']) && is_numeric($_GET['post']) && $_GET['action']=='edit');
		
		$is_woie_settings = (isset($_GET['page']) && $_GET['page'] == 'woie-settings');
		
		$custom_meta_vals_arr = array();
		
		if($is_orders_list ){
			
			
		
			$custom_meta_keys = $woie_filter_meta_keys;
			
			
			
			if(!empty($custom_meta_keys)){
				
				foreach($custom_meta_keys as $custom_meta_key){
				
					$custom_meta_vals_query = 'SELECT DISTINCT(meta_value) FROM '.$wpdb->postmeta.' WHERE meta_key="'.$custom_meta_key.'" AND meta_value!="" ORDER BY meta_value';
					
					//pree($custom_meta_vals_query);
					
					$custom_meta_vals = $wpdb->get_results($custom_meta_vals_query);
					
					//pree($custom_meta_vals);
					
					if(!empty($custom_meta_vals)){
						foreach($custom_meta_vals as $custom_meta_val){
					
							$count_meta_val_query = 'SELECT COUNT(post_id) AS total FROM '.$wpdb->postmeta.' WHERE meta_key="'.$custom_meta_key.'" AND meta_value="'.$custom_meta_val->meta_value.'"';			
							//pree($count_meta_val_query);//exit;	
							$count_meta_val = $wpdb->get_row($count_meta_val_query);
							
							$count = 0;
							
							if(!empty($count_meta_val)){
								$count = $count_meta_val->total;
							}
							
							//pree($count_meta_val);
					
							$custom_meta_vals_arr[$custom_meta_key][] = array('label' => $custom_meta_val->meta_value, 'count' => $count);
						}
					}
				
				}
			}
			//pree($custom_meta_vals_arr);
				
		}
		
		if ($is_woie_settings) {
			
			
				
			wp_enqueue_script('woie_boostrap', plugin_dir_url(dirname(__FILE__)) . 'js/bootstrap.min.js', array('jquery'));
			wp_enqueue_style('woie-boostrap', plugins_url('css/bootstrap.min.css', dirname(__FILE__)));
			wp_enqueue_script('woie_slim', plugin_dir_url(dirname(__FILE__)) . 'js/slimselect.js', array('jquery'));
			wp_enqueue_style('woie-slim', plugins_url('css/slimselect.css', dirname(__FILE__)));
	
			wp_enqueue_style('woie-fontawesome', plugins_url('css/fontawesome.min.css', dirname(__FILE__)));
	
			wp_enqueue_media();
	
			

			wp_enqueue_script('woie-jquery-form-min', plugin_dir_url(dirname(__FILE__)) . 'js/jquery.form.min.js?', array('jquery'), time());
			
			wp_enqueue_script('woie', plugin_dir_url(dirname(__FILE__)) . 'js/fontawesome.min.js', array('jquery'), time());

			if($woie_pro){
				wp_enqueue_script('woie_pro_scripts', plugin_dir_url(dirname(__FILE__)) . 'pro/woie-admin.js', array('jquery'), time());
			}
			
		}
		
		if($is_woie_settings || $is_orders_list || $is_edit_order){
			
			wp_enqueue_style('woie-admin', plugins_url('css/admin-styles.css', dirname(__FILE__)), array(), date('Ymdhi'));
			
			
			wp_enqueue_script('woie_admin_scripts', plugin_dir_url(dirname(__FILE__)) . 'js/admin-scripts.js', array('jquery'), time());
			
			$_woie_settings_obj = get_option('_woie_settings_obj', array());
			$_woie_settings_obj = (is_array($_woie_settings_obj)?$_woie_settings_obj:array());
			$export_buttons = ((isset($_woie_settings_obj['args']) && isset($_woie_settings_obj['args']['export_btn_display']))?$_woie_settings_obj['args']['export_btn_display']:array());
			
			//pree($custom_meta_vals_arr);
			
			wp_localize_script(
				'woie_admin_scripts',
				'woie_object',
				array(
					'current_url' => home_url( add_query_arg( NULL, NULL ) ),
                    'this_url' => $woie_settings_url,
                    'is_pro' => $woie_pro,
                    'woie_tab' => (isset($_GET['t'])?sanitize_woie_data($_GET['t']):'0'),
					'ajax_url' => admin_url('admin-ajax.php'),
					'url' => $woie_settings_url,
					'comma_str' =>  __('Enter comma separated ids...', 'woo-ie'),
					'include_id_str' =>  __('Selective Items to Export', 'woo-ie'),
					'post_type_str' =>  __('Select post types', 'woo-ie'),
					'post_status_str' =>  __('Select post statuses', 'woo-ie'),
					'nothing_str' =>  __('Please select a file or insert string to proceed.', 'woo-ie'),
					'txt_file_str' =>  __("Only .txt file is allowed.", 'woo-ie'),
					'nonce' => wp_create_nonce('woie_update_options_nonce'),
                    'empty_settings' => empty($woie_options),
					'_woie_settings_obj' => $_woie_settings_obj,
					'is_orders_list' => ($is_orders_list && !$is_edit_order),
					'is_edit_order' => ($is_orders_list && $is_edit_order),
					'order_id' => ($is_edit_order?sanitize_woie_data($_GET['post']):0),
					'export_buttons' => array(
							'button_display' => $export_buttons, 
							'action_url' => admin_url().'?woie_export_orders', 
							'button_text_single' => __('Export Order', 'woo-ie'), 
							'button_text_multiple' => __('Export Orders', 'woo-ie'), 
							'button_title' => __('Click here to export orders', 'woo-ie'),
							
					),
					'custom_meta_vals_arr' => $custom_meta_vals_arr,
				)
			);
		}
	}
	
	
	add_action('admin_enqueue_scripts', 'woie_admin_enqueue_script');
	
	add_action('wp_enqueue_scripts', 'woie_wp_enqueue_script');
	
	function woie_wp_enqueue_script()
	{
		global $post, $woie_pro, $woie_url, $woie_options;


	}
	
	if (is_admin()) {
		add_action('admin_menu', 'woie_menu');
	}
	function woie_menu()
	{
		global $woie_data, $woie_pro;
	
		$title = str_replace('For WooCommerce', 'WC', $woie_data['Name']);
		add_submenu_page('woocommerce', $title, $title, 'manage_options', 'woie-settings', 'woie_settings' );		
	}
	function woie_settings()
	{
		global $woie_premium_link, $woie_pro, $woie_url;
		$woie_options = get_option('woie_options', array());
		$woie_options = is_array($woie_options)?$woie_options:array();
		include_once('woie_settings.php');
	}


    add_action('wp_ajax_woie_update_option', 'woie_update_option');

    if(!function_exists('woie_update_option')){
        function woie_update_option(){



            if(isset($_POST['woie_update_option_nonce'])){

                $nonce = $_POST['woie_update_option_nonce'];

                $return = array(

                    
                );

                if ( ! wp_verify_nonce( $nonce, 'woie_update_options_nonce' ) )
                    die (__("Nonce did not verify.", 'woo-ie'));

                if(isset($_POST['woie_options'])){

                    $woie_options = isset($_POST['woie_options']) ? sanitize_woie_data($_POST['woie_options']) : array();


                    $update = update_option('woie_options', $woie_options);
                }




                echo  json_encode($return);

            }

            wp_die();

        }
    }

    function woie_plugin_links($links) {
        global $woie_premium_link, $woie_pro, $woie_settings_url;

        $settings_link = '<a href="'.$woie_settings_url.'">'.__('Settings', 'woo-ie').'</a>';

        if($woie_pro){
            array_unshift($links, $settings_link);
        }else{

            $woie_premium_link = '<a href="'.esc_url($woie_premium_link).'" title="'.__('Go Premium', 'woo-ie').'" target="_blank">'.__('Go Premium', 'woo-ie').'</a>';
            array_unshift($links, $settings_link, $woie_premium_link);

        }


        return $links;
    }
	
	add_action('wp_ajax_woie_filters_save', 'woie_filters_save_callback');
	
	function woie_filters_save_callback(){
		
		
		$ret = array();
		
		if(!empty($_POST) && is_admin()){
		
			global $woie_options;
			
			if(!isset($_POST['woie_nonce']) || !wp_verify_nonce($_POST['woie_nonce'], 'woie_update_options_nonce')){
			
				_e('Sorry, your nonce did not verify.', 'woo-ie');
				exit;
				
			} else {
				
				$filter_meta_keys = sanitize_woie_data($_POST['filter_meta_keys']);
				
				update_option('woie_filter_meta_keys', $filter_meta_keys);
				
				$ret['msg'] = true;
				
			}
			
		}
		
		echo wp_json_encode($ret);
		
		exit;
	}
	
	add_action('wp_ajax_woie_export_orders', 'woie_export_orders');
	
	function woie_export_orders(){
		
		
		
		if(!empty($_POST) && is_admin()){
		
			global $woie_options, $woie_dir, $woie_orders_data_file, $woie_orders_data_file_url;
			
			
				
			if (isset($_POST['woie_export_data']) && $_POST['woie_export_data']=='true') {
				if (
						!isset($_POST['woie_update_option_nonce'])
					|| 
						!wp_verify_nonce($_POST['woie_update_option_nonce'], 'woie_update_options_nonce')
				) {
			
					_e('Sorry, your nonce did not verify.', 'woo-ie');
					exit;
				} else {
			
					if(!class_exists('XLSXWriter')){
						$xlsxwriter = $woie_dir . '/inc/xlsxwriter.class.php';//exit;
						if(file_exists($xlsxwriter)){
							//echo 
							include_once($xlsxwriter);
							//exit;
						}
					}else{
						//echo 'XLSXWriter';exit;
					}
					
					if(class_exists('XLSXWriter')){
						
						if(class_exists('ZipArchive')){
							
							
							
							$_woie_settings_obj = get_option('_woie_settings_obj', array());
							$_woie_settings_obj = (is_array($_woie_settings_obj)?$_woie_settings_obj:array());
							
							
							
							$shop_order_args = array(
								'numberposts' => -1,
								'post_type' => 'shop_order',
								'orderby' => 'date',
								'order' => 'DESC',
								'suppress_filters' => true,
							);
							
							if(isset($_woie_settings_obj['args']['post_status'])){
								$shop_order_args['post_status'] = $_woie_settings_obj['args']['post_status'];
							}
							
							
							$export_column = array_map( 'sanitize_text_field', $_woie_settings_obj['args']['export_order_field']);
							$woie_orders = (isset($_POST['woie_orders'])?sanitize_woie_data($_POST['woie_orders']):array());
							
							if(is_array($woie_orders) && !empty($woie_orders)){
								$shop_order_args['include'] = $woie_orders;
							}
							
							//pree($export_column);
							//pree($shop_order_args);
							$orders = get_posts($shop_order_args);
							
							$ret = array();
							
							if (!empty($orders)) {									
									
									foreach($orders as $post){
										
										$order = wc_get_order($post->ID);

										$order_data = $order->get_data();									
										$order_ret = array();
										foreach($order_data as $order_key=>$order_val){
											
											if(in_array($order_key, $export_column)){
												$order_ret[$order_key] = $order_val;
											}
											
										}		
										
										foreach ($export_column as $index => $column) {
											$column_value = (array_key_exists($column, $order_ret)?$order_ret[$column]:'');
											$column_value_updated = apply_filters('woie_export_order_data', $column_value, $post->ID, $order, $column);
											 
											switch($column){
												case 'line_items':
													
												break;
											}
											 
											if(is_array($column_value_updated)){
												
												$column_value = array();
												//pree($column);
												//pree($column_value_updated);
												foreach($column_value_updated as $column_value_label=>$column_value_str){
													
													
													if(!is_object($column_value_str)){
														if(is_array($column_value_str)){								
															foreach($column_value_str as $column_value_str_key=>$column_value_str_val){		
																$column_value[] = $column_value_str_key.': '.$column_value_str_val;
															}
															
															$column_value[] = str_repeat(PHP_EOL, 1);
														}else{
															$column_value[] = $column_value_label.': '.$column_value_str;
														}
													}
													
												}
												//pree($column_value);
												
												switch($column){
													case 'line_items':
														//pree($column_value);exit;
													break;
												}
												
												$ret[$post->ID][$column] = implode(PHP_EOL, $column_value);
												
											}else{
												
												$ret[$post->ID][$column] = $column_value_updated;
												
											}
											
											
										}//exit;
										
										
									}	
							}
							//pree($ret);exit;
							
							$orders_data = array_filter($ret);
							
							//pree($orders_data);exit;
							
							//exit;
							//pree($upload_dir['basedir'].'/'.$filename);exit;
							
							ob_clean();
							$filename = basename($woie_orders_data_file);
							header('Content-disposition: attachment; filename="'.XLSXWriter::sanitize_filename($filename).'"');
							header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
							header('Content-Transfer-Encoding: binary');
							header('Cache-Control: must-revalidate');
							header('Pragma: public');
					
							$header = array();
							if(!empty($export_column)){
								$export_column = array_flip($export_column);
								foreach ($export_column as $key => $value) {
									
									$column_label_index = array_search($key, $_woie_settings_obj['args']['export_order_field']);
									$key_title = ($column_label_index!='' && isset($_woie_settings_obj['args']['export_order_field_label'][$column_label_index])?$_woie_settings_obj['args']['export_order_field_label'][$column_label_index]:$key);
									
									$header[$key_title] = 'string';
								}
							}
							
							
							
							$writer = new XLSXWriter();
							$writer->writeSheetHeader('Sheet1', $header);
							
							//pree($billing_address);exit;
							//$billing_address = array_unique($billing_address);
							
							foreach($orders_data as $row){
								$writer->writeSheetRow('Sheet1', $row);
								sleep(0.25);
							}
							
							//pree($billing_address);exit;
							
							//$writer->writeToStdOut();//
							
							$writer->writeToFile($woie_orders_data_file);
							
							echo json_encode(array('msg'=>__('Successfully exported', 'woo-ie').', '.'<a href="'.$woie_orders_data_file_url.'" target="_blank">'.__('click here', 'woo-ie').'</a>'.' '.__('to download the file.', 'woo-ie')));
							
						}else{
							_e('PHP Class ZipArchive is missing. Please check it with your hosting server settings.', 'woo-ie');
						}
							
						
						exit;
					}else{
						//echo '>P<';exit;
					}
				}
			}			
		
	
			
	
		}
	}
	
	//add_action('init', 'woie_export_orders');
	
	
	
	
	add_filter( 'woie_export_order_data_columns', 'woie_export_order_data_columns_callback', 8, 1 );


	function woie_export_order_data_columns_callback($arr=array()){	
	
		$arr = (is_array($arr)?$arr:array());
		
		$extra_columns = array('currency_symbol');
		
		$arr = array_merge($arr, $extra_columns);
	
		$arr = array_unique($arr);
	
		return $arr;
	
	}
	
	add_filter( 'woie_export_order_data', 'woie_export_order_data_callback', 8, 4 );


	function woie_export_order_data_callback($value='', $order_id=0, $order_obj=array(), $column=''){
		//pree($column);
		//pree($value->date);
		if(!is_object($order_obj)){
			
			$order_obj = wc_get_order($order_id);	
		}
		
		
		
	
		switch($column){
			case 'date_created':
				$get_date_created = $order_obj->get_date_created();				
				if(is_object($get_date_created)){
					$value = $get_date_created->date(get_option('date_format').' '.get_option('time_format'));
				}
			break;
			case 'date_modified':
				$get_date_modified = $order_obj->get_date_modified();
				if(is_object($get_date_modified)){
					$value = $get_date_modified->date(get_option('date_format').' '.get_option('time_format'));
				}
			break;
			case 'date_completed':			
				$get_date_completed = $order_obj->get_date_completed();
				if(is_object($get_date_completed)){
					$value = $get_date_completed->date(get_option('date_format').' '.get_option('time_format'));
				}
			break;
			case 'date_paid':
				$get_date_paid = $order_obj->get_date_paid();
				if(is_object($get_date_paid)){
					$value = $get_date_paid->date(get_option('date_format').' '.get_option('time_format'));
				}
			break;
			case 'currency_symbol':
				$value = get_woocommerce_currency_symbol();
			break;
			case 'line_items':
			
				$items_arr = array();
				
				foreach($order_obj->get_items() as $item_key=>$item_data){
					$items_arr[$item_key]['product_name'] = $item_data->get_name();
					$items_arr[$item_key]['product_quantity'] = $item_data->get_quantity();
				}
				
				$value = $items_arr;
				
				//pree($value);exit;
				
			break;
			
		}
		
		return $value;
	}