/**
 * Insert new subscriber.
 *
 * Add a new row of data in the failsafe table.
 *
 * @since  2.0
 *
 * @param  array   $data     Details of the subscriber
 * @param  boolean $wp_error Allow the function to return a WP_Error object
 *
 * @return mixed          Subscriber ID on success or WP_Error on failure
 */
function wpbo_failsafe_add_subscriber($data = array(), $wp_error = true)
{
    global $wpdb;
    $table_name = wpbo_failsafe_table;
    $defaults = array('ID' => false, 'conversion_id' => 0, 'time' => '', 'first_name' => '', 'last_name' => '', 'email' => '', 'provider' => '', 'status' => '');
    $data = array_merge($defaults, $data);
    if (empty($data['time']) || '0000-00-00 00:00:00' == $data['time']) {
        $data['time'] = current_time('mysql');
    }
    /**
     * Validate the date
     */
    $valid_date = wpbo_check_date($data['time']);
    if (!$valid_date) {
        if ($wp_error) {
            return new WP_Error('invalid_date', __('Whoops, the provided date is invalid.'));
        } else {
            return false;
        }
    }
    // Make sure we have a provider
    if (empty($data['provider'])) {
        $provider = str_replace(' ', '', ucwords(str_replace(array('-', '_'), ' ', sanitize_text_field(wpbo_get_option('mailing_provider', '')))));
        $data['provider'] = $provider;
    }
    // Set the status as failed by default
    if (empty($data['status'])) {
        $data['status'] = 'failed';
    }
    /* Sanitize all data values */
    $data = array_map('sanitize_text_field', $data);
    $insert = $wpdb->insert($table_name, $data, array('%s', '%d', '%d', '%s', '%s', '%s', '%s', '%s'));
    if (false === $insert) {
        if ($wp_error) {
            return new WP_Error('insert_failed', __('Whoops, we could not insert the data in the database.'));
        } else {
            return false;
        }
    } else {
        return $wpdb->insert_id;
    }
}
/**
 * Get a set of datas.
 *
 * Retrieve a set of datas based on the user
 * criterias. This function can return one or
 * more row(s) of data depending on the arguments;
 *
 * @param  array $args   Arguments
 * @param string $output Desired output format
 *
 * @return mixed
 */
function wpbo_db_get_datas($args, $output = 'OBJECT')
{
    global $wpdb;
    $table_name = wpbo_analytics_table;
    $query = array();
    $defaults = array('data_type' => 'any', 'user_agent' => '', 'referer' => '', 'popup_id' => '', 'date' => array(), 'limit' => 5, 'period' => '');
    $args = array_merge($defaults, $args);
    /**
     * Handle the limit
     */
    if (-1 === $args['limit']) {
        $args['limit'] = 1000;
    }
    /**
     * Handle data type first
     */
    if (is_array($args['data_type'])) {
        $relation = isset($args['data_type']['relation']) && in_array($args['data_type']['relation'], array('IN', 'NOT IN')) ? $args['data_type']['relation'] : 'IN';
        $types = array();
        foreach ($args['data_type']['type'] as $type) {
            array_push($types, "'{$type}'");
        }
        $types = implode(',', $types);
        array_push($query, "data_type {$relation} ({$types})");
    } elseif ('' != $args['data_type']) {
        if ('any' == $args['data_type']) {
            array_push($query, "data_type IN ( 'impression', 'conversion' )");
        } else {
            array_push($query, "data_type = '{$args['data_type']}'");
        }
    }
    /**
     * Handle the popup_id
     *
     * @todo test
     */
    if (is_array($args['popup_id'])) {
        $relation = isset($args['popup_id']['relation']) && in_array($args['popup_id']['relation'], array('IN', 'NOT IN')) ? $args['popup_id']['relation'] : 'IN';
        $popups = array();
        foreach ($args['popup_id']['ids'] as $popup) {
            array_push($popups, "{$popup}");
        }
        $popups = implode(',', $popups);
        array_push($query, "popup_id {$relation} ({$popups})");
    } elseif ('' != $args['popup_id']) {
        array_push($query, "popup_id = {$args['popup_id']}");
    }
    /**
     * Handle the period.
     */
    if ('' != $args['period']) {
        if (is_array($args['period'])) {
            $start = isset($args['period']['from']) ? date("Y-m-d", $args['period']['from']) : date("Y-m-d", time());
            $end = isset($args['period']['to']) ? date("Y-m-d", $args['period']['to']) : date("Y-m-d", time());
            $start = true === wpbo_check_date($start) ? $start . ' 00:00:00' : date("Y-m-d", time()) . ' 00:00:00';
            $end = true === wpbo_check_date($end) ? $end . ' 23:59:59' : date("Y-m-d", time()) . ' 23:59:59';
            array_push($query, "time BETWEEN '{$start}' AND '{$end}'");
        } else {
            /* Get datetime format */
            $date = date("Y-m-d", $args['period']);
            $start = "{$date} 00:00:00";
            $end = "{$date} 23:59:59";
            array_push($query, "time BETWEEN '{$start}' AND '{$end}'");
        }
    }
    /* Merge the query */
    $limit = (int) $args['limit'];
    $query = implode(' AND ', $query);
    $rows = $wpdb->get_results("SELECT * FROM {$table_name} WHERE {$query} LIMIT {$limit}", $output);
    return $rows;
}