<?php

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

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

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

    if ( false === $items ) {
        $items = $wpdb->get_results( 'SELECT ' . $wpdb->prefix . 'esi_news.*, entity.name AS entity, media.name AS media, type.name AS type, region.name AS region FROM ' . $wpdb->prefix . 'esi_news
        LEFT JOIN ' . $wpdb->prefix . 'esi_media  AS media ON ' . $wpdb->prefix . 'esi_news.media_id = media.id
        LEFT JOIN ' . $wpdb->prefix . 'esi_entity  AS entity ON ' . $wpdb->prefix . 'esi_news.entity_id = entity.id
        LEFT JOIN ' . $wpdb->prefix . 'esi_type  AS type ON ' . $wpdb->prefix . 'esi_news.type_id = type.id
        LEFT JOIN ' . $wpdb->prefix . 'esi_region  AS region ON ' . $wpdb->prefix . 'esi_news.region_id = region.id
        ORDER BY ' . $args['orderby'] .' ' . $args['order'] .' LIMIT ' . $args['offset'] . ', ' . $args['number'] );

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

    return $items;
}

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

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

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

    return $wpdb->get_row( $wpdb->prepare( 'SELECT ' . $wpdb->prefix . 'esi_news.*, entity.name AS entity, entity.url AS entity_url, media.name AS media_name, media.url AS media_url, type.name AS type, region.name AS region FROM ' . $wpdb->prefix . 'esi_news
    LEFT JOIN ' . $wpdb->prefix . 'esi_media  AS media ON ' . $wpdb->prefix . 'esi_news.media_id = media.id
    LEFT JOIN ' . $wpdb->prefix . 'esi_entity  AS entity ON ' . $wpdb->prefix . 'esi_news.entity_id = entity.id
    LEFT JOIN ' . $wpdb->prefix . 'esi_type  AS type ON ' . $wpdb->prefix . 'esi_news.type_id = type.id
    LEFT JOIN ' . $wpdb->prefix . 'esi_region  AS region ON ' . $wpdb->prefix . 'esi_news.region_id = region.id
    WHERE ' . $wpdb->prefix . 'esi_news.id = %d', $id ) );
}

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

    $defaults = array(
        'id' => null,
        'title' => '',
        'description' => '',
        'url' => '',
        'publish_date' => '',
        'region_id' => '',
    );

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

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

    // remove row id to determine if new or update
    $row_id = (int) $args['id'];
    $post_id = $args['post_id'];
    unset( $args['id'] );
    $industry_id = $args['industry_id'];
    unset( $args['industry_id'] );
    $function_id = $args['function_id'];
    unset( $args['function_id'] );
    $technology_ids = $args['technology_ids'];
    unset( $args['technology_ids'] );
    $ability_ids = $args['ability_ids'];
    unset( $args['ability_ids'] );

    $radar_industry_id = esi_get_radar_by_industry($industry_id);
    $radar_function_id = esi_get_radar_by_function($function_id);
    $radar_id = array_unique(array_merge($radar_industry_id, $radar_function_id));

    $args['post_id'] = wp_insert_post(array(
        'ID' => $post_id,
        'post_title' => $args['title'],
        'post_content' => $args['description'],
        'post_type' => 'news',
    ));

    if ( ! $row_id ) {
        // insert a new
        if ( $wpdb->insert( $table_name, $args ) ) {
            $row_id = $wpdb->insert_id;
            esi_save_news_radar($row_id, $radar_id);
            esi_save_news_industry($row_id, $industry_id);
            esi_save_news_function($row_id, $function_id);
            esi_save_list_technology_news($row_id, $technology_ids);
            esi_save_list_news_ability($row_id, $ability_ids);
            return $row_id;
        }

    } else {

        esi_save_news_radar($row_id, $radar_id);
        esi_save_news_industry($row_id, $industry_id);
        esi_save_news_function($row_id, $function_id);
        esi_save_list_technology_news($row_id, $technology_ids);
        esi_save_list_news_ability($row_id, $ability_ids);

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

    return false;
}


/**
* Fetch a single radar from database
*
* @param int   $id
*
* @return array
*/
function esi_get_radar_by_news( $news ) {
    global $wpdb;
    $items = $wpdb->get_results( 'SELECT radar_id FROM ' . $wpdb->prefix . 'esi_news_radar WHERE news_id = '. $news );
    foreach( $items as $item )
        $array[] = $item->radar_id;

    return $array;
}

/**
* Fetch a single radar from database
*
* @param int   $id
*
* @return array
*/
function esi_get_industry_by_news( $news ) {
    global $wpdb;
    $items = $wpdb->get_results( 'SELECT industry_id FROM ' . $wpdb->prefix . 'esi_news_industry WHERE news_id = '. $news );
    foreach( $items as $item )
        $array[] = $item->industry_id;

    return $array;
}

/**
* Fetch a single radar from database
*
* @param int   $id
*
* @return array
*/
function esi_get_function_by_news( $news ) {
    global $wpdb;
    $items = $wpdb->get_results( 'SELECT function_id FROM ' . $wpdb->prefix . 'esi_news_function WHERE news_id = '. $news );
    foreach( $items as $item )
        $array[] = $item->function_id;

    return $array;
}

/**
* Fetch a single radar from database
*
* @param int   $id
*
* @return array
*/
function esi_get_radar_by_industry( $industry_ids = array() ) {
    global $wpdb;
    $items = $wpdb->get_results( 'SELECT radar_id FROM ' . $wpdb->prefix . 'esi_radar_industry WHERE industry_id IN ('.join(",", $industry_ids).')' );
    foreach( $items as $item )
    $array[] = $item->radar_id;

    return array_unique($array);
}

/**
* Fetch a single radar from database
*
* @param int   $id
*
* @return array
*/
function esi_get_radar_by_function( $function_ids = array() ) {
    global $wpdb;
    $items = $wpdb->get_results( 'SELECT radar_id FROM ' . $wpdb->prefix . 'esi_radar_function WHERE function_id IN ('.join(",", $function_ids).')' );
    foreach( $items as $item )
    $array[] = $item->radar_id;

    return array_unique($array);
}

/**
* Save radar industry
*
* @param int   $id
* @param array   $industries
*/
function esi_save_news_radar( $id = 0, $radars = array() ) {
    global $wpdb;
    $wpdb->delete( $wpdb->prefix . "esi_news_radar", array( 'news_id' => $id ) );
    foreach ($radars as $radar) {
        $wpdb->insert(
        $wpdb->prefix . "esi_news_radar",
        array(
            'news_id' => $id,
            'radar_id' => intval($radar)
        ));
    }
}

/**
* Save radar industry
*
* @param int   $id
* @param array   $industries
*/
function esi_save_news_industry( $id = 0, $industries = array() ) {
    global $wpdb;

    $wpdb->delete( $wpdb->prefix . "esi_news_industry", array( 'news_id' => $id ) );
    foreach ($industries as $industry) {
        $wpdb->insert(
        $wpdb->prefix . "esi_news_industry",
        array(
            'news_id' => $id,
            'industry_id' => intval($industry)
        ));
    }
}

/**
* Save radar function
*
* @param int   $id
* @param array   $functions
*/
function esi_save_news_function( $id = 0, $functions = array() ) {
    global $wpdb;

    $wpdb->delete( $wpdb->prefix . "esi_news_function", array( 'news_id' => $id ) );
    foreach ($functions as $function) {
        $wpdb->insert(
        $wpdb->prefix . "esi_news_function",
        array(
            'news_id' => $id,
            'function_id' => intval($function)
        ));
    }
}

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

/**
 * Fetch technologies array
 *
 * @param int   $id
 *
 * @return array
 */
function esi_get_list_technology( $id = 0 ) {
    global $wpdb;

    // Get Selected technology mapping
    $arrSelectedTechnology = $wpdb->get_results("SELECT * FROM " .$wpdb->prefix . "esi_technology ORDER BY name ASC");

    return $arrSelectedTechnology;
}

function esi_save_list_technology_news ( $newsid = 0, $technologyids = array() ) {
    global $wpdb;

    // Delete all current join from liaison table
    $wpdb->query($wpdb->prepare('DELETE FROM ' . $wpdb->prefix . 'esi_technology_news WHERE news_id = %d', $newsid));

    // Insert new news_id technology_id relation
    foreach ($technologyids as $technology_id) {
        $wpdb->insert(
            $wpdb->prefix . "esi_technology_news",
            array(
                'technology_id' => $technology_id,
                'news_id' => intval($newsid)
            ));
    }
}

function esi_get_list_technology_news ( $newsid = 0 ) {
    global $wpdb;

    $query = $wpdb->get_results("
        SELECT id, name
        FROM " . $wpdb->prefix . "esi_technology
        INNER JOIN " . $wpdb->prefix . "esi_technology_news 
        ON " . $wpdb->prefix . "esi_technology.id = " . $wpdb->prefix . "esi_technology_news.technology_id
        WHERE news_id = " . $newsid . "
        ");

    return $query;
}

/**
 * Fetch technologies array
 *
 * @param int   $id
 *
 * @return array
 */
function esi_get_list_selected_news_technology( $id = 0, $output = 'object' ) {
    global $wpdb;

    $query = $wpdb->get_results("
        SELECT id, name
        FROM " . $wpdb->prefix . "esi_technology
        INNER JOIN " . $wpdb->prefix . "esi_technology_news 
        ON " . $wpdb->prefix . "esi_technology.id = " . $wpdb->prefix . "esi_technology_news.technology_id
        WHERE news_id = " . $id . "
        ", OBJECT_K);

    if ($output == 'array') {

        $array = array();
        foreach ($query as $selected) {
            $array [] = $selected->id;
        }

        $query = $array;
    }

    return $query;

}

/**
 * Fetch technologies array
 *
 * @param int   $news_id
 * @param array $ability_ids
 *
 * @return array
 */
function esi_save_list_news_ability( $news_id = 0, $ability_ids = array() ) {
    global $wpdb;

    // Delete all current join from liaison table
    $wpdb->query($wpdb->prepare('DELETE FROM ' . $wpdb->prefix . 'esi_ability_news WHERE news_id = %d', $news_id));

    // Insert new news_id ability_id relation
    foreach ($ability_ids as $ability_id) {
        $wpdb->insert(
            $wpdb->prefix . "esi_ability_news",
            array(
                'ability_id' => $ability_id,
                'news_id' => intval($news_id)
            ));
    }
}

/**
 * Fetch technologies array
 *
 * @param int   $id
 *
 * @return array
 */
function esi_get_list_selected_news_ability( $id = 0, $output = 'object' ) {
    global $wpdb;

    // Get Selected technology mapping
    $arrSelectedTechnology = $wpdb->get_results("SELECT * FROM " .$wpdb->prefix . "esi_ability_news WHERE news_id = " . $id, OBJECT_K);

    if ($output == 'array') {

        $array = array();
        foreach ($arrSelectedTechnology as $selected) {
            $array [] = $selected->ability_id;
        }

        $arrSelectedTechnology = $array;
    }

    return $arrSelectedTechnology;
}
