<?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 payments section
 *
 */
class DateBook_Payments_List_Table extends WP_List_Table {

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

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

    /**
     * Payments 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'  => 'payment',
            'plural'    => 'payments',
            'ajax'      => false
        ));

        // Set items per page
        $items_per_page = get_user_meta( get_current_user_id(), 'datebook_payments_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;

		// Process delete, edit functions
		self::process_data();


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

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

        $columns = array(
            'id'             => esc_html__( 'ID', 'datebook' ),
            'username'       => esc_html__( 'User', 'datebook' ),
            'subscription'   => esc_html__( 'Subscription', 'datebook' ),
            'amount'         => esc_html__( 'Amount', 'datebook' ),
            'date'           => esc_html__( 'Date / Time', 'datebook' ),
            'type'           => esc_html__( 'Type', 'datebook' ),
            'transaction_id' => esc_html__( 'Transaction ID', 'datebook' ),
            'status'         => esc_html__( 'Status', 'datebook' ),
        );

        return apply_filters( 'datebook_payments_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(
			'id'	=> array( '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_payments_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>'
        ));

    }


	private static function general_admin_notice(){
		echo esc_html__( 'Payment successfully deleted.', 'datebook' );
	}


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

		// Verify correct nonce
		if(!isset($_REQUEST['_wpnonce']) || !wp_verify_nonce($_REQUEST['_wpnonce'], 'datebook_payment_nonce'))
			return;

		// Get current actions
		$action = !empty($_REQUEST['datebook-action']) ? $_REQUEST['datebook-action'] : '';

		if(empty($action))
			return;


		// Deleting a payment
		if($action == 'delete_payment'){

			// Get payment id
			$payment_id = ( !empty( $_REQUEST['payment_id'] ) ? (int)$_REQUEST['payment_id'] : 0 );

			// Do nothing if there's no payment to work with
			if($payment_id == 0)
				return;

			$payment = datebook_get_payment($payment_id);

			if($payment->remove()){
				//$this->add_admin_notice( esc_html__( 'Payment successfully deleted.', 'datebook' ), 'updated' );
				//add_action( 'admin_notices', array( __CLASS__, 'general_admin_notice') );
			}

		}


        // Saving / editing a payment
		if($action == 'edit_payment'){

			// Get payment id
			$payment_id = (!empty($_REQUEST['payment_id']) ? (int)$_REQUEST['payment_id'] : 0);

			// Do nothing if there's no payment to work with
            if( $payment_id == 0 )
                return;

            // Get payment and extract the object/payment vars with their value
            $payment = datebook_get_payment( $payment_id );
            $payment_vars = get_object_vars( $payment );

            // Pass through each payment var and see if the value provided by the admin is different
            foreach( $payment_vars as $payment_var => $payment_var_val ) {

                // Get the value from the form field
                $post_field_value = isset( $_POST['datebook-payment-' . str_replace('_', '-', $payment_var) ] ) ? sanitize_text_field( $_POST['datebook-payment-' . str_replace('_', '-', $payment_var) ] ) : '';

                // If we're handling the date value take into account the time zone difference
                // In the db we want to have universal time, not local time
                if( $payment_var == 'date' )
                    $post_field_value = date( 'Y-m-d H:i:s', strtotime( $post_field_value ) - ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS ) );

                // If the form value exists and differs from the one saved in the payment
                // replace it, if not simply unset the value from the object vars array
				if($post_field_value !== '' && $post_field_value != $payment_var_val){
					$payment_vars[$payment_var] = $post_field_value;
				} else {
					unset($payment_vars[$payment_var]);
				}
			}

            // Subscription_id needs to be subscription_plan_id
            // This is not very consistent and should be modified
            if( !empty( $payment_vars['subscription_id'] ) ) {
                $payment_vars['subscription_plan_id'] = $payment_vars['subscription_id'];
                unset( $payment_vars['subscription_id'] );
            }

            // Update payment
            if( empty( $payment_vars ) )
                $updated = true;
            else
                $updated = $payment->update( $payment_vars );

            if( $updated )
                $this->add_admin_notice( esc_html__( 'Payment successfully updated.', 'datebook' ), 'updated' );

        }

    }


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

        $data = array();
        $args = array();
		$subscription_short_data = 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'] == '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 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']] = array_key_exists('name_' . DATEBOOK_WPLANG, $value) ? $value['name_' . DATEBOOK_WPLANG] : NULL;

				} 
			}
		}
		

        /**
         * Get payments
         *
         */
        $payments = datebook_get_payments( $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'] ) : '' );


        /**
         * Get payment gateways data
         *
         */
        $payment_gateways = DateBook_Profile_Subscription::datebook_get_payment_gateways();


        $args = array();


        /**
         * Set data array
         *
         */
		foreach( $payments as $payment ) {

            if( !empty($selected_view) && $payment->status != $selected_view )
                continue;

            // Get user data
            $user = get_user_by( 'id', $payment->user_id );

            if( $user )
                $username = $user->data->user_login;
            else
                $username = esc_html__( 'User no longer exists', 'datebook' );

            // Get payment gateway data
            if( ! empty( $payment_gateways[$payment->payment_gateway]['display_name_admin'] ) )
                $payment_gateway_name = $payment_gateways[$payment->payment_gateway]['display_name_admin'];
            else
                $payment_gateway_name = '';
            
			$payment_subscription_title = isset($subscription_short_data[$payment->subscription_id]) ? $subscription_short_data[$payment->subscription_id] : '-';

			if($payment->status == 'completed'){
				$payment_status = '<span style="padding: 1px 5px 3px; background: #08b908; color:white; border-radius: 3px">' . $payment->status . '</span>';
			} else if($payment->status == 'pending'){
				$payment_status = '<span style="padding: 1px 5px 3px; background: orange; color:white; border-radius: 3px">' . $payment->status . '</span>';
			} else {
				$payment_status = $payment->status;
			}


            $data[] = apply_filters( 'datebook_payments_list_table_entry_data', array(
                'id'              => $payment->id,
                'username'        => $username,
                'subscription'    => $payment_subscription_title,
                'amount'          => $payment->amount,
                'date'            => ucfirst( date_i18n( 'F d, Y H:i:s', strtotime( $payment->date ) + ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS ) ) ),
                'type'            => datebook_get_payment_type_name( $payment->type ),
                'payment_gateway' => $payment_gateway_name,
                'transaction_id'  => $payment->transaction_id,
                'status'          => $payment_status
            ), $payment );
        }

        /**
         * 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   - data of the current row
     *
     * @return string
     *
     */
    public function column_username( $item ) {

        // Add row actions
        $actions = array();

        // Edit payment row action
		$actions['edit'] = '<a href="' . add_query_arg( array( 'page' => 'datebook-options-members', 'subpage' => 'edit-subscription', 'subscription_id' => $item['id'] ) ) . '">' . esc_html__( 'Edit', 'datebook' ) . '</a>';
		
        // Delete row action
		$actions['delete'] = '<a onclick="return confirm( \'' . esc_html__( "Are you sure you want to delete this Payment?", 'datebook' ) . ' \' )" href="' . wp_nonce_url( add_query_arg( array( 'datebook-action' => 'delete_payment', 'payment_id' => $item['id'] ) ), 'datebook_payment_nonce' ) . '">' . esc_html__( 'Delete', 'datebook' ) . '</a>';

        /**
         * Filter the actions for a payment
         *
         * @param array $actions
         * @param array $item
         *
         */
        $actions = apply_filters( 'datebook_payments_list_table_entry_actions', $actions, $item );

        $output  = $item['username'];
        $output .= $this->row_actions( $actions );

        return $output;

    }


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

        $output = '<span class="datebook-payment-list-subscription"> ' . $item['subscription'] . ' </span>';

        return $output;

    }




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

        // Get currency symbol to display next to amount
        $currency_symbol = '';
        if ( get_option('datebook_settings') ) {

            $settings = get_option('datebook_settings');
            if ( ( function_exists('datebook_get_currency_symbol') ) && isset( $settings['payments']['currency'] ) )
                $currency_symbol = datebook_get_currency_symbol( $settings['payments']['currency'] );
        }

        return $item['amount'] . $currency_symbol;

    }


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

        $output = $item['type'];

        if( ! empty( $item['payment_gateway'] ) )
            $output .= ' (' . $item['payment_gateway'] . ')';

        return $output;

    }


    /**
     * 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 payments section in the admin section
 *
 */
class DateBook_Submenu_Page_Payments extends DateBook_Submenu_Page {


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

		// Display the edit payment view
		if( isset( $_GET['datebook-action'] ) && $_GET['datebook-action'] == 'edit_payment' && !empty( $_GET['payment_id'] ) ){
			
            // HTML output for the payments admin edit payment page
			$settings   = get_option('datebook_settings');
			
			$payment_id = !empty( $_GET['payment_id'] ) ? (int)$_GET['payment_id'] : 0;
			$payment = datebook_get_payment( $payment_id );

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

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

?>

			<div class="wrap">

				<h2><?php printf( esc_html__( 'Payment #%s', 'datebook' ), $payment_id ); ?></h2>

                <form id="datebook-form-edit-payment" class="datebook-form" method="POST" action="<?php echo admin_url( 'admin.php?page=datebook-payments-page' ); ?>">

                <!-- Hidden fields -->
                <input type="hidden" name="datebook-action" value="<?php echo esc_attr($_GET['datebook-action']); ?>" />
                <input type="hidden" name="payment_id" value="<?php echo esc_attr($payment_id); ?>" />
                
                <!-- User's Username -->
                <div class="datebook-form-field-wrapper datebook-form-field-user-name">
                
                	<label class="datebook-form-field-label"><?php echo esc_html__( 'Username', 'datebook' ); ?></label>
                    <span class="readonly medium"><strong><?php echo esc_html( $member->username ); ?></strong></span>
                    
				</div>

				<!-- Payment Subscription -->
                <div class="datebook-form-field-wrapper">
                
                	<label for="datebook-payment-subscription-id" class="datebook-form-field-label"><?php echo esc_html__( 'Subscription', 'datebook' ); ?></label>
                    
                    <select id="datebook-payment-subscription-id" name="datebook-payment-subscription-id" class="medium">
                    
                    <?php
					
					$subscription_plans = datebook_get_subscription_plans();
					
					foreach( $subscription_plans as $subscription_plan ) {
						echo '<option ' . selected( $payment->subscription_id, $subscription_plan->id, false ) . ' value="' . esc_attr( $subscription_plan->id ) . '">' . esc_html( $subscription_plan->name ) . '</option>';
					}
					
					?>
                    
					</select>

				</div>


				<!-- Payment Amount -->
                <div class="datebook-form-field-wrapper">
                
                	<input type="text" id="datebook-payment-amount" name="datebook-payment-amount" class="medium" value="<?php echo esc_attr( $payment->amount ); ?>" />

				</div>


				<!-- Payment Discount Code -->
                <?php if( !empty( $payment->discount_code ) ): ?>
                
                <div class="datebook-form-field-wrapper">
                
                	<label for="datebook-payment-discount" class="datebook-form-field-label"><?php echo esc_html__( 'Discount Code', 'datebook' ); ?></label>
                    
                    <span class="readonly medium"><strong><?php echo esc_html( $payment->discount_code ); ?></strong></span>
                    
				</div>

				<?php endif; ?>


				<!-- Payment Date -->
                <div class="datebook-form-field-wrapper">
                
                	<label for="datebook-payment-date" class="datebook-form-field-label"><?php echo esc_html__( 'Date', 'datebook' ); ?></label>
                    <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->date ) + ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS ) ) ); ?>" />
                    
				</div>
                
                
                <!-- Payment Type -->
                <div class="datebook-form-field-wrapper">
                
                	<label for="datebook-payment-type" class="datebook-form-field-label"><?php echo esc_html__( 'Type', 'datebook' ); ?></label>
                    <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->type, $type_slug, false ) . ' value="' . esc_attr( $type_slug ) . '">' . esc_html( $type_name ) . '</option>';
					}
					
					?>
                    
                    </select>
                    
				</div>
                
				<!-- Payment Transaction ID -->
                <div class="datebook-form-field-wrapper">
                
                	<label for="datebook-payment-transaction-id" class="datebook-form-field-label"><?php echo esc_html__( 'Transaction ID', 'datebook' ); ?></label>
                    
                    <input type="text" id="datebook-payment-transaction-id" name="datebook-payment-transaction-id" class="widefat" value="<?php echo ( ! empty( $payment->transaction_id ) ? esc_attr( $payment->transaction_id ) : '' ); ?>" />
                    
                    <?php if( empty( $payment->transaction_id ) && $payment->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; ?>
                    
				</div>
                
                <!-- Payment Status -->
                <div class="datebook-form-field-wrapper">
                
                	<label for="datebook-payment-status" class="datebook-form-field-label"><?php echo esc_html__( 'Status', 'datebook' ); ?></label>
                    
                    <select id="datebook-payment-status" name="datebook-payment-status" class="medium">
                    
                    <?php
					
					$statuses = datebook_get_payment_statuses();
					
					foreach( $statuses as $status_slug => $status_name ) {
						echo '<option ' . selected( $payment->status, $status_slug, false ) . ' value="' . esc_attr( $status_slug ) . '">' . esc_html( $status_name ) . '</option>';
					}
					
					?>
                    
                    </select>
                    
				</div>
                
                <!-- Payment IP Address -->
                <div class="datebook-form-field-wrapper datebook-form-field-ip-address">
                
                	<label class="datebook-form-field-label"><?php echo esc_html__( 'IP Address', 'datebook' ); ?></label>
                    
                    <span class="readonly medium"><strong><?php echo ( !empty( $payment->ip_address ) ? esc_html( $payment->ip_address ) : '-' ); ?></strong></span>
                    
				</div>
                
                
                <?php do_action( 'datebook_payment_edit_form_field' ); ?>
                
                <?php wp_nonce_field( 'datebook_payment_nonce' ); ?>
                
                <!-- Submit button and Cancel button -->
                <p class="submit"><?php submit_button( esc_html__( 'Save Payment', 'datebook' ), 'primary', 'submit_edit_payment', false ); ?><a href="<?php echo admin_url( 'admin.php?page=datebook-payments-page' ); ?>" class="button button-secondary"><?php echo esc_html__( 'Cancel', 'datebook' ); ?></a></p>
                
			</form>
            
		</div>

<?php

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

			if ($check_datebook_payments != $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('Payments (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 the Payments table.', 'datebook')?></p>
					</div>

				</div>

<?php

			} else {
				
				// Display all payments table
				
				// if Woocommerce installed then display payments made by WooCommerce functions
				//if (of_get_option('activate_woocommerce_subscription') == '2' && function_exists( 'WC' ) ) {
					
					// Builds out the Payments panel
					//echo DateBook_WC_Made_Subscriptions_Admin::datebook_subscriptions_page_handler();
					
				//} else {
					
					// HTML output for the payments admin page

?>

					<div class="wrap">

						<h1 class="wp-heading-inline"><?php esc_html_e('Payments', 'datebook')?></h1>
                    
						<p><?php esc_html_e('Payments made by users for Subscription plans', 'datebook')?></p>

						<form method="get">
							<input type="hidden" name="page" value="datebook-payments-page" />

							<?php
							
							$payments_list_table = new DateBook_Payments_List_Table();
							$payments_list_table->prepare_items();
							$payments_list_table->views();
							$payments_list_table->display();
							
							?>

						</form>

					</div>

<?php		
		
			//}
			
			}
			
		}

    }


	/**
	 * 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 that adds Screen Options to Payments page
     *
     */
	public function add_screen_options() {

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

		add_screen_option( 'per_page', $args );

	}

}