/**
  * Template function to render the template
  *
  * @since 1.0
  */
 function woocommerce_points_rewards_my_points()
 {
     global $wc_points_rewards;
     $points_balance = WC_Points_Rewards_Manager::get_users_points(get_current_user_id());
     $points_label = $wc_points_rewards->get_points_label($points_balance);
     $count = apply_filters('wc_points_rewards_my_account_points_events', 5, get_current_user_id());
     // get a set of points events, ordered newest to oldest
     $args = array('orderby' => array('field' => 'date', 'order' => 'DESC'), 'per_page' => $count, 'paged' => 0, 'user' => get_current_user_id());
     $events = WC_Points_Rewards_Points_Log::get_points_log_entries($args);
     // load the template
     woocommerce_get_template('myaccount/my-points.php', array('points_balance' => $points_balance, 'points_label' => $points_label, 'events' => $events), '', $wc_points_rewards->get_plugin_path() . '/templates/');
 }
 /**
  * Reduces the points balance for the user identified by $user_id
  *
  * @since 1.0
  * @param int $user_id the user identifier
  * @param int $points the points to reduce, ie 75
  * @param string $event_type the type of event responsible
  * @param mixed $data optional arbitrary data to associate with the log for this action
  * @param int $order_id optional order identifier, if this action is associated with a particular order
  * @return boolean true if the points are successfully reduced from the user's balance
  */
 public static function decrease_points($user_id, $points, $event_type, $data = null, $order_id = null)
 {
     global $wc_points_rewards, $wpdb;
     // ensure the user exists
     $user = get_userdata($user_id);
     if (false === $user) {
         return false;
     }
     $points = apply_filters('wc_points_rewards_decrease_points', $points, $user_id, $event_type, $data, $order_id);
     // get any existing points records
     $query = "SELECT * FROM {$wc_points_rewards->user_points_db_tablename} WHERE user_id = %d and points_balance != 0 ORDER BY date ASC";
     $user_points = $wpdb->get_results($wpdb->prepare($query, $user_id));
     // no non-zero records, so create a new one
     if (empty($user_points)) {
         $_data = array('user_id' => $user_id, 'points' => -$points, 'points_balance' => -$points, 'date' => current_time('mysql', 1));
         $format = array('%d', '%d', '%d', '%s');
         if ($order_id) {
             $_data['order_id'] = $order_id;
             $format[] = '%d';
         }
         // create the negative-balance user points record
         $wpdb->insert($wc_points_rewards->user_points_db_tablename, $_data, $format);
     } elseif (count($user_points) > 0) {
         // existing non-zero points records
         $points_difference = -$points;
         // the goal is to get each existing record as close to zero as possible, oldest to newest
         foreach ($user_points as $index => &$_points) {
             if ($_points->points_balance > 0 && $points_difference < 0) {
                 $_points->points_balance += $points_difference;
                 if ($_points->points_balance >= 0 || count($user_points) - 1 == $index) {
                     // used up all of points_difference, or reached the newest user points record which therefore receives the remaining balance
                     $points_difference = 0;
                     break;
                 } else {
                     // still have more points balance to distribute
                     $points_difference = $_points->points_balance;
                     $_points->points_balance = 0;
                 }
             } elseif (count($user_points) - 1 == $index && 0 != $points_difference) {
                 // if we made it here, assign all remaining points to the final record and we're done
                 $_points->points_balance += $points_difference;
                 $points_difference = 0;
             }
         }
         // update any affected rows
         for ($i = 0; $i <= $index; $i++) {
             $wpdb->update($wc_points_rewards->user_points_db_tablename, array('points_balance' => $user_points[$i]->points_balance), array('id' => $user_points[$i]->id), array('%d'), array('%d'));
         }
     }
     // update the current points balance user meta
     $points_balance = (int) get_user_meta($user_id, 'wc_points_balance');
     update_user_meta($user_id, 'wc_points_balance', $points_balance - $points);
     // log the points change
     $args = array('user_id' => $user_id, 'points' => -$points, 'event_type' => $event_type);
     // optional associated order
     if ($order_id) {
         $args['order_id'] = $order_id;
     }
     // optional associated data
     if ($data) {
         $args['data'] = $data;
     }
     // log the event
     WC_Points_Rewards_Points_Log::add_log_entry($args);
     do_action('wc_points_rewards_after_reduce_points', $user_id, $points_balance);
     // always return true for now
     return true;
 }
 /**
  * Query for point log entries based on $args
  *
  * @since 1.0
  * @param array $args the query arguments
  * @return array of log entry objects
  */
 public static function query($args)
 {
     global $wc_points_rewards, $wpdb;
     // calculate found rows? (costly, but needed for pagination)
     $found_rows = '';
     if (isset($args['calc_found_rows']) && $args['calc_found_rows']) {
         $found_rows = 'SQL_CALC_FOUND_ROWS';
     }
     // distinct results?
     $distinct = '';
     if (isset($args['distinct']) && $args['distinct']) {
         $distinct = 'DISTINCT';
     }
     // returned fields
     $fields = "{$wc_points_rewards->user_points_log_db_tablename}.*";
     if (!empty($args['fields']) && is_array($args['fields'])) {
         $fields .= ', ' . implode(', ', $args['fields']);
     }
     // joins
     $join = '';
     if (!empty($args['join']) && is_array($args['join'])) {
         $join = implode(' ', $args['join']);
     }
     // where clauses
     $where = '';
     if (!empty($args['where'])) {
         $where = "AND " . implode(" AND ", $args['where']);
     }
     // group by
     $groupby = '';
     if (!empty($args['groupby']) && is_array($args['groupby'])) {
         $groupby = implode(', ', $args['groupby']);
     }
     // order by
     $orderby = '';
     if (!empty($args['orderby'])) {
         // convert "really simple" format of simply a string
         if (is_string($args['orderby'])) {
             $args['orderby'] = array(array('field' => $args['orderby']));
         }
         // check if the 'simple' format is being used with a single column to order by
         list($key) = array_keys($args['orderby']);
         if (is_string($key)) {
             $args['orderby'] = array($args['orderby']);
         }
         foreach ($args['orderby'] as $_orderby) {
             if (isset($_orderby['field'])) {
                 $orderby .= empty($orderby) ? $_orderby['field'] : ', ' . $_orderby['field'];
                 if (isset($_orderby['order'])) {
                     $orderby .= ' ' . $_orderby['order'];
                 }
             }
         }
         if ($orderby) {
             $orderby = 'ORDER BY ' . $orderby;
         }
     }
     // query limits
     $limits = '';
     // allow a page and per_page to be provided, or simply per_page to limit to that number of results (defaults 'paged' to '1')
     if (!empty($args['per_page']) && empty($args['paged'])) {
         $args['paged'] = 1;
     }
     if (!empty($args['per_page'])) {
         $limits = ' LIMIT ' . ($args['paged'] - 1) * $args['per_page'] . ', ' . $args['per_page'];
     }
     // build the query
     $query = "SELECT {$found_rows} {$distinct} {$fields} FROM {$wc_points_rewards->user_points_log_db_tablename} {$join} WHERE 1=1 {$where} {$groupby} {$orderby} {$limits}";
     $results = $wpdb->get_results($query);
     // record the found rows
     if (isset($args['calc_found_rows']) && $args['calc_found_rows']) {
         self::$found_rows = $wpdb->get_var('SELECT FOUND_ROWS()');
     }
     $results = $results ? $results : array();
     return $results;
 }
    /**
     * Extra controls to be displayed before pagination, which
     * includes our Filters: Customers, Event Types, Event Dates
     *
     * @see WP_List_Table::extra_tablenav();
     * @since 1.0
     * @param string $which the placement, one of 'top' or 'bottom'
     */
    public function extra_tablenav($which)
    {
        global $woocommerce;
        if ('top' == $which) {
            echo '<div class="alignleft actions">';
            // Customers, products
            ?>
			<select id="dropdown_customers" name="_customer_user">
				<option value=""><?php 
            _e('Show All Customers', 'wc_points_rewards');
            ?>
</option>
				<?php 
            if (!empty($_GET['_customer_user'])) {
                $user = get_user_by('id', absint($_GET['_customer_user']));
                echo '<option value="' . absint($user->ID) . '" ';
                selected(1, 1);
                echo '>' . esc_html($user->display_name) . ' (#' . absint($user->ID) . ' &ndash; ' . esc_html($user->user_email) . ')</option>';
            }
            ?>
			</select>

			<select id="dropdown_event_types" name="_event_type">
				<option value=""><?php 
            _e('Show All Event Types', 'wc_points_rewards');
            ?>
</option>
				<?php 
            foreach (WC_Points_Rewards_Points_Log::get_event_types() as $event_type) {
                echo '<option value="' . esc_attr($event_type->type) . '" ' . selected($event_type->type, isset($_GET['_event_type']) ? $_GET['_event_type'] : null, false) . '>' . esc_html(sprintf("%s (%d)", $event_type->name, $event_type->count)) . '</option>';
            }
            ?>
			</select>
			<?php 
            $this->render_dates_dropdown();
            submit_button(__('Filter'), 'button', false, false, array('id' => 'post-query-submit'));
            echo '</div>';
            // javascript
            $js = "\n\t\t\t\t// Ajax Chosen Product Selectors\n\t\t\t\t\$('select#dropdown_dates').css('width', '250px').chosen();\n\n\t\t\t\t\$('select#dropdown_event_types').css('min-width', '190px').chosen();\n\n\t\t\t\t\$('select#dropdown_customers').css('width', '250px').ajaxChosen({\n\t\t\t\t\tmethod:         'GET',\n\t\t\t\t\turl:            '" . admin_url('admin-ajax.php') . "',\n\t\t\t\t\tdataType:       'json',\n\t\t\t\t\tafterTypeDelay: 100,\n\t\t\t\t\tminTermLength:  1,\n\t\t\t\t\tdata: {\n\t\t\t\t\t\taction:   'woocommerce_json_search_customers',\n\t\t\t\t\t\tsecurity: '" . wp_create_nonce("search-customers") . "',\n\t\t\t\t\t\tdefault:  '" . esc_js(__('Show All Customers', 'wc_points_rewards')) . "'\n\t\t\t\t\t}\n\t\t\t\t}, function (data) {\n\n\t\t\t\t\tvar terms = {};\n\n\t\t\t\t\t\$.each(data, function (i, val) {\n\t\t\t\t\t\tterms[i] = val;\n\t\t\t\t\t});\n\n\t\t\t\t\treturn terms;\n\t\t\t\t});\n\t\t\t";
            if (function_exists('wc_enqueue_js')) {
                wc_enqueue_js($js);
            } else {
                $woocommerce->add_inline_js($js);
            }
        }
    }