<?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']);
    } else {
        return false;
    }

    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'])) {
        if ($_POST['private']) {
            $post_status = 'private';
        } else {
            $post_status = 'publish';
        }
    } else {
        $post_status = 'publish';
    }

    $videoData = array();
    $videoID = getVideoID($video_url);
        
    if (checkYoutubeId($videoID) == 1) {
        $xml = getVideoDetails($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";
        }
    }

    $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']);
                
        $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);
        add_post_meta($post_id, 'ghostpool_destination_user_email', $friend_info->user_email);

        $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);

        /* bp_dedication_record_activity(array(
          'type' => 'accepted_terms',
          'action' => apply_filters('bp_dedication_create_new_dedication_activity_action',
          sprintf(__('%s sent a new dedication %s!', 'bp-dedication'), $user_link, $link), $user_id, ),
          )); */

        /* See bp_example_reject_terms() for an explanation of deleting activity items */
//	if ( function_exists( 'bp_activity_delete') )
//		bp_activity_delete( array( 'type' => 'rejected_terms', 'user_id' => $bp->loggedin_user->id ) );

        /* Add a do_action here so other plugins can hook in */
        do_action('bp_dedication_create_new_dedication', $bp->loggedin_user->id);

        /*         * *
         * You'd want to do something here, like set a flag in the database, or set usermeta.
         * just for the sake of the demo we're going to return true.
         */

        return true;
    }
}

?>
