<?php

/**
* Get all type
*
* @param $args array
*
* @return array
*/
function esi_get_all_investment_type( $args = array() ) {
    global $wpdb;

    $defaults = array(
        'number'     => 20,
        'offset'     => 0,
        'orderby'    => 'id',
        'order'      => 'ASC',
    );

    $args      = wp_parse_args( $args, $defaults );
    $cache_key = 'type-all';
    $items     = wp_cache_get( $cache_key, 'esi_investment_type' );

    if ( false === $items ) {
        $items = $wpdb->get_results( 'SELECT * FROM ' . $wpdb->prefix . 'esi_investment_type ORDER BY ' . $args['orderby'] .' ' . $args['order'] .' LIMIT ' . $args['offset'] . ', ' . $args['number'] );

        wp_cache_set( $cache_key, $items, 'esi_investment_type' );
    }

    return $items;
}

/**
* Fetch all type from database
*
* @return array
*/
function esi_get_investment_type_count() {
    global $wpdb;

    return (int) $wpdb->get_var( 'SELECT COUNT(*) FROM ' . $wpdb->prefix . 'esi_investment_type' );
}

/**
* Fetch a single type from database
*
* @param int   $id
*
* @return array
*/
function esi_get_investment_type( $id = 0 ) {
    global $wpdb;

    return $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . $wpdb->prefix . 'esi_investment_type WHERE id = %d', $id ) );
}

/**
* Insert a type type
*
* @param array $args
*/
function esi_insert_investment_type( $args = array() ) {
    global $wpdb;

    $defaults = array(
        'id'         => null,
        'name' => '',
        'description' => '',
    );

    $args       = wp_parse_args( $args, $defaults );
    $table_name = $wpdb->prefix . 'esi_investment_type';

    // some basic validation
    if ( empty( $args['name'] ) ) {
        return new WP_Error( 'no-name', __( 'No name provided.', 'esi' ) );
    }
    if ( empty( $args['description'] ) ) {
        return new WP_Error( 'no-description', __( 'No description provided.', 'esi' ) );
    }


    // remove row id to determine if type or update
    $row_id = (int) $args['id'];
    unset( $args['id'] );

    if ( ! $row_id ) {
        // insert a type
        if ( $wpdb->insert( $table_name, $args ) ) {
            return $wpdb->insert_id;
        }

    } else {

        // do update method here
        if ( $wpdb->update( $table_name, $args, array( 'id' => $row_id ) ) ) {
            return $row_id;
        }
    }

    return false;
}

/**
* Deletitem
*
* @param int   $id
*
*/
function esi_delete_investment_type( $id = 0 ) {
    global $wpdb;
    $wpdb->query( $wpdb->prepare( 'DELETE FROM ' . $wpdb->prefix . 'esi_investment_type WHERE id = %d', $id ) );
}
