<?php

require_once(ABSPATH . "wp-admin" . '/includes/image.php');

function bp_dedication_create_new_dedication() {
    global $bp;

    /**
     * First check the nonce to make sure that the user has initiated this
     * action. Remember the wp_nonce_url() call? The second parameter is what
     * you need to check for.
     */
    check_admin_referer('bp_dedication_create_new_dedication');

    if (empty($_POST) || !wp_verify_nonce($_POST['_wpnonce_new_dedication'], 'new_dedication')) {
        return false;
    }

    // Do some minor form validation to make sure there is content
    if (isset($_POST['dedication_text'])) {
        $title = $_POST['dedication_text'];
    } else {
        return false;
    }

    if (isset($_POST['friend_ids'])) {
        $friend_ids = explode(',', $_POST['friend_ids']);
    } 

    if (isset($_POST['friend_email'])) {
        $friend_email = $_POST['friend_email'];
        
        if (isset($_POST['dedicate_to_name'])) {
            $friend_name = $_POST['dedicate_to_name'];
        }

        if (isset($_POST['dedicate_to_country'])) {
            $friend_country = $_POST['dedicate_to_country'];
        }
    } 
    
    if (isset($_POST['video_url'])) {
        $video_url = $_POST['video_url'];
    } else {
        return false;
    }

    if (isset($_POST['artist_name'])) {
        $artist_name = $_POST['artist_name'];
    }

    if (isset($_POST['song_name'])) {
        $song_name = $_POST['song_name'];
    }

    if (isset($_POST['private_dedication'])) {
        if ($_POST['private_dedication']) {
            $post_status = 'private';
        } else {
            $post_status = 'publish';
        }
    } else {
        $post_status = 'publish';
    }
    
    // Para quien va el video ?
    if (isset($friend_email) && (is_email($friend_email))) {
        // Existe un usuario con ese email?
        $user_email = get_user_by('email', $friend_email);
        if ($user_email) {
            $friend_ids = array(',');
            $friend_ids[] = $user_email->ID;
        } else {
            $friend_ids = array();
        }
    }
    
    $videoData = array();
    
    if ((!isYoutubeVideo($video_url)) && (!isVimeoVideo($video_url))) {
        return false;
    }
    
    if (isYoutubeVideo($video_url)) {
        $videoID = getYouTubeVideoID($video_url);

        if (checkYoutubeId($videoID) == 1) {
            $xml = getYouTubeVideoDetails($videoID);
            if ($xml->title != 'YouTube Videos') {
                $videoData['videoURL'] = $video_url;
                $videoData['title'] = $xml->title;
                $videoData['description'] = $xml->content;
                $videoData['thumbnail'] = "http://i.ytimg.com/vi/" . $videoID . "/hqdefault.jpg";
            }
        }
    }

    if (isVimeoVideo($video_url)) {
        $videoID = getVimeoVideoID($video_url);

        if (checkVimeoId($videoID) == 1) {
            $xml = getVimeoVideoDetails($videoID);
            if ($xml) {
                $videoData['videoURL'] = $video_url;
                $videoData['title'] = $xml->video->title;
                $videoData['description'] = $xml->video->description;
                $videoData['thumbnail'] = $xml->video->thumbnail_large;
            }
        }
    }
    
    
    $category = get_category_by_slug(DEDICATION_CATEGORY_SLUG);

    $new_post = array(
        'post_title' => wp_strip_all_tags($title),
        'post_content' => '',
        'post_category' => array($category->term_id), //Dedication
        'post_status' => $post_status,
        'post_type' => 'post'  //'post',page' or use a custom post type if you want to
    );

    $post_id = wp_insert_post($new_post);
    if ($post_id) {
        $link = get_permalink($post_id);

        add_post_meta($post_id, 'ghostpool_dedication_artist', $artist_name);
        add_post_meta($post_id, 'ghostpool_dedication_song', $song_name);
        add_post_meta($post_id, 'ghostpool_dedication_url', $videoData['videoURL']);
                
        if (count($friend_ids) > 1) {
            $friend_info = get_userdata($friend_ids[1]);
            add_post_meta($post_id, 'ghostpool_destination_user_id', $friend_info->ID);
            add_post_meta($post_id, 'ghostpool_destination_user_name', $friend_info->user_login);
            $friend_email = $friend_info->user_email;
        }
        
        if (isset($friend_email) && (is_email($friend_email))) {
            add_post_meta($post_id, 'ghostpool_destination_user_name', $friend_name);
            add_post_meta($post_id, 'ghostpool_destination_user_email', $friend_email);
            add_post_meta($post_id, 'ghostpool_destination_user_country', $friend_country);
        }

        $imageurl = $videoData['thumbnail'];
        $imageurl = stripslashes($imageurl);
        $uploads = wp_upload_dir();

        $filename = wp_unique_filename($uploads['path'], basename($imageurl), $unique_filename_callback = null);
        $wp_filetype = wp_check_filetype($filename, null);
        $fullpathfilename = $uploads['path'] . "/" . $filename;

        try {
            if (!substr_count($wp_filetype['type'], "image")) {
                throw new Exception(basename($imageurl) . ' is not a valid image. ' . $wp_filetype['type'] . '');
            }

            $image_string = fetch_image($imageurl);
            $fileSaved = file_put_contents($uploads['path'] . "/" . $filename, $image_string);
            if (!$fileSaved) {
                throw new Exception("The file cannot be saved.");
            }

            $attachment = array(
                'post_mime_type' => $wp_filetype['type'],
                'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
                'post_content' => '',
                'post_status' => 'inherit',
                'guid' => $uploads['url'] . "/" . $filename
            );
            $attach_id = wp_insert_attachment($attachment, $fullpathfilename, $post_id);
            if (!$attach_id) {
                throw new Exception("Failed to save record into database.");
            }

            $attach_data = wp_generate_attachment_metadata($attach_id, $fullpathfilename);
            wp_update_attachment_metadata($attach_id, $attach_data);
            update_post_meta($post_id, '_thumbnail_id', $attach_id);
        } catch (Exception $e) {
            throw new Exception('<div id="message" class="error"><p>' . $e->getMessage() . '</p></div>');
            return false;
        }

        /*$user_id = $bp->loggedin_user->id;
        $user_link = bp_core_get_userlink($user_id);*/

        do_action( 'bp_dedication_create_new_dedication', $post_id, $friend_email, $bp->loggedin_user->id);

        return true;
    } else {
        return false;
    }
}

?>
