/**
 * Fetches emails from queue and sends them in batches of 10
 * 
 * @access public
 * @since 0.9.2
 * @return $sent (number of emails successfully processed)
 */
function edd_pup_ajax_trigger()
{
    global $wpdb;
    global $edd_options;
    global $wpdb;
    if (!empty($_POST['email_id']) && absint($_POST['email_id']) != 0) {
        $email_id = $_POST['email_id'];
    } else {
        $email_id = get_transient('edd_pup_sending_email_' . get_current_user_id());
    }
    // Refresh email ID transient
    set_transient('edd_pup_sending_email_' . get_current_user_id(), $email_id, 60);
    $batch = $_POST['iteration'];
    $sent = $_POST['sent'];
    $limit = 10;
    $rows = array();
    /* Throttle emails if enabled in settings
    	if ( isset( $edd_options['edd_pup_throttle'] ) ) {
    		
    		$last = $wpdb->query( "SELECT UNIX_TIMESTAMP(sent_date) FROM $wpdb->edd_pup_queue WHERE email_id = $email_id AND sent = 1 ORDER BY sent_date DESC LIMIT 1" )
    		$now = time();
    		
    		if ( ( $now - $last ) < $edd_options['edd_pup_throttle_int'] ) {
    			echo json_encode(array('status'=>'new','sent'=>0,'total'=>absint($total),'processed'=>absint($processed+$count)));
    			exit;
    		}
    	}*/
    $query = "SELECT * FROM {$wpdb->edd_pup_queue} WHERE email_id = {$email_id} AND sent = 0 LIMIT {$limit}";
    $customers = $wpdb->get_results($query, ARRAY_A);
    foreach ($customers as $customer) {
        $trigger = edd_pup_ajax_send_email($customer['customer_id'], $email_id, $edd_options['edd_pup_test']);
        // Reset file download limits for customers' eligible updates
        $customer_updates = edd_pup_get_customer_updates($customer['customer_id'], $email_id);
        foreach ($customer_updates as $download) {
            $limit = edd_get_file_download_limit($download['id']);
            if (!empty($limit)) {
                edd_set_file_download_limit_override($download['id'], $customer['customer_id']);
            }
        }
        if (true == $trigger) {
            $rows[] = $customer['eddpup_id'];
            $sent++;
        }
    }
    // Designate emails in database as having been sent
    if (!empty($rows)) {
        $updateids = implode(',', $rows);
        $wpdb->query("UPDATE {$wpdb->edd_pup_queue} SET sent=1 WHERE eddpup_id IN ({$updateids})");
    }
    echo $sent;
    exit;
}
/**
 * Email template tag: updated_products_links
 * A list of updated products with download links included
 * 
 * @access public
 * @param mixed $payment_id
 * @return void
 */
function edd_pup_products_links_tag_plain($payment_id, $email = null)
{
    // Used to generate accurate tag outputs for preview and test emails
    if (isset($email) && absint($email) != 0) {
        $updated_products = get_post_meta($email, '_edd_pup_updated_products', true);
        $updated_products = is_array($updated_products) ? $updated_products : array($updated_products);
        foreach ($updated_products as $id => $name) {
            $customer_updates[$id] = array('id' => $id, 'name' => $name);
        }
    } else {
        $email = get_transient('edd_pup_sending_email_' . get_current_user_id());
        $updated_products = get_post_meta($email, '_edd_pup_updated_products', true);
        $updated_products = is_array($updated_products) ? $updated_products : array($updated_products);
        $customer_updates = edd_pup_get_customer_updates($payment_id, $email);
        $customer_updates = is_array($customer_updates) ? $customer_updates : array($customer_updates);
    }
    $filters = get_post_meta($email, '_edd_pup_filters', true);
    if ($customer_updates) {
        $show_names = apply_filters('edd_pup_email_show_names', true);
        $payment_data = edd_get_payment_meta($payment_id);
        // Set email to most recent email if it's been changed from initial email
        if (isset($payment_data['user_info']['email']) && $payment_data['user_info']['email'] != $payment_data['email']) {
            $payment_data['email'] = $payment_data['user_info']['email'];
        }
        // Used for detecting when to place commas
        $c = 1;
        $download_list = '';
        foreach ($customer_updates as $item) {
            if (edd_use_skus()) {
                $sku = edd_get_download_sku($item['id']);
            }
            $price_id = edd_get_cart_item_price_id($item);
            if ($show_names) {
                $title = $c == 1 ? $item['name'] : ', ' . $item['name'];
                if (!empty($sku)) {
                    $title .= "&nbsp;&ndash;&nbsp;" . __('SKU', 'edd') . ': ' . $sku;
                }
                $download_list .= apply_filters('edd_pup_email_products_link_title_plain', $title, $item, $price_id, $payment_id);
            }
            $files = edd_get_download_files($item['id'], $price_id);
            if ($files) {
                // $f used for detecting when to place commas
                $f = 1;
                $download_list .= ' (';
                foreach ($files as $filekey => &$file) {
                    $file_url = edd_get_download_file_url($payment_data['key'], $payment_data['email'], $filekey, $item['id'], $price_id);
                    $download_list .= $f == 1 ? edd_get_file_name($file) . ': ' . esc_url($file_url) : ', ' . edd_get_file_name($file) . ': ' . esc_url($file_url);
                    $f++;
                }
                $download_list .= ')';
            }
            if (edd_is_bundled_product($item['id'])) {
                $b = 1;
                $bundled_products = edd_get_bundled_products($item['id']);
                $download_list .= "&nbsp;&ndash;&nbsp;";
                foreach ($bundled_products as $bundle_item) {
                    if ($filters['bundle_1'] == 'all' || isset($updated_products[$bundle_item])) {
                        $download_list .= $b == 1 ? get_the_title($bundle_item) : '; ' . get_the_title($bundle_item);
                        $fb = 1;
                        $bundlefiles = edd_get_download_files($bundle_item);
                        $download_list .= ' (';
                        foreach ($bundlefiles as $bundlefilekey => $bundlefile) {
                            $bundlefile_url = edd_get_download_file_url($payment_data['key'], $payment_data['email'], $bundlefilekey, $bundle_item, $price_id);
                            $download_list .= $fb == 1 ? $bundlefile['name'] . ': ' . esc_url($bundlefile_url) : ', ' . $bundlefile['name'] . ': ' . esc_url($bundlefile_url);
                            $fb++;
                        }
                        $download_list .= ')';
                    }
                    $b++;
                }
            }
            if ('' != edd_get_product_notes($item['id'])) {
                $download_list .= ' &ndash; ' . edd_get_product_notes($item['id']);
            }
            $c++;
        }
        return $download_list;
    }
}