<?php
if (!defined('ABSPATH')) exit();
if ( !class_exists('Indeed_List_Table')) require_once ULP_PATH . 'classes/Abstracts/Indeed_List_Table.class.php';
if (class_exists('ListOrders')) return;
class ListOrders extends Indeed_List_Table{
	protected $post_type = 'ulp_order';
	protected $label = 'Order';
	protected $label_plural = 'Orders';
  private $_order_meta_object = null;
	/**
	 * @param none
	 * @return string
	 */
	public function finalOutput(){
    require_once ULP_PATH . 'classes/Db/DbUlpOrdersMeta.class.php';
    $this->_order_meta_object = new DbUlpOrdersMeta();
		parent::prepare_items();
		parent::display();
	}
	/**
	 * @param none
	 * @return array
	 */
	public function get_columns(){
	  	$columns = array(
		  	'cb' => '<input type="checkbox" />',
		    'ID' => __('Order ID', 'ulp'),
				'code' => __('Code', 'ulp'),
		    'student' => __('Student', 'ulp'),
		    'course' => __('Course', 'ulp'),
		    'price' => __('Price', 'ulp'),
		    'source' => __('Source', 'ulp'),
		    'date' => __('Date', 'ulp'),
		    'status' => __('Status', 'ulp'),
	  	);
			if (get_option('ulp_invoices_enable')){
					$columns ['invoice'] = __('Invoice', 'ulp');
			}
	  	$columns = apply_filters("manage_" . $this->post_type . "_posts_columns", $columns);
	  	$columns = apply_filters("manage_edit-" . $this->post_type . "_columns",  $columns);
		return $columns;
	}
	/**
	 * @param object
	 * @param string
	 * @return string
	 */
	public function column_default($post, $column_name){
	  	switch ($column_name){
	    	case 'ID':
					return $post->ID;
					break;
				case 'code':
					$code = $this->_order_meta_object->get($post->ID, 'code');
					if (empty($code)){
							echo '-';
							return;
					}
					echo $code;
					break;
				case 'date':
					return ulp_print_date_like_wp($post->post_date);
					break;
				case 'course':
          $course_id = $this->_order_meta_object->get($post->ID, 'course_id');
          if ($course_id){
              $course_name = DbUlp::getPostTitleByPostId($course_id);
              if ($course_name){
                  echo $course_name;
              }
          } else {
              echo '<span style="color: red">' . __("The course no longer exists. (ID=", 'ulp') . $post->ID . ')' . '</span>';
          }
					break;
        case 'student':
          $uid = $this->_order_meta_object->get($post->ID, 'user_id');
          if ($uid){
							$avatar = DbUlp::getAuthorImage($uid);
							$username = DbUlp::getUsernameByUID($uid);
							return '<img src="' . $avatar . '" class="" />'.'<a href="' . admin_url('user-edit.php?user_id=' . $uid) . '" target="_blank">' . $username . '</a>' ;
              return;
          }
          _e('Unknown student', 'ulp');
          break;
        case 'price':
          $course_id = $this->_order_meta_object->get($post->ID, 'course_id');
          if (get_post_meta($course_id, 'ulp_course_payment', true)){
							$price = $this->_order_meta_object->get($post->ID, 'amount');
							if ($price){
                  echo ulp_format_price($price);
              }
          }
          break;
        case 'source':
          $source = $this->_order_meta_object->getSource($post->ID);
          if ($source){
              echo ucfirst($source);
          }
          break;
        case 'status':
          $status = $post->post_status;
          switch ($status){
              case 'ulp_complete':
                _e('Completed', 'ulp');
                break;
              case 'ulp_fail':
                _e('Fail', 'ulp');
                break;
              case 'ulp_pending':
                _e('Pending', 'ulp');
                break;
          }
          break;
        case 'invoice':
					return '<i class="fa-ulp fa-invoice-preview-ulp ulp-pointer" onClick="ulpOpenInvoiceAdmin(' . $post->ID . ', ' . $post->post_author . ');"></i>';
          break;
	  	}
	  	do_action("manage_{$this->post_type}_posts_custom_column", $column_name, $post->ID);
	}
  public function column_ID($item) {
      $wpnonce = wp_create_nonce('ulp_nonce');
      $actions = array(
              'edit'      => "<a href='" . admin_url('post.php?post=' . $item->ID . '&action=edit') . "'>" . __("Edit", 'ulp') . "</a>",
              'delete'    => "<span class='js-ulp-do-delete-post ulp-delete-link' data-id='{$item->ID}'>". __("Delete", 'ulp') . "</span>",///"<a href='" . admin_url('admin.php?page=ultimate_learning_pro&tab=ulp_order&action=trash&id=' . $item->ID . '&_wpnonce=' . $wpnonce) . "'>" . __("Delete", 'ulp') . "</a>",
      );

			$actions = apply_filters('ulp_filter_custom_post_type_dashboard_action_links', $actions);
      return $item->ID . sprintf('%1$s %2$s', $item->post_content, $this->row_actions($actions) );
  }
	/**
	 * @param none
	 * @return array
	 */
	public function get_sortable_columns() {
	  $sortable_columns = array(
	    'title'  => array('post_title',false),
	    'date' => array('post_date', false),
	  );
	  return $sortable_columns;
	}
	protected function table_data($per_page=5, $page_number=1){
			global $wpdb;
			$q = "SELECT `ID`, `post_author`, `post_date`, `post_date_gmt`, `post_content`, `post_title`, `post_excerpt`, `post_status`, `comment_status`, `ping_status`, `post_password`, `post_name`, `to_ping`, `pinged`, `post_modified`, `post_modified_gmt`, `post_content_filtered`, `post_parent`, `guid`, `menu_order`, `post_type`, `post_mime_type`, `comment_count`
							FROM {$wpdb->posts} WHERE post_type='{$this->post_type}' AND post_status NOT IN ('trash', 'auto-draft') ";
			$q .= $this->extra_query_params;
			if (!empty($_REQUEST['orderby'])){
					$q .= ' ORDER BY ' . esc_sql( $_REQUEST['orderby'] );
					$q .= !empty( $_REQUEST['order'] ) ? ' ' . esc_sql( $_REQUEST['order'] ) : ' DESC';
			} else {
					$q .= " ORDER BY ID DESC";
			}
			$q .= " LIMIT $per_page";
			$q .= ' OFFSET ' . ( $page_number - 1 ) * $per_page;
			$data = $wpdb->get_results($q);
			return $data;
			//return indeed_convert_to_array($data);
	}
}
