<?php

function AMVG_delete_post( $post_id ){
    $feed_id = get_post_meta( $post_id, 'feed', true );

    if( $feed_id == '' ) return false;

    //delete thumb
    global $_wp_additional_image_sizes;

    $upload_dir = wp_upload_dir();
    
    $attachments = get_children( array(
        'post_type'      => 'attachment',
        'posts_per_page' => -1,
        'post_parent'    => $post_id,
    ) );

    if ( $attachments ) {
        foreach ( (array) $attachments as $attachment ) {
            wp_delete_attachment( $attachment->ID, true );
        }
    }

    //decrement video counter in feed
    $saved_feeds = WPSCORE()->get_product_option( 'AMVG', 'feeds' );

    $saved_feed = AMVG()->get_feed( $feed_id );

    $new_total_videos = 0;

    if( isset( $saved_feed['total_videos'] ) && is_int( $saved_feed['total_videos'] ) )
        AMVG()->update_feed( $feed_id, array( 'total_videos' => intval( $saved_feed['total_videos'] ) - 1 ) );

}

add_action('before_delete_post', 'AMVG_delete_post');

function AMVG_enable_auto_import( $value ){

    wp_clear_scheduled_hook( 'AMVG_update_one_feed' );
    
    if( $value == 'on' ){
        $default_frequency_value = xbox_get_field_value( 'amvg-options', 'amvg-auto-import-frequency' );
        wp_schedule_event(  time(), $default_frequency_value, 'AMVG_update_one_feed' );
    }
}
add_action('xbox_before_save_field_amvg-enable-auto-import', 'AMVG_enable_auto_import');

function AMVG_upate_auto_import_frequency( $frequency_value ){
    if( xbox_get_field_value( 'amvg-options', 'amvg-enable-auto-import' ) == 'on' ){
        wp_clear_scheduled_hook( 'AMVG_update_one_feed' );
        wp_schedule_event(  time(), $frequency_value, 'AMVG_update_one_feed' );
    }
}
add_action('xbox_before_save_field_amvg-auto-import-frequency', 'AMVG_upate_auto_import_frequency');
