<?php

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

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

    $args      = wp_parse_args( $args, $defaults );
    $cache_key = 'media-all';
    $items     = wp_cache_get( $cache_key, 'esi' );

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

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

    return $items;
}

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

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

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

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

/**
* Fetch a single media from database
*
* @param int   $id
*
* @return array
*/
function esi_get_media_by_url( $url = "" ) {
    global $wpdb;

    return $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . $wpdb->prefix . 'esi_media WHERE url = %s', $url ) );
}

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

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

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

    // some basic validation
    if ( empty( $args['name'] ) ) {
        return new WP_Error( 'no-name', __( 'No Name provided.', 'esi' ) );
    }
    if ( empty( $args['url'] ) ) {
        return new WP_Error( 'no-url', __( 'No URL provided.', 'esi' ) );
    }
    if($mediaExist = esi_get_media_by_url($args['url'])) {
        return $mediaExist->id;
    }


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

    if ( ! $row_id) {
        // insert a media
        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_media( $id = 0 ) {
    global $wpdb;
    $wpdb->query( $wpdb->prepare( 'DELETE FROM ' . $wpdb->prefix . 'esi_media WHERE id = %d', $id ) );
}
