<?php

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) exit;

// WP_List_Table is not loaded automatically in the plugins section
if( ! class_exists( 'WP_List_Table' ) ) {
    require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}


/*
 * Extent WP default list table for our custom members section
 *
 */
class DateBook_Members_List_Table extends WP_List_Table {

    /**
     * Members per page
     *
     * @access public
     * @var int
     */
    public $items_per_page;

    /**
     * Members table data
     *
     * @access public
     * @var array
     */
    public $data;

    /**
     * Members table views count
     *
     * @access public
     * @var array
     */
    public $views_count = array();

    /**
     * The total number of items
     *
     * @access private
     * @var int
     *
     */
    private $total_items;


    /*
     * Constructor function
     *
     */
    public function __construct() {

        parent::__construct( array(
            'singular'  => 'member',
            'plural'    => 'members',
            'ajax'      => false
        ));

        // Set items per page
        $items_per_page = get_user_meta( get_current_user_id(), 'datebook_members_per_page', true );

        if( empty( $items_per_page ) ) {

            $screen     = get_current_screen();
            $per_page   = $screen->get_option('per_page');
            $items_per_page = isset($per_page['default']) && $per_page['default'] > 0 ? $per_page['default'] : 100;

        }

        $this->items_per_page = $items_per_page;

        // Set data
        $this->set_table_data();

    }

    /*
     * Overwrites the parent class.
     * Define the columns for the members
     *
     * @return array
     *
     */
    public function get_columns() {

        $columns = array(
            'user_id'           => esc_html__( 'User ID', 'datebook' ),
            'username'          => esc_html__( 'Username', 'datebook' ),
            'email'             => esc_html__( 'E-mail', 'datebook' ),
            'subscriptions'     => esc_html__( 'Details', 'datebook' ),
			'status'            => esc_html__( 'Status', 'datebook' )
        );

        return apply_filters( 'datebook_members_list_table_columns', $columns );

    }


    /*
     * Overwrites the parent class.
     * Define which columns to hide
     *
     * @return array
     *
     */
    public function get_hidden_columns() {

        return array();

    }


    /*
     * Overwrites the parent class.
     * Define which columns are sortable
     *
     * @return array
     *
     */
	public function get_sortable_columns() {

		return array(
			'user_id'	=> array( 'user_id', false ),
			'username'	=> array( 'username', false ),
			'status'	=> array( 'status', false )
		);

	}


    /*
     * Returns the possible views for the members list table
     *
     */
    protected function get_views() {

        return apply_filters( 'datebook_members_list_table_get_views', array(
            'all'       => '<a href="' . remove_query_arg( array( 'datebook-view', 'paged' ) ) . '" ' . ( !isset( $_GET['datebook-view'] ) ? 'class="current"' : '' ) . '>All <span class="count">(' . ( isset( $this->views_count['all'] ) ? $this->views_count['all'] : '' ) . ')</span></a>',
            'active'    => '<a href="' . add_query_arg( array( 'datebook-view' => 'active', 'paged' => 1 ) ) . '" ' . ( isset( $_GET['datebook-view'] ) &&$_GET['datebook-view'] == 'active' ? 'class="current"' : '' ) . '>Active <span class="count">(' . ( isset( $this->views_count['active'] ) ? $this->views_count['active'] : '' ) . ')</span></a>',
            'expired'   => '<a href="' . add_query_arg( array( 'datebook-view' => 'expired', 'paged' => 1 ) ) . '" ' . ( isset( $_GET['datebook-view'] ) &&$_GET['datebook-view'] == 'expired' ? 'class="current"' : '' ) . '>Expired <span class="count">(' . ( isset( $this->views_count['expired'] ) ? $this->views_count['expired'] : '' ) . ')</span></a>',
            'pending'   => '<a href="' . add_query_arg( array( 'datebook-view' => 'pending', 'paged' => 1 ) ) . '" ' . ( isset( $_GET['datebook-view'] ) &&$_GET['datebook-view'] == 'pending' ? 'class="current"' : '' ) . '>Pending <span class="count">(' . ( isset( $this->views_count['pending'] ) ? $this->views_count['pending'] : '' ) . ')</span></a>',
			'canceled'   => '<a href="' . add_query_arg( array( 'datebook-view' => 'canceled', 'paged' => 1 ) ) . '" ' . ( isset( $_GET['datebook-view'] ) &&$_GET['datebook-view'] == 'canceled' ? 'class="current"' : '' ) . '>Pending <span class="count">(' . ( isset( $this->views_count['canceled'] ) ? $this->views_count['canceled'] : '' ) . ')</span></a>'
        ));

    }




    /*
     * Sets the table data
     *
     * @return array
     *
     */
    public function set_table_data() {

        $data = array();
        $args = array();

        $selected_view = ( isset( $_GET['datebook-view'] ) ? sanitize_text_field( $_GET['datebook-view'] ) : '' );
        $paged         = ( isset( $_GET['paged'] )    ? (int)$_GET['paged'] : 1 );


        /**
         * Set member arguments
         *
         */
        $args['number'] = $this->items_per_page;
        $args['offset'] = ( $paged - 1 ) * $this->items_per_page;
        $args['member_subscription_status'] = $selected_view;

        // Order by query
        if( ! empty( $_REQUEST['orderby'] ) && ! empty( $_REQUEST['order'] ) ) {

            if( $_REQUEST['orderby'] == 'user_id' )
                $args['orderby'] = 'ID';

            if( $_REQUEST['orderby'] == 'username' )
                $args['orderby'] = 'user_login';
            
            $args['order']   = sanitize_text_field( $_REQUEST['order'] );

        }

        // Set subscription plan if it exists
        if( ! empty( $_GET['datebook-filter-subscription-plan'] ) ) {
            $args['subscription_plan_id'] = (int)$_GET['datebook-filter-subscription-plan'];
        }


        // Get the members
        $members = datebook_get_members( $args );
		
        // Set views count array to 0, we use this to display the count
        // next to the views links (all, active, expired, etc)
        $views = $this->get_views();

        foreach( $views as $view_slug => $view_link) {

            $args['member_subscription_status'] = ( $view_slug != 'all' ? $view_slug : '' );

            $this->views_count[$view_slug] = datebook_get_members( $args, true );

        }

        // Get the current view to filter results
        $selected_view = ( isset( $_GET['datebook-view'] ) ? sanitize_text_field( $_GET['datebook-view'] ) : '' );

        foreach( $members as $key => $member ) {

            $member_subscriptions = datebook_get_member_subscriptions( array( 'user_id' => $member->user_id ) );

			if(isset($member->subscriptions[0]['status']) && ($member->subscriptions[0]['status'] == 'active' || $member->subscriptions[0]['status'] == 'completed')){
				$member_subscription_status = '<span style="padding: 1px 5px 3px; background: #08b908; color:white; border-radius: 3px">' . $member->subscriptions[0]['status'] . '</span>';
			} else if(isset($member->subscriptions[0]['status']) && $member->subscriptions[0]['status'] == 'expired'){
				$member_subscription_status = '<span style="padding: 1px 5px 3px; background: grey; color:white; border-radius: 3px">' . $member->subscriptions[0]['status'] . '</span>';
			} else if(isset($member->subscriptions[0]['status']) && $member->subscriptions[0]['status'] == 'pending'){
				$member_subscription_status = '<span style="padding: 1px 5px 3px; background: orange; color:white; border-radius: 3px">' . $member->subscriptions[0]['status'] . '</span>';
			} else if(isset($member->subscriptions[0]['status']) && $member->subscriptions[0]['status'] == 'canceled'){
				$member_subscription_status = '<span style="padding: 1px 5px 3px; background: grey; color:white; border-radius: 3px">' . $member->subscriptions[0]['status'] . '</span>';
			} else {
				$member_subscription_status = esc_html__( 'undefined', 'datebook' );
			}

            $data[] = array(
                'user_id'           => $member->user_id,
                'username'          => '<strong><a href="' . add_query_arg( array( 'subpage' => 'edit-member', 'member_id' => $member->user_id ) ) . '">' . esc_attr( $member->username ) . '</a></strong>',
                'email'             => $member->email,
                'subscriptions'     => $member_subscriptions,
				'status'            => $member_subscription_status,
            );

        }

        /**
         * Set all items
         *
         */
        $this->total_items = $this->views_count[ ( ! empty( $selected_view ) ? $selected_view : 'all' ) ];


        /**
         * Set table data
         *
         */
        $this->data = $data;

    }



    /**
     * Populates the items for the table
     *
     * @param array $item           - data for the current row
     *
     * @return string
     *
     */
    public function prepare_items() {

        $columns        = $this->get_columns();
        $hidden_columns = $this->get_hidden_columns();
        $sortable       = $this->get_sortable_columns();

        $this->_column_headers = array( $columns, $hidden_columns, $sortable );

        $this->set_pagination_args( array(
            'total_items' => $this->total_items,
            'per_page'    => $this->items_per_page
        ));

        $this->items = $this->data;

    }


    /*
     * Return data that will be displayed in each column
     *
     * @param array $item           - data for the current row
     * @param string $column_name   - name of the current column
     *
     * @return string
     *
     */
    public function column_default( $item, $column_name ) {

        return !empty( $item[ $column_name ] ) ? $item[ $column_name ] : '';

    }


    /*
     * Return data that will be displayed in the username column
     *
     * @param array $item   - row data
     *
     * @return string
     *
     */
    public function column_username( $item ) {

        $actions = array();

        // Add an edit user action for each member
        $actions['edit'] = '<a href="' . add_query_arg( array( 'subpage' => 'edit-member', 'member_id' => $item['user_id'] ) ) . '">' . esc_html__( 'View Details', 'datebook' ) . '</a>';

        // Return value saved for username and also the row actions
        return $item['username'] . $this->row_actions( $actions );

    }


    /**
     * Return data that will be displayed in the subscriptions column
     *
     * @param array $item   - row data
     *
     * @return string
     *
     */
    public function column_subscriptions( $item ) {

        $output = '';

        foreach( $item['subscriptions'] as $member_subscription ) {

			$output .= apply_filters( 'datebook_list_table_' . $this->_args['plural'] . '_show_status_dot', '<span class="datebook-status-dot ' . esc_attr( $member_subscription->status ) . '"></span>' );

			$output .= '<div class="datebook-bubble">';

			$output .= '<span class="alignleft"><strong>' . esc_html__( 'Start date', 'datebook' ) . '</strong></span><br>';
			$output .= '<span class="alignleft">' . date( get_option( 'date_format' ), strtotime( datebook_sanitize_date( $member_subscription->start_date ) ) ) . '</span><br>';

			$output .= '<span class="alignleft"><strong>' . esc_html__( 'Expiration date', 'datebook' ) . '</strong></span><br>';
			$output .= '<span class="alignleft">' . ( ! empty( $member_subscription->expiration_date ) ? date( get_option( 'date_format' ), strtotime( datebook_sanitize_date( $member_subscription->expiration_date ) ) ) : esc_html__( 'Unlimited', 'datebook' ) ) . '</span>';

			if( DateBook_Profile_Subscription::datebook_payment_gateways_support( DateBook_Profile_Subscription::datebook_get_active_payment_gateways(), 'recurring_payments' ) ){
				$output .= '<span class="alignleft"><strong>' . esc_html__( 'Auto-renewing', 'datebook' ) . '</strong></span><br>';
				$output .= '<span class="alignleft">' . ( $member_subscription->is_auto_renewing() ? esc_html__( 'Yes', 'datebook' ) : esc_html__( 'No', 'datebook' ) ) . '</span>';
			}

            $output .= '</div>';

        }

        return $output;

    }


    /*
     * Display if no items are found
     *
     */
    public function no_items() {

        echo esc_html__( 'No members found', 'datebook' );

    }

}



/*
 * Extent WP default list table for our custom members section
 *
 */
class DateBook_Member_Subscription_List_Table extends WP_List_Table {

    /**
     * Member
     *
     * @access public
     * @var int
     */
    public $member;

    /**
     * Subscription plan ids
     *
     * @access public
     * @var array
     */
    public $existing_subscription_plan_ids;


    /*
     * Constructor function
     *
     */
    public function __construct( $user_id ) {

        global $pagenow, $wp_importers, $hook_suffix, $plugin_page, $typenow, $taxnow;
        $page_hook = get_plugin_page_hook($plugin_page, $plugin_page);

        parent::__construct( array(
            'singular'  => 'member-subscription',
            'plural'    => 'member-subscriptions',
            'ajax'      => false,

            // Screen is a must!
            'screen'    => $page_hook
        ));

        $this->member = datebook_get_member($user_id);

    }


    /**
     * Overwrites the parent class.
     * Define the columns for the members
     *
     * @return array
     *
     */
    public function get_columns() {

        $columns = array(
            'subscription_plan' => esc_html__( 'Subscription Plan', 'datebook' ),
            'start_date'        => esc_html__( 'Start Date', 'datebook' ),
            'expiration_date'   => esc_html__( 'Expiration date', 'datebook' ),
            'status'   			=> esc_html__( 'Status', 'datebook' ),
            'auto_renewal'      => esc_html__( 'Auto-renewing', 'datebook' ),
        );

        if( ! DateBook_Profile_Subscription::datebook_payment_gateways_support( DateBook_Profile_Subscription::datebook_get_active_payment_gateways(), 'recurring_payments' ) )
            unset( $columns['auto_renewal'] );

        return $columns;

    }


    /**
     * Overwrites the parent class.
     * Define which columns to hide
     *
     * @return array
     *
     */
    public function get_hidden_columns() {

        return array();

    }


    /**
     * Overwrites the parent class.
     * Define which columns are sortable
     *
     * @return array
     *
     */
    public function get_sortable_columns() {

        return array();

    }


    /**
     * Method to add an entire row to the table
     * Replaces parent method
     *
     * @param array $item - The current row information
     *
     */
    public function single_row( $item ) {

        $row_classes = '';

        if( isset( $item['errors'] ) )
            $row_classes .= ' datebook-field-error';

        if( !$this->member->is_member() )
            $row_classes .= ' datebook-add-new edit-active';

        echo '<tr class="' . $row_classes . '">';
        $this->single_row_columns( $item );
        echo '</tr>';
    }



    /**
     * Returns the table data
     *
     * @return array
     *
     */
    public function get_table_data() {

        $data = array();

        if( !$this->member->is_member() )
            return $data;

        $item_count = 0;

        $member_subscriptions = datebook_get_member_subscriptions( array( 'user_id' => $this->member->user_id ) );

		// Get Subscription plans
		$get_subscription_plans = get_option('datebook_subscription_plans');

        foreach( $member_subscriptions as $member_subscription ) {

			if (is_array($get_subscription_plans)){

				foreach($get_subscription_plans as $key => $value){
					if (isset($value['subscription_id']) && $value['subscription_id'] == $member_subscription->subscription_plan_id) {
						$member_subscription_name = isset($value['name_' . DATEBOOK_WPLANG]) ? $value['name_' . DATEBOOK_WPLANG] : $value['name_en_US'];

					}
				}

			}

			$member_subscription_name = isset($member_subscription_name) ? $member_subscription_name : esc_html__( 'No title', 'datebook' );
			
			$member_subscription_status = $member_subscription->status == 'active' || $member_subscription->status == 'completed' ? '<span style="padding: 1px 5px 3px; background: #08b908; color:white; border-radius: 3px">' . $member_subscription->status . '</span>' : '<span style="padding: 1px 5px 3px; background: orange; color:white; border-radius: 3px">' . $member_subscription->status . '</span>';
			

            $data[] = array(
                'subscription_id'       => $member_subscription->id,
                'subscription_plan_id'  => $member_subscription->subscription_plan_id,
                'subscription_plan'     => $member_subscription_name,
                'start_date'            => datebook_sanitize_date( $member_subscription->start_date ),
                'expiration_date'       => datebook_sanitize_date( $member_subscription->expiration_date ),
				'status'			    => $member_subscription_status
            );

            $item_count++;
        }

        return $data;

    }


    /*
     * Populates the items for the table
     *
     */
    public function prepare_items() {

        $columns = $this->get_columns();
        $hidden_columns = $this->get_hidden_columns();
        $sortable = $this->get_sortable_columns();

        $data = $this->get_table_data();

        $this->_column_headers = array( $columns, $hidden_columns, $sortable );
        $this->items = $data;

    }


    /**
     * Return data that will be displayed in each column
     *
     * @param array $item           - data for the current row
     * @param string $column_name   - name of the current column
     *
     * @return string
     *
     */
    public function column_default( $item, $column_name ) {

        if( !isset( $item[ $column_name ] ) )
            return false;

        return $item[ $column_name ];

    }


    /**
     * Return data that will be displayed in the subscription plan column
     *
     * @param array $item           - data for the current row
     *
     * @return string
     *
     */
    public function column_subscription_plan( $item ) {

		if(!empty($item['subscription_plan'])){

			$actions = array();

	        // Add an edit user action for each member
    	    $actions['edit'] = '<a href="' . add_query_arg(array( 'subpage' => 'edit-subscription')) . '">' . esc_html__( 'Edit', 'datebook' ) . '</a>';

	        // Return value saved for username and also the row actions
    	    return $item['subscription_plan'] . $this->row_actions( $actions );

		} else {

			$output = '<span>' . sprintf( esc_html__( 'Not Found - ID: %s', 'datebook' ), $item['subscription_plan_id'] ) . '</span>';

			return $output;

		}
    }
}



/*
 * Extent WP default list table for our custom members section
 *
 */
class DateBook_Member_Payments_List_Table extends WP_List_Table {


    /*
     * Constructor function
     *
     */
    public function __construct() {

        global $pagenow, $wp_importers, $hook_suffix, $plugin_page, $typenow, $taxnow;
        $page_hook = get_plugin_page_hook($plugin_page, $plugin_page);

        parent::__construct( array(
            'singular'  => 'member-payment',
            'plural'    => 'member-payments',
            'ajax'      => false,

            // Screen is a must!
            'screen'    => $page_hook
        ));

    }


    /*
     * Overwrites the parent class.
     * Define the columns for the members
     *
     * @return array
     *
     */
    public function get_columns() {

        $columns = array(
            'subscription_plan' => esc_html__( 'Subscription', 'datebook' ),
            'amount'            => esc_html__( 'Amount', 'datebook' ),
            'date'              => esc_html__( 'Date', 'datebook' ),
            'status'   			=> esc_html__( 'Status', 'datebook' ),
            'actions'           => esc_html__( 'Actions', 'datebook' )
        );

        return $columns;

    }


    /*
     * Overwrites the parent class.
     * Define which columns to hide
     *
     * @return array
     *
     */
    public function get_hidden_columns() {

        return array();

    }


    /*
     * Overwrites the parent class.
     * Define which columns are sortable
     *
     * @return array
     *
     */
    public function get_sortable_columns() {

        return array();

    }


    /*
     * Returns the table data
     *
     * @return array
     *
     */
    public function get_table_data() {

        $data = array();

        $args = array(
            'user_id' => (int)trim($_REQUEST['member_id']),
            'number'   => 10
        );

		// Get all subscription plans
		$get_subscription_plans = get_option('datebook_subscription_plans');
		
		if (is_array($get_subscription_plans)){

			foreach($get_subscription_plans as $key => $value){

				if (isset($value['subscription_id'])) {
					
					$subscription_short_data[$value['subscription_id']] = $value['name_' . DATEBOOK_WPLANG];

				} 
			}
		}

        $payments = datebook_get_payments( $args );

        foreach( $payments as $payment ) {
			
			$payment_subscription_title = isset($subscription_short_data[$payment->subscription_id]) ? $subscription_short_data[$payment->subscription_id] : '-';
			
			$payment_status = $payment->status == 'completed' ? '<span style="padding: 1px 5px 3px; background: #08b908; color:white; border-radius: 3px">' . $payment->status . '</span>' : '<span style="padding: 1px 5px 3px; background: orange; color:white; border-radius: 3px">' . $payment->status . '</span>';

            $data[] = array(
                'subscription_plan' => $payment_subscription_title,
                'amount'            => datebook_get_currency_symbol( datebook_get_active_currency() ) . $payment->amount,
                'date'              => date_i18n( 'F d, Y H:i:s', strtotime( $payment->date ) + ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS ) ),
                'status'            => $payment_status,
                'actions'           => $payment->id
            );
        }

        return $data;

    }


    /*
     * Populates the items for the table
     *
     */
    public function prepare_items() {

        $columns = $this->get_columns();
        $hidden_columns = $this->get_hidden_columns();
        $sortable = $this->get_sortable_columns();

        $data = $this->get_table_data();

        $this->_column_headers = array( $columns, $hidden_columns, $sortable );
        $this->items = $data;

    }


    /*
     * Return data that will be displayed in each column
     *
     * @param array $item           - data for the current row
     * @param string $column_name   - name of the current column
     *
     * @return string
     *
     */
    public function column_default( $item, $column_name ) {

        if( !isset( $item[ $column_name ] ) )
            return false;

        return $item[ $column_name ];

    }


    /*
     * Return data that will be displayed in the actions column
     *
     * @param array $item   - data of the current row
     *
     * @return string
     *
     */
    public function column_actions( $item ) {

		return '<a href="' . add_query_arg( array( 'page' => 'datebook-options-members', 'subpage' => 'edit-subscription', 'subscription_id' => $item['actions'] ), admin_url( 'admin.php' ) ) . '">' . esc_html__( 'Edit', 'datebook' ) . '</a>';

    }


    /*
     * Display if no items are found
     *
     */
    public function no_items() {

        echo esc_html__( 'No payments found', 'datebook' );

    }

}












/**
 * Extends core DateBook_Submenu_Page base class to create and add custom functionality
 * for the members section in the admin section
 *
 */
class DateBook_Submenu_Page_Members extends DateBook_Submenu_Page {

    /**
     * Returns a custom message by the provided code
     *
     * @param int $code
     *
     * @return string
     *
     */
    protected function get_message_by_code( $code = 0 ) {

        $messages = array(
            1 => esc_html__( 'Something went wrong. Could not process your request.', 'datebook' ),
            2 => esc_html__( 'Member Subscription added successfully.', 'datebook' ),
            3 => esc_html__( 'Member Subscription updated successfully.', 'datebook' ),
            4 => esc_html__( 'Member Subscription deleted successfully.', 'datebook' )
        );

        return ( ! empty( $messages[$code] ) ? $messages[$code] : '' );

    }


    /**
     * Method that validates general subscription data 
     *
     * @return bool
     *
     */
	static function validate_data($item) {

		$data = array();
		$messages = array();

		if(is_array($item)) {


			// Check to see if the username field is empty
			if (empty($item['user_id'])){

				$messages[] = esc_html__('Select a user', 'datebook');

			} else {

				$user_id = sanitize_text_field( $item['user_id'] );

				// Check to see if the username exists
    	        $user = get_user_by( 'id', $user_id );

	            if( !$user ){
					$messages[] = esc_html__( 'It seems this user does not exist.', 'datebook' );
				}
        
        	}

			// Check to see if we have a subscription id for the subscription we want to edit
		    if( empty( $_GET['subscription_id'] ) ){
				$messages[] = esc_html__( 'Something went wrong. Could not complete your request.', 'datebook' );
			}


			if( ! empty( $_GET['subscription_id'] ) ) {

	            $member_subscription = datebook_get_member_subscription( (int)$_GET['subscription_id'] );

				if( is_null( $member_subscription ) ){
					// Check to see if there's a subscription with the provided id
					$messages[] = esc_html__( 'Something went wrong. Could not complete your request.', 'datebook' );
				} elseif( $member_subscription->user_id != (int)$_POST['user_id'] ){
					// Check to see if the subscription's attached user_id is the same with the provided user_id
					$messages[] = esc_html__( 'Something went wrong. Could not complete your request.', 'datebook' );
				}

	        }
		
	        // Check to see if a subscription plan was selected
	        if( empty( $item['subscription_plan_id'] ) ){
				$messages[] = esc_html__( 'Select a subscription plan.', 'datebook' );
			}

	        // Check to see if a start date was selected
	        if( empty( $item['start_date'] ) ){
				$messages[] = esc_html__( 'Add a start date for the subscription.', 'datebook' );
			}


			// If expiration date is provided it should be bigger than the start date and also the trial date
	        /*if( ! empty( $item['expiration_date'] ) ) {

	            if( ! empty( $item['start_date'] ) && ( strtotime( $item['expiration_date'] ) < strtotime( $item['start_date'] ) ) ){
					$messages[] = esc_html__( 'The expiration date needs to be greater than the start date.', 'datebook' );
				}

	            if( ! empty( $item['trial_end'] ) && ( strtotime( $item['expiration_date'] ) < strtotime( $item['trial_end'] ) ) ){
					$messages[] = esc_html__( 'The expiration date needs to be greater than the trial end date', 'datebook' );
				}

	        }*/

	        // Check to see if a start date was selected
	        if( empty( $item['status'] ) ){
				$messages[] = esc_html__( 'Select a status of the subscription plan', 'datebook' );
			}

	        // Check to see if a start date was selected
	        if( empty( $item['payment_status'] ) ){
				$messages[] = esc_html__( 'Select a status of the payment', 'datebook' );
			}
			

			$data['form_fields'] = $item;

			if (is_array($data)) {

				$data['success'] = true;
				
			} else {

				$data['success'] = false;
				$data['error_message'] = esc_html__( 'Oops! Something went wrong.', 'datebook' );
	
			}

		} else {

			$data['success'] = false;
			$data['error_message'] = esc_html__( 'Oops! Something went wrong.', 'datebook' );

		}

		return $data;

    }


    /*
     * Method that processes data on members admin pages
     *
     */
	private static function process_data() {

        // These processes should be handled only by an admin
		if( ! current_user_can( 'manage_options' ) )
			return;

		$result_array = array();

        // Handle edit subscription
        if(!empty($_POST['subpage']) && $_POST['subpage'] == 'edit-subscription' && !empty($_POST['_wpnonce']) && wp_verify_nonce( $_POST['_wpnonce'], 'datebook_payment_nonce' ) ) {

            $item_data = self::validate_data( $_POST );

			if ($item_data['success'] === true) {

				$item = $item_data['form_fields'];

				// Get all subscription plans
				$get_subscription_plans = get_option('datebook_subscription_plans');

				if (is_array($get_subscription_plans)){

					$subscription_period_out = '0000-00-00 00:00:00';

					$activate_woocommerce_subscription = (of_get_option('activate_woocommerce_subscription') == '2' && function_exists('WC')) ? 1 : 0;
					if($activate_woocommerce_subscription == 1){
						
						$subscription_plan_id = $item['subscription_plan_id'];

						if(isset($get_subscription_plans[$subscription_plan_id]['wc_subscription_product'])){
							
							$plan_price_period = 0;

							$product = wc_get_product($get_subscription_plans[$subscription_plan_id]['wc_subscription_product']);
							$price_is_per = datebook_get_prop($product, '_wcaddon_price_is_per');
							$price_time_option = datebook_get_prop($product, '_wcaddon_price_time_option');
							$subscription_period_out = datebook_wc_get_price_per_string($price_is_per, $price_time_option);

						}

					} else {

						$item_subscription_plan_id = explode('-', $item['subscription_plan_id']);
						$subscription_plan_id = $item_subscription_plan_id[0];
						$plan_price_period = $item_subscription_plan_id[1];

						if(isset($get_subscription_plans[$subscription_plan_id]['register_period_number'][$plan_price_period]) && isset($get_subscription_plans[$subscription_plan_id]['register_period'][$plan_price_period])){
							$register_period_number = absint($get_subscription_plans[$subscription_plan_id]['register_period_number'][$plan_price_period]);
							$subscription_period_out = $register_period_number > 0 ? DateBook_Utilities::datebook_plural_text($register_period_number, $get_subscription_plans[$subscription_plan_id]['register_period'][$plan_price_period]) : '0000-00-00 00:00:00';
						}
					}

					$expiration_date = $register_period_number > 0 ? date('Y-m-d H:i:s', strtotime($item['start_date'] . " +" . $subscription_period_out)) : '0000-00-00 00:00:00';

				}

				// Update subscription and payment status
				if(isset($subscription_plan_id) && isset($plan_price_period) && isset($item['start_date']) && isset($expiration_date) && isset($item['status'])){

					// Get all member subscriptions
					$member_subscriptions = datebook_get_member_subscriptions( array( 'user_id' => $item['user_id'] ) );

					foreach( $member_subscriptions as $member_subscription ) {

						// Update subscription
						$updated = $member_subscription->update(array('subscription_plan_id' => $subscription_plan_id, 'plan_price_period' => $plan_price_period, 'start_date' => $item['start_date'], 'expiration_date' => $expiration_date, 'status' => $item['status']));

					}

					// Get the payment
					$payment = datebook_get_payment($item['subscription_id']);
					// Update payment status
					$payment->update(array('subscription_plan_id' => $subscription_plan_id, 'status' => $item['status']));

				}

				if(isset($updated) && $updated){

					$result_array['success'] = 1;
					$result_array['message'] = esc_html__('Subscription has been successfully saved', 'datebook');

				} else {

					$result_array['success'] = 0;
					$result_array['message'] = esc_html__('Oops! Something went wrong. Data has NOT been saved.', 'datebook');

				}

			} else {

				// if $item_data not true it contains error message(s)
				$result_array['success'] = 0;
				$result_array['message'] = $item_data['error_message'];

			}

		}
		

        // Handle delete subscription
		if( isset( $_GET['action'] ) && $_GET['action'] == 'delete' && isset( $_GET['subscription_id'] ) && !empty( $_GET['subscription_id'] ) && isset( $_GET['_wpnonce'] ) && !empty( $_GET['_wpnonce'] ) && wp_verify_nonce( $_GET['_wpnonce'], 'datebook_delete_subscription_nonce' ) ) {

			$member_subscription = datebook_get_member_subscription( (int)$_GET['subscription_id'] );

			if( is_null( $member_subscription ) ) return;

			$member_id = $member_subscription->user_id;
			$deleted   = $member_subscription->remove();

			if( $deleted ) {

				$member_subscriptions = datebook_get_member_subscriptions( array( 'user_id' => $member_id ) );
				
				if( ! empty( $member_subscriptions ) ){
					$result_array['success'] = 1;
					$result_array['message'] = esc_html__('Subscription has not been deleted', 'datebook');
				} else {
					$result_array['success'] = 0;
					$result_array['message'] = esc_html__('Subscription has been deleted', 'datebook');
				}

			}
		}

		return $result_array;

	}


	/**
	 * List page handler
	 *
	 * This function renders our custom table
	 * Notice how we display message about successfull deletion
	 * Actualy this is very easy, and you can add as many features
	 * as you want.
	 *
	 * Look into /wp-admin/includes/class-wp-*-list-table.php for examples
	 */
	static function datebook_page_handler() {

		self::output();

	}


    /*
     * Method to output content in the custom page
     *
     */
	public static function output() {

		global $wpdb;
		
		$result_message = self::process_data();

		// Display the edit member form
		if( isset( $_REQUEST['subpage'] ) && $_REQUEST['subpage'] == 'edit-member' && isset( $_REQUEST['member_id'] ) && !empty( $_REQUEST['member_id'] ) ) {

			// HTML output for the members admin edit member page
			
			$member = datebook_get_member( (int)trim( $_REQUEST['member_id'] ) );

			?>

			<div class="wrap">

				<h1><?php echo esc_html__( 'Member\'s Subscription Information', 'datebook' ); ?></h1>
				
				<hr class="wp-header-end">

				<div class="datebook-form-field-wrapper datebook-form-field-user-name">

					<h2><?php echo esc_html__( 'Username', 'datebook' ); ?>: <span class="readonly medium"><strong><?php echo esc_attr($member->username); ?></strong></span></h2>

				</div>

				<h3><?php echo esc_html__( 'Subscriptions the member has', 'datebook' ); ?></h3>

				<?php

	            $member_subscriptions_table = new DateBook_Member_Subscription_List_Table( $member->user_id );
	            $member_subscriptions_table->prepare_items();
       		    $member_subscriptions_table->display();

		        ?>

				<br />

				<h3><?php echo esc_html__( 'Orders the member made', 'datebook' ); ?></h3>

				<?php

				$member_payments_table = new DateBook_Member_Payments_List_Table();
				$member_payments_table->prepare_items();
				$member_payments_table->display();

				?>

			</div>

		<?php

		} elseif( isset( $_REQUEST['subpage'] ) && $_REQUEST['subpage'] == 'edit-subscription' && (isset($_REQUEST['subscription_id']) && !empty($_REQUEST['subscription_id']) || isset($_REQUEST['member_id']) && !empty($_REQUEST['member_id']))) {

			// View for adding / editting member subscriptions
			$subpage   = (!empty($_REQUEST['subpage']) ? (int)$_REQUEST['subpage'] : '');
			$payment_id = (!empty($_REQUEST['subscription_id']) ? (int)$_REQUEST['subscription_id'] : 0);

			$payment_subscription = datebook_get_payment($payment_id);

			if($payment_id > 0){

				// Display nothing if payment does not exist
				if(is_null($payment_subscription)) return;
				// Display nothing if this is not a valid payment			
				if(!$payment_subscription->is_valid()) return;

			}

			$member_id = ($payment_id > 0 ? $payment_subscription->user_id : (isset($_REQUEST['member_id']) && !empty($_REQUEST['member_id']) ? $_REQUEST['member_id'] : 0));

			$member_subscription = datebook_get_member($member_id);

			if(is_null($member_subscription)) return;

			$member_data = $member_subscription->to_array();

			$user_id = (int)$member_data['user_id'];

			$user = get_user_by('id', $user_id);

		?>

<div class="wrap">

	<h2><?php echo esc_html__( 'Edit Member Subscription', 'datebook' ); ?></h2>
	
	<hr class="wp-header-end">

	<?php

	if(is_array($result_message) && isset($result_message['success'])){
		if($result_message['success'] == 1){

			echo '<div id="message" class="updated notice"><p>' . $result_message['message'] . '</p></div>';

		} else if($result_message['success'] == 0){

			echo '<div id="message" class="updated notice"><p>' . $result_message['message'] . '</p></div>';

		}
	}

	$member_subscription_id = isset($member_data['subscriptions'][0]['id']) && !empty($member_data['subscriptions'][0]['id']) ? $member_data['subscriptions'][0]['id'] : 0;

	?>

	<form class="datebook-form" method="POST">

		<input type="hidden" name="subscription_id" value="<?php echo absint($member_subscription_id); ?>" />
		<input type="hidden" name="user_id" value="<?php echo esc_attr( $user_id ); ?>" />
		<input type="hidden" name="subpage" value="edit-subscription" />

		<?php wp_nonce_field( 'datebook_payment_nonce' ); ?>

		<div id="poststuff">
			<div id="datebook-dashboard-widgets-wrap">
				<div id="post-body" class="metabox-holder columns-2">
					
					<!-- Right Sidebar -->
					<div id="postbox-container-1" class="postbox-container">
						
						<!-- Update Subscription Meta-box -->
						<div id="side-sortables" class="meta-box-sortables ui-sortable">
							<div id="datebook-subscription-update" class="postbox">
								
								<!-- Meta-box Title -->
								<h3 class="hndle"><?php echo esc_html__( 'Update Subscription', 'datebook' ); ?></h3>
								
								<!-- Actions -->
								<div class="submitbox">
									<div id="major-publishing-actions">
										
										<!-- Delete subscription -->
										<div id="delete-action">
											<a onClick="return confirm('<?php echo esc_html__( 'Do you want to delete this subscription?', 'datebook' ); ?>')" href="<?php echo wp_nonce_url( add_query_arg( array( 'subscription_id' => $member_subscription_id, 'action' => 'delete' ), admin_url( 'admin.php?page=datebook-options-members' ) ), 'datebook_delete_subscription_nonce' ) ?>" class="submitdelete deletion"><?php echo esc_html__( 'Delete Subscription', 'datebook' ); ?></a>
										</div>
										
										<!-- Update Subscription -->
										<input type="submit" class="button button-primary right" value="<?php echo esc_html__( 'Save Subscription', 'datebook' ); ?>"/>

										<div class="clear"></div>

									</div>
								</div>
								<!-- End of Actions -->
								
							</div>
						</div>
					</div>
					<!-- End of Right Sidebar --> 
					
					<!-- Main Content -->
					<div id="postbox-container-2" class="postbox-container">
						
						<!-- Member/User Data -->
						<div id="normal-sortables" class="meta-box-sortables ui-sortable">
							<div id="datebook-member-details" class="postbox">

								<h3 class="hndle"> <span><?php echo esc_html__( 'Member', 'datebook' ); ?></span> </h3>

								<div class="inside">

									<table cellspacing="2" cellpadding="5" style="width: 100%;" class="form-table">
										<tbody>
											
											<!-- Member -->
											<tr class="form-field">
												<th valign="top" scope="row">

													<label for="datebook-subscription-plan-id" class="datebook-meta-box-field-label">
														<?php echo esc_html__( 'Name', 'datebook' ); ?>
													</label>

												</th>
												<td>

													 <strong><?php echo esc_attr($user->display_name); ?></strong> (<?php echo sanitize_email($user->user_email); ?>)
												</td>
												<td>
												
												<a href="<?php echo add_query_arg( array( 'page' => 'datebook-options-members', 'subpage' => 'edit-member', 'member_id' => (int)$user_id ), admin_url( 'admin.php' ) ); ?>"><?php echo esc_html__( 'View all subscriptions', 'datebook' ); ?></a>
												
												</td>
											</tr>

											<tr class="form-field">
												<th valign="top" scope="row">

													<label for="datebook-subscription-plan-id" class="datebook-meta-box-field-label">
														<?php echo esc_html__( 'Username', 'datebook' ); ?>
													</label>

												</th>

												<td><strong><?php echo esc_html($member_data['username']); ?></strong></td>
												
											</tr>
											
											<tr class="form-field">
												<th valign="top" scope="row">

													<label for="datebook-subscription-plan-id" class="datebook-meta-box-field-label">
														<?php echo esc_html__( 'Profile', 'datebook' ); ?> (ID: <?php echo absint($member_data['subscriptions'][0]['payment_profile_id']); ?>)
													</label>

												</th>
												<td colspan="2">

												<a href="<?php echo esc_url(get_permalink($member_data['subscriptions'][0]['payment_profile_id'])); ?>" target="_blank"><?php echo esc_url(get_permalink($member_data['subscriptions'][0]['payment_profile_id'])); ?></a>
												
												</td>
												
											</tr>
										</tbody>
									</table>

								</div>
							</div>
						</div>
						
						<!-- Member Subscription Details Meta-box -->
						<div id="normal-sortables" class="meta-box-sortables ui-sortable">
							<div id="datebook-member-subscription-details" class="postbox">

								<h3 class="hndle"> <span><?php echo esc_html__( 'Subscription Details', 'datebook' ); ?></span> </h3>

								<div class="inside">
									<table cellspacing="2" cellpadding="5" style="width: 100%;" class="form-table">
										<thead>

											<tr class="form-field">
												<th valign="top" scope="row">

												</th>
												<th><?php echo esc_html__( 'Current', 'datebook' ); ?></th>
												<th><?php echo esc_html__( 'New', 'datebook' ); ?></th>
											</tr>
										</thead>
										
										<tbody>

											<!-- Subscription plan -->
											<tr class="form-field">
												<th valign="top" scope="row">

													<label for="datebook-subscription-plan-id" class="datebook-meta-box-field-label">
														<?php echo esc_html__( 'Subscription plan', 'datebook' ); ?>
													</label>

												</th>
												<td>

													<?php 

													// Get all subscription plans
													$get_subscription_plans = get_option('datebook_subscription_plans');
													
													if (is_array($get_subscription_plans)){
														foreach($get_subscription_plans as $key => $value){
															if (isset($value['subscription_id'])) {
																
																if(!empty($member_data['subscriptions'][0]['subscription_plan_id']) && $member_data['subscriptions'][0]['subscription_plan_id'] != $value['subscription_id']) continue;
																
																$subscription_short_data[$value['subscription_id']] = $value['name_' . DATEBOOK_WPLANG];

																echo esc_attr($subscription_short_data[$value['subscription_id']]);
															}
														}
													}

											        ?>

												</td>
												<td>

													<select id="datebook-subscription-plan-id" name="subscription_plan_id" class="datebook-subscription-field" required>
													<?php 

													if (is_array($get_subscription_plans)){

														$activate_woocommerce_subscription = (of_get_option('activate_woocommerce_subscription') == '2' && function_exists('WC')) ? 1 : 0;
														
														foreach($get_subscription_plans as $key => $value){
															if (isset($value['subscription_id'])) {
																
																if($activate_woocommerce_subscription == 0){
																	$disabled = 'disabled="disabled"';
																	$selected = '';
																} else {
																	$disabled = '';
																	$selected = selected( $value['subscription_id'], (!empty($payment_subscription->subscription_id) ? (int)$payment_subscription->subscription_id : 0 ), false );
																}

																$subscription_short_data[$value['subscription_id']] = $value['name_' . DATEBOOK_WPLANG];

																echo '<option value="' . esc_attr($value['subscription_id']) . '"' . $selected . ' ' . $disabled . '>' . $subscription_short_data[$value['subscription_id']] . '</option>';

																if($activate_woocommerce_subscription == 0){
																	foreach($value['price'] as $key => $price){

																		$value_price = DateBook_Profile_Subscription::datebook_format_money($price);
																		$subscription_period_out = DateBook_Utilities::datebook_plural_text($value['register_period_number'][$key], $value['register_period'][$key]);


																		if($payment_subscription->subscription_id == $value['subscription_id'] && $payment_subscription->plan_price_period == $key){
																			$selected = 'selected';
																		} else {
																			$selected = '';
																		}

																		echo '<option value="' . esc_attr($value['subscription_id'] . '-' . $key) . '"' . esc_attr($selected) . '>&#8212; ' . esc_attr($value_price). ' / ' . esc_attr($subscription_period_out) . '</option>';

																	}
																}

															}
														}
													}

											        ?>

													</select>

												</td>
											</tr>
											

											<!-- Start Date -->
											<tr class="form-field">
												<th valign="top" scope="row">

													<label for="datebook-subscription-start-date" class="datebook-meta-box-field-label">
														<?php echo esc_html__( 'Start Date', 'datebook' ); ?>
													</label>

												</th>
												<td><?php echo (!empty( $member_data['subscriptions'][0]['start_date'] ) ? esc_attr( datebook_sanitize_date( $member_data['subscriptions'][0]['start_date'] ) ) : ''); ?></td>

												<td>
												
													<input id="datebook-subscription-start-date" type="date" name="start_date" class="datepicker datebook-subscription-field" value="<?php echo (!empty($payment_subscription->start_date) ? esc_attr(datebook_sanitize_date($payment_subscription->start_date)) : ''); ?>" required />
												</td>
												
											</tr>
											
											<!-- Expiration Date -->
											<tr class="form-field">
												<th valign="top" scope="row">
													<label for="datebook-subscription-expiration-date" class="datebook-meta-box-field-label">
														<?php echo esc_html__( 'Expiration Date', 'datebook' ); ?>
													</label>
												</th>
												<td valign="top"><?php echo (!empty($member_data['subscriptions'][0]['expiration_date']) && $member_data['subscriptions'][0]['expiration_date'] == '0000-00-00 00:00:00' ? esc_html__( 'Lifetime', 'datebook' ) : esc_attr( datebook_sanitize_date( $member_data['subscriptions'][0]['expiration_date']))); ?></td>

												<td>
													<?php /*?><input id="datebook-subscription-expiration-date" type="date" name="expiration_date" class="datepicker datebook-subscription-field" value="<?php echo (!empty($payment_subscription->expiration_date) ? esc_attr( datebook_sanitize_date($payment_subscription->expiration_date) ) : '' ); ?>" />
													<p class="description"><?php echo esc_html__( 'If the expiration date is not set then it will be set as Unlimited', 'datebook' ); ?></p><?php */?>
												</td>

											</tr>
											
											<!-- Status -->
											<tr class="form-field">
												<th valign="top" scope="row">
													<label for="datebook-subscription-status" class="datebook-meta-box-field-label">
														<?php echo esc_html__( 'Status', 'datebook' ); ?>
													</label>
												</th>
												<td>

													<?php
										        	foreach( datebook_get_member_subscription_statuses() as $member_status_slug => $member_status_name ) {
														
														if(!empty($member_data['subscriptions'][0]['status']) && $member_data['subscriptions'][0]['status'] != $member_status_slug) continue;
														
											            echo esc_attr($member_status_name);
											        }
							    				    ?>

												</td>

												<td>
													<select id="datebook-subscription-status" name="status" class="datebook-subscription-field" required>
														<?php
											        	foreach( datebook_get_member_subscription_statuses() as $member_status_slug => $member_status_name ) {
												            echo '<option value="' . esc_attr( $member_status_slug ) . '"' . selected( $member_status_slug, $member_data['subscriptions'][0]['status'] , false ) . '>' . $member_status_name . '</option>';
												        }
								    				    ?>
													</select>
												</td>

											</tr>
											
											<!-- Trial End -->
											<?php if( DateBook_Profile_Subscription::datebook_payment_gateways_support( DateBook_Profile_Subscription::datebook_get_payment_gateways( true ), 'subscription_free_trial' ) ): ?>

											<tr class="form-field">
												<th valign="top" scope="row">

													<label for="datebook-subscription-trial-end" class="datebook-meta-box-field-label">
														<?php echo esc_html__( 'Trial End', 'datebook' ); ?>
													</label>

												</th>
												<td>

													<input id="datebook-subscription-trial-end" type="text" name="trial_end" class="datepicker datebook-subscription-field" value="<?php echo ( ! empty( $member_data['trial_end'] ) ? esc_attr( datebook_sanitize_date( $member_data['trial_end'] ) ) : '' ); ?>" />

												</td>
											</tr>

											<?php endif; ?>

										</tbody>
									</table>
								</div>
							</div>
						</div>

						<?php if($payment_id > 0){ ?>
						
						<!-- Member Subscription Details Meta-box -->
						<div id="normal-sortables" class="meta-box-sortables ui-sortable">
							<div id="datebook-member-subscription-details" class="postbox">

								<h3 class="hndle"><?php printf( esc_html__( 'Payment #%s', 'datebook' ), $payment_id ); ?></h3>

								<div class="inside">
									<table cellspacing="2" cellpadding="5" style="width: 100%;" class="form-table">
										<tbody>
											
											<!-- Payment Status -->
											<tr>
												<th valign="top" scope="row">

												<label for="datebook-payment-status" class="datebook-form-field-label"><?php echo esc_html__( 'Status', 'datebook' ); ?></label>

												</th>
												
												<td>
												
												<select id="datebook-payment-status" name="payment_status" class="medium">
												
												<?php
												
												$statuses = datebook_get_payment_statuses();
												
												foreach( $statuses as $status_slug => $status_name ) {
													echo '<option ' . selected( $payment_subscription->status, $status_slug, false ) . ' value="' . esc_attr( $status_slug ) . '">' . esc_html( $status_name ) . '</option>';
												}
												
												?>

												</select>
												
												</td>
											</tr>

											<!-- Payment Discount Code -->
											<?php if( !empty( $payment_subscription->discount_code ) ) { ?>
												
											<tr>
												<th valign="top" scope="row">
												
												<label for="datebook-payment-discount" class="datebook-form-field-label"><?php echo esc_html__( 'Discount Code', 'datebook' ); ?></label>
												
												</th>

												<td><span class="readonly medium"><strong><?php echo esc_html( $payment_subscription->discount_code ); ?></strong></span></td>
												
											</tr>

										<?php } ?>

											<tr>
												<th valign="top" scope="row">
												
												<label for="datebook-payment-date" class="datebook-form-field-label"><?php echo esc_html__( 'Date', 'datebook' ); ?></label>
												
												</th>
												
												<td><input type="text" id="datebook-payment-date" name="datebook-payment-date" class="datepicker medium" value="<?php echo esc_attr( date( 'Y-m-d H:i:s', strtotime( $payment_subscription->date ) + ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS ) ) ); ?>" /></td>
												
											</tr>

											<!-- Payment Type -->
											<tr>
												<th valign="top" scope="row">

												<label for="datebook-payment-type" class="datebook-form-field-label"><?php echo esc_html__( 'Type', 'datebook' ); ?></label>

												</th>
												
												<td>
												
												<select id="datebook-payment-type" name="datebook-payment-type" class="widefat">
												
												<?php
												
												$types = datebook_get_payment_types();
												
												foreach( $types as $type_slug => $type_name ) {
													echo '<option ' . selected( $payment_subscription->type, $type_slug, false ) . ' value="' . esc_attr( $type_slug ) . '">' . esc_html( $type_name ) . '</option>';
												}
												
												?>

												</select>
												
												</td>
												
											</tr>
											
											<!-- Payment Transaction ID -->
											<tr>
												<th valign="top" scope="row">

												<label for="datebook-payment-transaction-id" class="datebook-form-field-label"><?php echo esc_html__( 'Transaction ID', 'datebook' ); ?></label>

												</th>
												
												<td>
												
												<input type="text" id="datebook-payment-transaction-id" name="datebook-payment-transaction-id" class="widefat" value="<?php echo ( ! empty( $payment_subscription->transaction_id ) ? esc_attr( $payment_subscription->transaction_id ) : '' ); ?>" /> 
												
												<?php if( empty( $payment_subscription->transaction_id ) && $payment_subscription->payment_gateway != 'bank' ): ?>
												
												<p class="description"><?php echo esc_html__( 'The Transaction ID will be provided by the payment gateway when the payment is registered within their system.', 'datebook' ); ?></p>
												
												<?php endif; ?>
												
												</td>
											</tr>

											<!-- Payment IP Address -->
											<tr>
												<th valign="top" scope="row">

												<label class="datebook-form-field-label"><?php echo esc_html__( 'IP Address', 'datebook' ); ?></label>

												</th>
												
												<td><strong><?php echo ( !empty( $payment_subscription->ip_address ) ? esc_html( $payment_subscription->ip_address ) : '-' ); ?></strong></td>
											</tr>
											
											
											
										</tbody>
									</table>
										
								</div>
							</div>
						</div>
						
						<!-- Member Subscription Billing Schedule Meta-box -->
						<?php if( DateBook_Profile_Subscription::datebook_payment_gateways_support( DateBook_Profile_Subscription::datebook_get_payment_gateways( true ), 'change_subscription_payment_method_admin' ) ) { ?>

						<div id="normal-sortables" class="meta-box-sortables ui-sortable">
							<div id="datebook-member-subscriptions-billing-schedule" class="postbox">

								<h3 class="hndle"> <span><?php echo esc_html__( 'Subscription Billing Schedule', 'datebook' ); ?></span> </h3>

								<div class="inside">

									<?php if(!empty($member_data['subscriptions'][0]['payment_profile_id'])){ ?>

									<div class="datebook-meta-box-field-wrapper">

										<label class="datebook-meta-box-field-label">
											<?php echo esc_html__( 'Payment Gateway Subscription', 'datebook' ); ?>
										</label>

										<p class="description"><?php echo esc_html__( 'The subscription payment schedule is handled by the payment gateway.', 'datebook' ); ?></p>

										<?php do_action( 'datebook_meta_box_field_payment_profile_id', $member_data ); ?>

									</div>

									<?php } else { ?>
									
									<!-- Recurring Duration and Duration Unit -->
									<div class="datebook-meta-box-field-wrapper">

										<label for="datebook-subscription-billing-duration" class="datebook-meta-box-field-label">
											<?php echo esc_html__( 'Recurring Once Every', 'datebook' ); ?>
										</label>

										<input type="text" id="datebook-subscription-billing-duration" name="billing_duration" value="<?php echo ( ! empty( $member_data['billing_duration'] ) ? $member_data['billing_duration'] : '' ); ?>" />

										<select id="datebook-subscription-plan-duration-unit" name="billing_duration_unit">
											<option value=""><?php echo esc_html__( 'Choose...', 'datebook' ); ?></option>
											<option value="day"   <?php selected( 'day', ( ! empty( $member_data['billing_duration_unit'] ) ? $member_data['billing_duration_unit'] : '' ), true ); ?>><?php echo esc_html__( 'Day(s)', 'datebook' ); ?></option>
											<option value="week"  <?php selected( 'week', ( ! empty( $member_data['billing_duration_unit'] ) ? $member_data['billing_duration_unit'] : '' ), true ); ?>><?php echo esc_html__( 'Week(s)', 'datebook' ); ?></option>
											<option value="month" <?php selected( 'month', ( ! empty( $member_data['billing_duration_unit'] ) ? $member_data['billing_duration_unit'] : '' ), true ); ?>><?php echo esc_html__( 'Month(s)', 'datebook' ); ?></option>
											<option value="year"  <?php selected( 'year', ( ! empty( $member_data['billing_duration_unit'] ) ? $member_data['billing_duration_unit'] : '' ), true ); ?>><?php echo esc_html__( 'Year(s)', 'datebook' ); ?></option>
										</select>

									</div>
									
									<!-- Billing Next Payment -->
									<div class="datebook-meta-box-field-wrapper">

										<label for="datebook-subscription-billing-next-payment" class="datebook-meta-box-field-label">
											<?php echo esc_html__( 'Next Payment', 'datebook' ); ?>
										</label>

										<input id="datebook-subscription-billing-next-payment" type="text" name="billing_next_payment" class="datepicker datebook-subscription-field" value="<?php echo ( ! empty( $member_data['billing_next_payment'] ) ? esc_attr( datebook_sanitize_date( $member_data['billing_next_payment'] ) ) : '' ); ?>" />

									</div>
									
									<!-- Payment gateway -->
									<?php if( DateBook_Profile_Subscription::datebook_payment_gateways_support( DateBook_Profile_Subscription::datebook_get_payment_gateways( true ), 'change_subscription_payment_method_admin' ) ) { ?>

									<?php 

									$payment_gateways = DateBook_Profile_Subscription::datebook_get_payment_gateways(); 

									foreach( $payment_gateways as $payment_gateway_slug => $payment_gateway_details ) {

										$payment_gateway = DateBook_Profile_Subscription::datebook_get_payment_gateway( $payment_gateway_slug );

										if( ! $payment_gateway->supports( 'change_subscription_payment_method_admin' ) )
											unset( $payment_gateways[$payment_gateway_slug] );
										}
										?>

									<div class="datebook-meta-box-field-wrapper">

										<label for="datebook-subscription-payment-gateway" class="datebook-meta-box-field-label">
											<?php echo esc_html__( 'Payment Gateway', 'datebook' ); ?>
										</label>

										<select id="datebook-subscription-payment-gateway" name="payment_gateway">

											<?php

											foreach( $payment_gateways as $payment_gateway_slug => $payment_gateway_details ) {

												echo '<option value="' . $payment_gateway_slug . '" ' . selected( $payment_gateway_slug, ( ! empty( $member_data['payment_gateway'] ) ? $member_data['payment_gateway'] : '' ), true ) . '>' . $payment_gateway_details['display_name_admin'] . '</option>';

											}

											?>

										</select>

									</div>

									<?php } ?>

								<?php } ?>

								</div>
							</div>
						</div>

						<?php } ?>
						
						<?php } ?>

					</div>
					<!-- End Main Content -->
					
				</div>
			</div>
		</div>

		

	</form>

</div>

		<?php

		} else {
			
			$table_name = strtolower($wpdb->prefix) . 'datebook_member_subscriptions';
			$check_datebook_member_subscriptions = $wpdb->get_var($wpdb->prepare("show tables like %s", $table_name));

			if ($check_datebook_member_subscriptions != $table_name) {
				
			?>

				<div class="wrap">

					<h1 class="wp-heading-inline"><?php esc_html_e('Database Table is not created yet!', 'datebook')?></h1>

					<hr class="wp-header-end">

					<div id="message" class="below-h1">

						<p><?php esc_html_e('Member Subscriptions (MySQL) table is not created yet.', 'datebook')?></p>

						<p><?php esc_html_e('Please, go to DateBook -> Theme Installer. Click on the 1. Install button to install all countries and cities.', 'datebook')?></p>

					</div>
				</div>

		<?php 

		} else {

			// Display a list with all the members. HTML output for the members admin page
			$menu = Options_Framework_Admin::menu_settings();

			$menu_members_slug = ( isset( $menu['menu_members_slug'] ) ) ? $menu['menu_members_slug'] : '';

		?>

		<div class="wrap">

			<h1 class="wp-heading-inline"><?php esc_html_e('Members', 'datebook')?></h1>

			<a class="page-title-action" href="<?php echo get_admin_url(get_current_blog_id(), 'admin.php?page='.esc_attr($menu_members_slug));?>"><?php esc_html_e('Back to Members', 'datebook')?></a>
			
			<hr class="wp-header-end">

			<?php

			if(is_array($result_message) && isset($result_message['success'])){
				if($result_message['success'] == 1){
					echo '<div id="message" class="updated notice"><p>' . $result_message['message'] . '</p></div>';
				} else if($result_message['success'] == 0){
					echo '<div id="message" class="updated notice"><p>' . $result_message['message'] . '</p></div>';
				}
			}

			?>

			<form method="get">

				<input type="hidden" name="page" value="datebook-options-members" />

				<?php

		        $members_list_table = new DateBook_Members_List_Table();
        		$members_list_table->prepare_items();
		        $members_list_table->views();
        		$members_list_table->display();

			    ?>

			</form>

		</div>

		<?php

			}
		}
    }


	/*
     * Method that adds Screen Options to Members page
     *
     */
	public function add_screen_options() {

          $args = array(
                'label' => 'Members per page',
                'default' => 100,
                'option' => 'datebook_members_per_page'
            );

		add_screen_option( 'per_page', $args );

	}

}