<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

/* post type multipurpose elementor blocks
------------------------------------------------------------------------------------------ */
add_action( 'elementor/init', 'fox_elementor_register_multipurpose_blocks', 10 );
function fox_elementor_register_multipurpose_blocks() {
    
    register_post_type( 'fox_block', array(
        'labels' => array(
            'name' => 'FOX Blocks',
            'all_items' => 'FOX Blocks',
            'singular_name' => 'FOX Block',
            
            'add_new' => 'New Block',
            'add_new_item' => 'Add New Block',
            'edit_item' => 'Edit Block',
            'view_item' => 'View Block',
        ),
        'public' => true,
        'publicly_queryable' => true,
        'has_archive' => true,
        'can_export' => true,
        'rewrite' => array( 'slug' => 'fox-block' ),
        'capability_type' => 'post',
        'show_in_rest' => true,
        'hierarchical' => false,
        'exclude_from_search' => true,
        'supports' => [ 'title', 'revisions' ],
        
        'menu_icon' => 'dashicons-layout',
        'menu_position' => 3,

    ) );
    
    
}

/**
 * since 2.0
 */
add_action( 'elementor/init', 'fox_elementor_post_type_support' );
function fox_elementor_post_type_support() {
    add_post_type_support( 'fox_block', 'elementor' );
}

/**
 * template include
 */
add_filter( 'template_include', 'fox_block_the_template', 99 );
function fox_block_the_template( $template ) {
    global $post;
    if ( ! $post || ( 'fox_block' !== get_post_type( $post ) ) ) {
        return $template;
    }

    $file_path = FOX_FRAMEWORK_PATH . 'templates/single.php';
    if ( file_exists( $file_path ) ) {
        return $file_path;
    }
}

/**
 * type
 * removed since 2.0 while It's no real use
 * metaboxes
 */
add_filter( 'fox_metaboxes', 'fox_framework_block_boxes' );
function fox_framework_block_boxes( $metaboxes ) {
    
    $fields = [];
    $fields[] = [
        'id' => 'role',
        'name' => 'This Block Role',
        'type' => 'radio',
        'options' => [
            'general' => 'General purpose',
            'header' => 'Header',
            'footer' => 'Footer',
            'single_template' => 'Single Template',
            'page_template' => 'Page Template',
            'archive_template' => 'Archive Template',
        ],
        'std' => 'general',
        'tab' => 'general',
    ];
    
    $metaboxes[ 'block-settings' ] = array (

        'id' => 'post-settings',
        'screen' => array( 'fox_block' ),
        'title' => 'FOX Block Settings',
        'context' => 'advanced',
        'tabs' => [
            'general' => 'Settings',
        ],
        'fields' => $fields,

    );
    
    return $metaboxes;
    
}

if ( ! function_exists( 'fox_get_block_list' ) ) :
/**
 * since .40
 * RETURN list of blocks id => name
 */
function fox_get_block_list( $type = '' ) {
    
    $blocks_dropdown = [];
    $query_args = [
        'post_type' => 'fox_block',
        'posts_per_page' => 100,
        'orderby' => 'name',
        'order' => 'ASC',
    ];
    /*
    we drop $type since v2.0
    if ( $type ) {
        $query_args[ 'meta_key' ] = '_wi_type';
        $query_args[ 'meta_value' ] = $type;
    }
    */
    $get_list = get_posts( $query_args );
    foreach( $get_list as $p ) {
        $blocks_dropdown[ $p->ID ] = strip_tags( $p->post_title );
    }
    
    return $blocks_dropdown;
    
}
endif;

if ( ! function_exists( 'fox_get_block' ) ) :
/**
 * RETURN void
 */
function fox_get_block( $pid ) {
    
    /**
     * 1.7.0.1
     * make FOX Block compatible with WMPL
     */
    $pid = apply_filters( 'wpml_object_id', $pid, 'post' );
    
    if ( FALSE === get_post_status( $pid ) ) {
        return;
    }
    
    return \Elementor\Plugin::$instance->frontend->get_builder_content_for_display( $pid, false );
    
    /*
    
    $p = new \Elementor\Core\Files\CSS\Post( $pid );
    $meta = $p->get_meta();
    
    ob_start();
    if ( false && $p::CSS_STATUS_FILE === $meta[ 'status' ] ) : ?>
        <link rel="stylesheet" id="elementor-post-<?php echo esc_attr( $pid ); ?>-css" href="<?php echo esc_url( $p->get_url() ); ?>" type="text/css" media="all">
    <?php else :
        echo '<style class="elementor-inline-css">html{display:block;}' . $p->get_content() . '</style>';
        \Elementor\Plugin::$instance->frontend->print_fonts_links();
    endif;
    
    echo \Elementor\Plugin::$instance->frontend->get_builder_content_for_display( $pid, false );
    
    wp_deregister_style( 'elementor-post-' . $pid );
    wp_dequeue_style( 'elementor-post-' . $pid );
    
    $result = ob_get_clean();
    
    echo $result;
    */
    
}
endif;

if ( ! function_exists( 'fox_block' ) ) :
function fox_block( $pid ) {
    echo fox_get_block( $pid );
}
endif;

add_action( 'wp_enqueue_scripts', 'fox_block_scripts' );
/**
 * since Framework 2.0
 * we enqueue necessary scripts in the header because by default, it's included in the footer and it goes wrong
 */
function fox_block_scripts() {
    
    if ( ! class_exists( '\Elementor\Core\Files\CSS\Post' ) ) {
        return;
    }
    $ids = [];
    
    /**
     * header builder
     */
    $ids[] = fox_framework_header_block_id();
    
    /**
     * footer builder
     */
    $ids[] = fox_framework_footer_block_id();
    
    /**
     * single tempalte
     */
    if ( is_single() ) {
        $ids[] = fox_framework_single_block_id();    
    }
    
    /**
     * page tempalte
     */
    if ( is_page() ) {
        $ids[] = fox_framework_page_block_id();    
    }
    
    /**
     * archive tempalte
     */
    if ( is_home() || is_archive() || is_404() || is_search() ) {
        $ids[] = fox_framework_archive_block_id();   
    }
     
    
    if ( empty( $ids ) ) {
        return;
    }
    
    $ids = fox_recursively_get_block_ids( $ids );
    
    $elementor = \Elementor\Plugin::instance();
    $elementor->frontend->enqueue_styles();
    
    foreach ( $ids as $pid ) {
        
        if ( ! $pid ) {
            continue;
        }
        
        $pid = apply_filters( 'wpml_object_id', $pid, 'post' );
        
        if ( FALSE === get_post_status( $pid ) ) {
            continue;
        }
        
        $css_file = new \Elementor\Core\Files\CSS\Post( $pid );
        $css_file->enqueue();
        
    }
    
}

/**
 * $arr is the data of Elementor
 */
function fox_recursively_get_block_ids_from_array( $arr, $elementor = null ) {
    
    $result = [];
    foreach ( $arr as $k => $v ) {
        if ( 'popup_id' == $k ) {
            $result[] = absint( $v );
        } else {
            if ( is_array( $v ) ) {
                $result = array_merge( $result, fox_recursively_get_block_ids_from_array( $v ) );
            }
        }
    }
    return $result;
}

// RETURN array
function fox_block_get_new_ids( $id, $elementor = null ) {
    
    if ( ! $elementor ) {
        $elementor = \Elementor\Plugin::instance();
    }
    if ( ! $elementor->documents ) {
        return [];
    }
    $element = $elementor->documents->get( $id );
    if ( ! $element ) {
        return [];
    }
    $data = $element->get_elements_data();
    
    return fox_recursively_get_block_ids_from_array( $data );
    
}

function fox_recursively_get_block_ids( $torun, $elementor = null ) {
    
    $result = $torun;
    $torun = $result;
    
    $safe_logic = 4;
    $count = 0;
        
    while ( ! empty( $torun ) ) {
        $count += 1;
        if ( $count > $safe_logic ) {
            break;
        }
        foreach ( $torun as $torun_id ) {
            
            $new_set = [];
            if ( $count > $safe_logic ) {
                break;
            }
            if ( ! $torun_id ) {
                continue;
            }
            
            $new_ids= fox_block_get_new_ids( $torun_id, $elementor );
            
            $new_set = array_diff( $new_ids, $result );
            $result = array_merge( $result, $new_ids );
            
            $torun = $new_set;
        }
    }
    
    return $result;
    
}

/**
 * return ID/false
 */
function fox_framework_single_block_id() {
    
    /**
     * logic 1: if _wi_style has been set and works ok
     */
    $style = get_post_meta( get_the_ID(), '_wi_style', true );
    if ( ! is_numeric( $style ) && $style !='' && $style != '1b' ) {
        // it means this is Elementor FOX block
        $block_id = null;
        $try_get = new WP_Query([
            'posts_per_page' => 1,
            'name'        => $style,
            'post_type'   => 'fox_block',
            'post_status' => 'any',
        ]);
        if ( $try_get->have_posts() ) {
            while ( $try_get->have_posts() ) {
                $try_get->the_post();
                $block_id = get_the_ID();
            }
        }
        wp_reset_query();
        return $block_id;
    }
    
    /**
     * if it has custom predefined layout
     */
    if ( get_post_meta( get_the_ID(), '_wi_style', true ) ) {
        return;
    }
    
    $local_block_id = get_post_meta( get_the_ID(), '_wi_single_template', true );
    $global_block_id = get_theme_mod( 'wi_single_template' );
    $layout_type = get_theme_mod( 'wi_single_layout_type', 'classic' );
    
    $final_block_id = false;
    
    if ( $local_block_id ) {
        $final_block_id = $local_block_id;
    }
    if ( ! $final_block_id && 'classic' != $layout_type ) {
        $final_block_id = $global_block_id;
    }
    
    return apply_filters( 'fox_check_block_exists', $final_block_id );
    
}

/**
 * return ID/false
 */
function fox_framework_page_block_id() {
    
    /**
     * if it has custom predefined layout
     */
    if ( get_post_meta( get_the_ID(), '_wi_style', true ) ) {
        return;
    }
    
    $local_block_id = get_post_meta( get_the_ID(), '_wi_page_template', true );
    $global_block_id = get_theme_mod( 'wi_page_template' );
    $layout_type = get_theme_mod( 'wi_page_layout_type', 'classic' );
    
    $final_block_id = false;
    
    if ( $local_block_id ) {
        $final_block_id = $local_block_id;
    }
    if ( ! $final_block_id && 'classic' != $layout_type ) {
        $final_block_id = $global_block_id;
    }
    
    return apply_filters( 'fox_check_block_exists', $final_block_id );
    
}

/**
 * return ID/false
 */
function fox_framework_archive_block_id() {
 
    $layout_type = get_theme_mod( 'wi_archive_layout_type', 'classic' );
    $global_block_id = false;
    
    if ( is_category() )  {
        $global_block_id = get_theme_mod( 'wi_category_template' );
    } elseif ( is_tag() ) {
        $global_block_id = get_theme_mod( 'wi_tag_template' );
    } elseif ( is_author() ) {
        $global_block_id = get_theme_mod( 'wi_author_template' );
    } elseif ( is_search() ) {
        $global_block_id = get_theme_mod( 'wi_search_template' );
    } elseif ( is_404() ) {
        $global_block_id = get_theme_mod( 'wi_404_template' );
    }
    
    // fallback
    if ( ! $global_block_id ) {
        $global_block_id = get_theme_mod( 'wi_archive_template' );
    }
    
    $final_block_id = false;
    if ( ! $final_block_id && 'classic' != $layout_type ) {
        $final_block_id = $global_block_id;
    }
    
    return apply_filters( 'fox_check_block_exists', $final_block_id );
    
}

function fox_framework_header_block_id() {
    
    $layout_type = get_theme_mod( 'wi_header_builder', 'false' );
    $local_block_id = false;
    $global_block_id = false;
    
    if ( is_singular() ) {
        $local_block_id = get_post_meta( get_the_ID(), '_wi_header_template', true );
    }
    
    if ( is_single() ) {
        $global_block_id = get_theme_mod( 'wi_single_header_template' );
    } elseif ( is_page() )  {
        $global_block_id = get_theme_mod( 'wi_page_header_template' );
    } elseif ( is_category() )  {
        $global_block_id = get_theme_mod( 'wi_category_header_template' );
    } elseif ( is_tag() ) {
        $global_block_id = get_theme_mod( 'wi_tag_header_template' );
    } elseif ( is_author() ) {
        $global_block_id = get_theme_mod( 'wi_author_header_template' );
    } elseif ( is_search() ) {
        $global_block_id = get_theme_mod( 'wi_search_header_template' );
    } elseif ( is_404() ) {
        $global_block_id = get_theme_mod( 'wi_404_header_template' );
    }
    
    // fallback
    if ( ! $global_block_id ) {
        $global_block_id = get_theme_mod( 'wi_header_elementor' );
    }
    
    // $local_block_id
    // regardless the layout type
    if ( $local_block_id ) {
        return apply_filters( 'fox_check_block_exists', $local_block_id );
    }
    
    if ( 'elementor' != $layout_type ) {
        return;
    }
    
    return apply_filters( 'fox_check_block_exists', $global_block_id );
    
}

function fox_framework_footer_block_id() {
    
    $layout_type = get_theme_mod( 'wi_footer_builder', 'false' );
    $local_block_id = false;
    $global_block_id = false;
    
    if ( is_singular() ) {
        $local_block_id = get_post_meta( get_the_ID(), '_wi_footer_template', true );
    }
    
    if ( is_single() ) {
        $global_block_id = get_theme_mod( 'wi_single_footer_template' );
    } elseif ( is_page() )  {
        $global_block_id = get_theme_mod( 'wi_page_footer_template' );
    } elseif ( is_category() )  {
        $global_block_id = get_theme_mod( 'wi_category_footer_template' );
    } elseif ( is_tag() ) {
        $global_block_id = get_theme_mod( 'wi_tag_footer_template' );
    } elseif ( is_author() ) {
        $global_block_id = get_theme_mod( 'wi_author_footer_template' );
    } elseif ( is_search() ) {
        $global_block_id = get_theme_mod( 'wi_search_footer_template' );
    } elseif ( is_404() ) {
        $global_block_id = get_theme_mod( 'wi_404_footer_template' );
    }
    
    // fallback
    if ( ! $global_block_id ) {
        $global_block_id = get_theme_mod( 'wi_footer_block_id' );
    }
    
    // $local_block_id
    // regardless the layout type
    if ( $local_block_id ) {
        return apply_filters( 'fox_check_block_exists', $local_block_id );
    }
    
    if ( 'true' != $layout_type ) {
        return;
    }
    
    return apply_filters( 'fox_check_block_exists', $global_block_id );
    
}

add_filter( 'fox_check_block_exists', 'fox_check_block_exists' );
function fox_check_block_exists( $block_id ) {
    if ( false !== get_post_status( $block_id ) ) {
        return $block_id;
    }
    return;
}

/* fox_block support
------------------------------------------------------------------------ */
add_action( 'init', 'fox_update_elementor_cpt_support', 1 ); // make sure it's always being supported
function fox_update_elementor_cpt_support() {
    $cpt_support = get_option( 'elementor_cpt_support', null );
    if ( null === $cpt_support ) {
        $cpt_support = [ 'post', 'page', 'fox_block' ];
        update_option( 'elementor_cpt_support', $cpt_support );
    } elseif ( is_array( $cpt_support ) ) {
        if ( ! in_array(  'fox_block', $cpt_support ) ) {
            $cpt_support[] = 'fox_block';
            update_option( 'elementor_cpt_support', $cpt_support );
        }
    }
}