<?php
// Exit if accessed directly
defined( 'ABSPATH' ) or die( 'Cheatin&#8217; uh?' );

function YMVI_import_video(){

    if ( ! wp_verify_nonce( $_POST['nonce'], 'ajax-nonce' ) )
        die ( 'Busted!');
 
    if( !isset( $_POST['video_infos'], $_POST['cat_wp'] ) ){
        WPSCORE()->write_log( 'error','Import video failed (<code>Some parameters are missing!</code>)', __FILE__, __LINE__ );
        wp_send_json( -1 );
        wp_die( 'Some parameters are missing!' );
    }

    //get custom post type
    $custom_post_type   = xbox_get_field_value( 'ymvi-options', 'custom-video-post-type' );
    $custom_status      = xbox_get_field_value( 'ymvi-options', 'default-status' );

    //prepare post data
    $post_args = array(
        'post_author'     => '1',
        'post_status'     => (string) $custom_status != '' ? $custom_status : 'draft',
        'post_type'       => (string) $custom_post_type != '' ? $custom_post_type : 'post',
        'post_title'      => (string) isset( $_POST['video_infos']['title'] ) ? $_POST['video_infos']['title'] : '',
        'post_content'    => (string) isset( $_POST['video_infos']['desc'] ) ? $_POST['video_infos']['desc'] : ''
    );

    //insert post
    $post_id = wp_insert_post( $post_args );

    //add post metas & taxonomies
    if( $post_id ){

        //add metas
        /** add partner id **/
        update_post_meta( $post_id, 'partner',      'youtube' );
        /** add video id **/
        update_post_meta( $post_id, 'video_id',     (string) $_POST['video_infos']['id'] );
        /** add main thumb **/
        update_post_meta( $post_id, 'thumb',        (string) $_POST['video_infos']['thumb_url'] );

        /** add video duration **/
        $custom_duration = xbox_get_field_value( 'ymvi-options', 'custom-duration' );
        update_post_meta($post_id, $custom_duration != '' ? $custom_duration : 'duration', (string) $_POST['video_infos']['duration']);

        /** add embed player **/
        $custom_embed_player = xbox_get_field_value( 'ymvi-options', 'custom-embed-player' );
        update_post_meta($post_id, $custom_embed_player != '' ? $custom_embed_player : 'embed', (string) $_POST['video_infos']['embed']);

        /** add video url **/
        $custom_video_url = xbox_get_field_value( 'ymvi-options', 'custom-video-url' );
        update_post_meta($post_id, $custom_video_url != '' ? $custom_video_url : 'video_url', (string) 'https://www.youtube.com/watch?v=' . $_POST['video_infos']['id']);

        //add category
        $custom_taxonomy = xbox_get_field_value( 'ymvi-options', 'custom-video-categories' );
        wp_set_object_terms( $post_id, intval( $_POST['cat_wp'] ), $custom_taxonomy != '' ? $custom_taxonomy : 'category', false);

        //add features
        $custom_features = xbox_get_field_value( 'ymvi-options', 'custom-features' );
        foreach( $_POST['video_infos']['features'] as $feature_key => $has_feature ){
            if( $has_feature == 'true' )
                add_post_meta($post_id, $custom_features != '' ? $custom_features : 'features', (string) $feature_key);
        }

        //add tags
        $custom_tags = xbox_get_field_value( 'ymvi-options', 'custom-video-tags' );
        if ( $custom_tags == '' ) $custom_tags = 'post_tag';

        wp_set_object_terms( $post_id,  explode(',', str_replace( ';', ',', (string) $_POST['video_infos']['tags'] ) ), YMVI()->call_by_ref( $custom_tags ), false);

        //add actors
        $custom_actors = xbox_get_field_value( 'ymvi-options', 'custom-video-actors' );
        if ( $custom_actors == '' ) $custom_actors = 'actors';
        if( !empty( $_POST['video_infos']['actors'] ) ){
            wp_set_object_terms( $post_id, explode(',', str_replace( ';', ',', (string) $_POST['video_infos']['actors'] ) ), YMVI()->call_by_ref( $custom_actors ), false);
        }

        //downloading main thumb
        if( xbox_get_field_value( 'ymvi-options', 'import-thumb' ) == 'on' ){

            $defaultThumb = (string) $_POST['video_infos']['thumb_url'];

            if( strpos( $defaultThumb, 'http' ) === false ){
                $defaultThumb = 'http:' . $defaultThumb;
            }

            // magic sideload image returns an HTML image, not an ID
            $media = YMVI()->media_sideload_image( $defaultThumb, $post_id, null, 'youtube' );

            // therefore we must find it so we can set it as featured ID
            if(!empty( $media ) && !is_wp_error( $media ) ){
                $args = array(
                    'post_type'         => 'attachment',
                    'posts_per_page'    => -1,
                    'post_status'       => 'any',
                    'post_parent'       => $post_id
                );

                // reference new image to set as featured
                $attachments = get_posts($args);
                if(isset($attachments) && is_array($attachments)){
                    foreach($attachments as $attachment){
                        // grab partner_id of full size images (so no 300x150 nonsense in path)
                        $defaultThumb = wp_get_attachment_image_src($attachment->ID, 'full');
                        // determine if in the $media image we created, the string of the URL exists
                        if(strpos($media, $defaultThumb[0]) !== false){
                            // if so, we found our image. set it as thumbnail
                            set_post_thumbnail($post_id, $attachment->ID);
                            // only want one image
                            break;
                        }
                    }
                }
            }
        }

        //post format video
        set_post_format( $post_id , 'video');

        $output = $_POST['video_infos']['id'];

    }else{
        $output = -1;
    }

    wp_send_json( $output );

    wp_die();

}
add_action('wp_ajax_YMVI_import_video', 'YMVI_import_video');
