<?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.*, 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_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.*, 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_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'] );
    $entity_ids = $args['entity_ids'];
    unset( $args['entity_ids'] );
    $tag_ids = $args['tag_ids'];
    unset( $args['tag_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_entity($row_id, $entity_ids);
            esi_save_list_news_tag($row_id, $tag_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_entity($row_id, $entity_ids);
        esi_save_list_news_tag($row_id, $tag_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;

    $array = array();
    $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 $tag_ids
 *
 * @return array
 */
function esi_save_list_news_tag( $news_id = 0, $tag_ids = array() ) {
    global $wpdb;

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

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

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

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

    // Insert new news_id tag_id relation
    foreach ($entity_ids as $entity_id) {
        $wpdb->insert(
            $wpdb->prefix . "esi_news_entity",
            array(
                'entity_idaaaa' => $entity_id,
                'news_id' => intval($news_id)
            ));

        if ($wpdb->last_error) {
            return new WP_Error( 'query_failed', 'No update. ' . $wpdb->last_error);
        }
    }



}

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

    $query = $wpdb->get_results("
        SELECT id, name
        FROM " . $wpdb->prefix . "esi_entity
        INNER JOIN " . $wpdb->prefix . "esi_news_entity
        ON " . $wpdb->prefix . "esi_entity.id = " . $wpdb->prefix . "esi_news_entity.entity_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   $id
 *
 * @return array
 */
function esi_get_list_selected_news_tag( $id = 0, $output = 'object' ) {
    global $wpdb;

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

    if ($output == 'array') {

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

        $arrSelectedTechnology = $array;
    }

    return $arrSelectedTechnology;
}

//$name = 'John Doe';
//
//add_action('admin_notices', function() use ($name){
//    echo "<div class='notice notice-error is-dismissible'>
//             <p>". $name ."</p>
//         </div>";
//});

function esi_error_display() {

    if ($_GET['error']) {
        $errors = $_GET['error'];

        if (is_array($errors)) {
            foreach ($errors as $error) {
                add_action('admin_notices', function() use ($error){
                    echo "<div class='notice notice-error is-dismissible'>
                <p>". $error ."</p>
                </div>";
                });
            }
        }
        else {
            add_action('admin_notices', function() use ($errors){
                echo "<div class='notice notice-error is-dismissible'>
         <p>". $errors ."</p>
     </div>";
            });
        }

        do_action('admin_notices');
    }

    if ($_GET['success']) {
        $errors = $_GET['success'];

        if (is_array($errors)) {
            foreach ($errors as $error) {
                add_action('admin_notices', function() use ($error){
                    echo "<div class='notice notice-success is-dismissible'>
                <p>". $error ."</p>
                </div>";
                });
            }
        }
        else {
            add_action('admin_notices', function() use ($errors){
                echo "<div class='notice notice-success is-dismissible'>
         <p>". $errors ."</p>
     </div>";
            });
        }

        do_action('admin_notices');
    }

}