/**
 * Displays the meta box contents (called by *add_meta_box* callback).
 *
 * @param WP_Post $post The current post.
 */
function wl_entities_box_content($post)
{
    // wl_write_log( "wl_entities_box_content [ post id :: $post->ID ]" );
    // Angularjs edit-post widget wrapper
    echo '<div id="wordlift-edit-post-outer-wrapper"></div>';
    // Angularjs edit-post widget classification boxes configuration
    $classification_boxes = unserialize(WL_CORE_POST_CLASSIFICATION_BOXES);
    // Array to store all related entities ids
    $all_referenced_entities_ids = array();
    // Add selected entities to classification_boxes
    foreach ($classification_boxes as $i => $box) {
        // Build the proper relation name
        $relation_name = $box['id'];
        // wl_write_log( "Going to related of $relation_name" );
        // Get entity ids related to the current post for the given relation name (both draft and published entities)
        $draft_entity_ids = wl_core_get_related_entity_ids($post->ID, array('predicate' => $relation_name, 'status' => 'draft'));
        $publish_entity_ids = wl_core_get_related_entity_ids($post->ID, array('predicate' => $relation_name, 'status' => 'publish'));
        $entity_ids = array_unique(array_merge($draft_entity_ids, $publish_entity_ids));
        // Store the entity ids for all the 4W
        $all_referenced_entities_ids = array_merge($all_referenced_entities_ids, $entity_ids);
        // Transform entity ids array in entity uris array
        array_walk($entity_ids, function (&$entity_id) {
            // Retrieve the entity uri for the given entity id
            $entity_id = wl_get_entity_uri($entity_id);
        });
        // Enhance current box selected entities
        $classification_boxes[$i]['selectedEntities'] = $entity_ids;
    }
    // Json encoding for classification boxes structure
    $classification_boxes = json_encode($classification_boxes);
    // Ensure there are no repetitions of the referenced entities
    $all_referenced_entities_ids = array_unique($all_referenced_entities_ids);
    // Build the entity storage object
    $referenced_entities_obj = array();
    foreach ($all_referenced_entities_ids as $referenced_entity) {
        $entity = wl_serialize_entity($referenced_entity);
        $referenced_entities_obj[$entity['id']] = $entity;
    }
    $referenced_entities_obj = empty($referenced_entities_obj) ? '{}' : json_encode($referenced_entities_obj);
    $default_thumbnail_path = WL_DEFAULT_THUMBNAIL_PATH;
    $dataset_uri = wl_configuration_get_redlink_dataset_uri();
    echo <<<EOF
    <script type="text/javascript">
        jQuery( function() {

        \tif ('undefined' == typeof window.wordlift) {
            \twindow.wordlift = {}
            \twindow.wordlift.entities = {}  \t\t
        \t}

        \twindow.wordlift.classificationBoxes = {$classification_boxes};
        \twindow.wordlift.entities = {$referenced_entities_obj};
        \twindow.wordlift.currentPostId = {$post->ID};
\t\t\twindow.wordlift.defaultThumbnailPath = '{$default_thumbnail_path}';
\t\t\twindow.wordlift.datasetUri = '{$dataset_uri}';

        });
    </script>
EOF;
}
function wl_shortcode_faceted_search_ajax($http_raw_data = null)
{
    // Entity ID must be defined
    if (!isset($_GET['entity_id'])) {
        wp_die('No entity_id given');
        return;
    }
    $entity_id = $_GET['entity_id'];
    // If the current post is not an entity post an exception needs to be raised
    $entity = get_post($entity_id);
    if (Wordlift_Entity_Service::TYPE_NAME !== $entity->post_type) {
        wp_die('Faceted search supports only entity posts');
        return;
    }
    // Which type was requested?
    if (isset($_GET['type'])) {
        $required_type = $_GET['type'];
    } else {
        $required_type = null;
    }
    // Extract filtering conditions
    $filtering_entity_uris = null == $http_raw_data ? file_get_contents("php://input") : $http_raw_data;
    $filtering_entity_uris = json_decode($filtering_entity_uris);
    // Set up data structures
    $referencing_post_ids = wl_core_get_related_post_ids($entity_id, array('status' => 'publish'));
    $results = array();
    if ('posts' == $required_type) {
        // Required filtered posts.
        wl_write_log("Going to find related posts for the current entity [ entity ID :: {$entity_id} ]");
        if (empty($filtering_entity_uris)) {
            // No filter, just get referencing posts
            foreach ($referencing_post_ids as $post_obj_id) {
                $post_obj = get_post($post_obj_id);
                $thumbnail = wp_get_attachment_url(get_post_thumbnail_id($post_obj->ID, 'thumbnail'));
                $post_obj->thumbnail = $thumbnail ? $thumbnail : WL_DEFAULT_THUMBNAIL_PATH;
                $post_obj->permalink = get_post_permalink($post_obj->ID);
                $results[] = $post_obj;
            }
        } else {
            $filtering_entity_ids = wl_get_entity_post_ids_by_uris($filtering_entity_uris);
            // Search posts that reference all the filtering entities.
            $filtered_posts = wl_core_get_posts(array('get' => 'posts', 'post__in' => $referencing_post_ids, 'related_to__in' => $filtering_entity_ids, 'post_type' => 'post', 'as' => 'subject'));
            foreach ($filtered_posts as $post_obj) {
                $thumbnail = wp_get_attachment_url(get_post_thumbnail_id($post_obj->ID, 'thumbnail'));
                $post_obj->thumbnail = $thumbnail ? $thumbnail : WL_DEFAULT_THUMBNAIL_PATH;
                $post_obj->permalink = get_post_permalink($post_obj->ID);
                $results[] = $post_obj;
            }
            $results = $filtered_posts;
        }
    } else {
        global $wpdb;
        wl_write_log("Going to find related entities for the current entity [ entity ID :: {$entity_id} ]");
        // Retrieve Wordlift relation instances table name
        $table_name = wl_core_get_relation_instances_table_name();
        $ids = implode(',', $referencing_post_ids);
        // TODO - if an entity is related with different predicates each predicate impacts on counter
        $query = <<<EOF
            SELECT object_id as ID, count( object_id ) as counter 
            FROM {$table_name} 
            WHERE subject_id IN ({$ids}) and object_id != {$entity_id}
            GROUP BY object_id;
EOF;
        wl_write_log("Going to find related entities for the current entity [ entity ID :: {$entity_id} ] [ query :: {$query} ]");
        $entities = $wpdb->get_results($query, OBJECT);
        wl_write_log("Entities found " . count($entities));
        foreach ($entities as $obj) {
            $entity = get_post($obj->ID);
            $entity = wl_serialize_entity($entity);
            $entity['counter'] = $obj->counter;
            $results[] = $entity;
        }
    }
    wl_core_send_json($results);
}