<?php 
namespace WCQT\classes\admin;

use Automattic\WooCommerce\Utilities\OrderUtil;


if (!class_exists('WP_List_Table')) {
      require_once(ABSPATH . 'wp-admin/includes/class-wp-list-table.php');
}

class QuotesTablePage extends \WP_List_Table
{
	var $wcqt_quotes_table_page = "woocommerce-quote_page_woocommerce-quote-quotes-table-page";
	var $table_data;
	var $orders_cache = array();
	
	function __construct()
	{
		$this->wcqt_quotes_table_page;
		add_action("load-".$this->wcqt_quotes_table_page, array($this, "screen_options"));
		
		parent::__construct( array(
            'singular'  => 'quote',     
            'plural'    => 'quotes',    
            'ajax'      => false        
        ) );
        
	}
	protected function get_views() 
	{ 
		global $wcqt_order_model;
		$statuses = $wcqt_order_model->get_quote_statuses();
		$status_links = array("all"  => __("<a href='#'>All</a>",'woocommerce-quote'));
		foreach($statuses as $status_slug => $status_data)
		{
			$status_links[$status_slug] = sprintf("<a href='#'>%s</a>", $status_data["label"]);
		}
		return $status_links;
	}


	function extra_tablenav( $which ) 
	{
		global $wpdb, $testiURL, $tablename, $tablet,$wcqt_order_model;
		$statuses = $wcqt_order_model->get_quote_statuses();
		if ( $which == "top" || $which == "bottom" )
		{
			?>
				<div class="alignleft actions bulkactions">
				<select name="status-filter" class="wcqt-filter-status">
                <option value=""><?php esc_html_e('All statuses', 'woocommerce-quote') ?></option>
				<?php foreach($statuses as $status_slug => $status_data): ?>
					<option value="<?php echo $status_slug; ?>" <?php selected(wcqt_get_value_if_set($_GET, 'status-filter',""), $status_slug); ?> ><?php echo $status_data["label"]; ?></option>
				<?php endforeach; ?>
				</select>
				</div>
			<?php
		}
	}
	function prepare_items()
    {
      
		$this->process_bulk_action();
        //data
        if ( isset($_POST['s']) ) 
		{
            $this->table_data = $this->get_table_data($_POST['s']);
        } 
		else 
		{
            $this->table_data = $this->get_table_data();
        }
		$columns = $this->get_columns();
        $hidden = $this->get_hidden_columns();
        $sortable = $this->get_sortable_columns();
        $primary  = 'name';
        $this->_column_headers = array($columns, $hidden, $sortable, $primary);

        usort($this->table_data, array(&$this, 'usort_reorder'));
        
		/* pagination */
        $per_page = $this->get_items_per_page('elements_per_page', 15);
        $current_page = $this->get_pagenum();
        $total_items = count($this->table_data);

        $this->table_data = array_slice($this->table_data, (($current_page - 1) * $per_page), $per_page);

        $this->set_pagination_args(array(
                'total_items' => $total_items, // total number of items
                'per_page'    => $per_page, // items to show on a page
                'total_pages' => ceil( $total_items / $per_page ) // use ceil to round up
        ));
		
        $this->items = $this->table_data;
    }
	
	function render_page()
	{
	  wp_enqueue_style('wcqt-quotes-table-page', WCQT_PLUGIN_PATH.'/css/admin/quotes-table-page.css');  
	  
	  wp_enqueue_script( 'wcqt-quotes-table-page', WCQT_PLUGIN_PATH.'/js/admin/quotes-table-page.js', array('jquery') );
		
	  echo '<div class="wrap"><h2>'.esc_html__('Quotes', 'woocommerce-quote').'</h2>';
	  //no need $this->views();
	  echo '<form method="post">';
	  // Prepare table
	  $this->prepare_items();
	  // Search form
	  $this->search_box('search', 'search_id');
	  // Display table
	  $this->display();
	  echo '</div></form>';
	}
	
	// add screen options
	function screen_options() 
	{
		
		global $table;
	 
		$screen = get_current_screen();
		// get out of here if we are not on our settings page
		if(!is_object($screen) || $screen->id != $this->wcqt_quotes_table_page)
			return;
	 
		$args = array(
			'label' => esc_html__('Elements per page', 'woocommerce-quote'),
			'default' => 15,
			'option' => 'elements_per_page'
		);
		add_screen_option( 'per_page', $args );

	}
	function get_bulk_actions()
    {
		global $wcqt_order_model;
		$actions = array();
		$statuses = $wcqt_order_model->get_quote_statuses();
		foreach($statuses as $slug => $status_data)
			$actions["mark_".$slug] = sprintf( esc_html__('Change status to %s', 'woocommerce-quote'),
												 $status_data['label']
												);
		$actions['move_to_trash'] = esc_html__('Delete', 'woocommerce-quote');
		return $actions;
    }    
	function process_bulk_action()
	{
		global $wcqt_order_model, $wcqt_order_model;
		$statuses = $wcqt_order_model->get_quote_statuses();
		$to_process = wcqt_get_value_if_set($_REQUEST, 'quote', array());
		
		wcqt_write_log($this->current_action());
		if( 'move_to_trash'=== $this->current_action() ) 
			foreach($to_process as $key => $order_id)
					{
						$order = isset($this->orders_cache[$order_id]) ? $this->orders_cache[$order_id] : wc_get_order($order_id) ;
						$this->orders_cache[$order_id] = $order;
						$order->delete(true);
						unset($this->orders_cache[$order_id]);
						unset($to_process[$key]);
					}
		
		foreach($statuses as $slug => $status_data)
			if( "mark_".$slug === $this->current_action() ) 
				foreach($to_process as $order_id)
				{
					$order = isset($this->orders_cache[$order_id]) ? $this->orders_cache[$order_id] : wc_get_order($order_id) ;
					$this->orders_cache[$order_id] = $order;
					$order->update_status($slug);
					//ToDo: to assign status
				}
	}
	private function get_table_data( $search = '') 
	{
        global $wpdb, $wcqt_order_model;

        $table = $wpdb->prefix . 'posts';
		$quote_statuses = $wcqt_order_model->get_statuses();
		//Filter via get 
		$status_filter = wcqt_get_value_if_set($_GET, 'status-filter',"");
		$quote_statuses = $status_filter ? array($status_filter) : $quote_statuses ;
		
		if( OrderUtil::custom_orders_table_usage_is_enabled() ) 
		{
			$data = array();
			if ( !empty($search) ) 
				{
					$orders = array();
					$result = wc_get_order($search);
					if($result)
						$orders[] = $result;
					
				}
			else
				{
					$orders = wc_get_orders( array(
							'status' => $quote_statuses,
						) );
						
						//wcqt_var_dump($data);
				}
				//For backward compability
				foreach($orders as $order)
				{
					$date = $order->get_date_created();
					$data[] = array(
									'ID' => $order->get_id(),
									'post_date' => $date->date("Y-m-d H:i:s"),
									'post_date_gmt' => $date->date("Y-m-d H:i:s"),
									'post_status'   => "wc-".$order->get_status()
								);
				}
		}
		
		else
		{
			if ( !empty($search) ) {
				$data =  $wpdb->get_results(
					"SELECT * from {$table} WHERE post_type = 'shop_order' AND ID Like '%{$search}%' OR post_date Like '%{$search}%' OR post_status Like '%{$search}%' AND post_status IN('".implode("','",$wcqt_order_model->get_statuses())."') ",
					ARRAY_A
				);
			} else {
				$data = $wpdb->get_results(
					"SELECT * from {$table} WHERE post_type = 'shop_order' AND post_status IN('".implode("','",$quote_statuses)."')",
					ARRAY_A
				);
			} 
		}
		return $data;
    }
	function column_cb($item)
	{
        return sprintf(
            '<input type="checkbox"  name="%1$s[]" value="%2$s" />', 
             $this->_args['singular'],  
             $item['ID']               
        );
    }
	function column_ID($item)
	{
		$order = isset($this->orders_cache[$item['ID']]) ? $this->orders_cache[$item['ID']] : wc_get_order($item['ID']) ;
		$this->orders_cache[$item['ID']] = $order;
		
		
		return !OrderUtil::custom_orders_table_usage_is_enabled()  ? sprintf(
				'<a href="%s" >#%s %s %s</a>', 
				 get_edit_post_link($item['ID']),  			
				 $order->get_order_number(),
				 $order->get_billing_first_name(),
				 $order->get_billing_last_name(),			 
			) : 
			sprintf(
				'<a href="%s" >#%s %s %s</a>', 
				 "?page=wc-orders&action=edit&id=".$item['ID'],  			
				 $order->get_order_number(),
				 $order->get_billing_first_name(),
				 $order->get_billing_last_name(),			 
			);
		
		
    }
	function column_status($item)
	{
		global  $wcqt_order_model;
		$stauses = $wcqt_order_model->get_quote_statuses();
		return sprintf(
            '<span class="wcqt-status-text wcqt-status-%s">%s</a>', 
             $item['post_status'],
			 $stauses[$item['post_status']]['label']
			 
        );
    }
	function column_total($item)
	{
		global  $wcqt_order_model;
		$order = isset($this->orders_cache[$item['ID']]) ? $this->orders_cache[$item['ID']] : wc_get_order($item['ID']) ;
		$this->orders_cache[$item['ID']] = $order;
		
		return $order->get_formatted_order_total();
    }
	function column_date($item)
	{
		global $wcqt_time_model;
        return $wcqt_time_model->get_date_time_according_wordpress_settings($item['post_date']);
    }
	function column_expire($item)
	{
		global $wcqt_order_model, $wcqt_time_model;
		
		$order = isset($this->orders_cache[$item['ID']]) ? $this->orders_cache[$item['ID']] : wc_get_order($item['ID']) ;
		$this->orders_cache[$item['ID']] = $order;
		
		$expiring_datetime = $wcqt_order_model->get_expiring_date($order);
		return $expiring_datetime['datetime'] ? $expiring_datetime['datetime'] : " - ";
    }
	
	function get_columns()
    {
        $columns = array(
                'cb'            => '<input type="checkbox" />',
				'ID'			=> 'ID',
				'date'	   		=> esc_html__('Date', 'woocommerce-quote'),
				'expire'	   	=> esc_html__('Expiring date', 'woocommerce-quote'),
				'status'	   	=> esc_html__('Status', 'woocommerce-quote'),
				'total'	   		=> esc_html__('Total', 'woocommerce-quote'),
        );
        return $columns;
    }
	function column_default($item, $column_name)
    {
          switch ($column_name) {
                case 'ID':
                default:
                    return $item[$column_name];
          }
    }
	
	protected function get_sortable_columns()
	{
		  $sortable_columns = array(
				'ID'   => array('ID', false), //second parameter: how data is sort clicking the first time. False -> desc, true -> asc
				'date'   => array('post_date', false),
		  );
		   return $sortable_columns;
	}
	protected function get_hidden_columns()
	{
		
		  return array();
	}
	// Sorting function
    function usort_reorder($a, $b)
    {
        // If no sort, default to user_login
        $orderby = (!empty($_GET['orderby'])) ? $_GET['orderby'] : 'ID';

        // If no order, default to asc
        $order = (!empty($_GET['order'])) ? $_GET['order'] : 'desc';

        // Determine sort order
        $result = strcmp($a[$orderby], $b[$orderby]);

        // Send final sort direction to usort
        return ($order === 'asc') ? $result : -$result;
    }
}
?>