<?php


/////////////////////////////////////////////////////////////////////
//region Recipes Custom Post Type with Meta Boxes
add_action('init', 'apicius_register_cpt_recipe');

function apicius_register_cpt_recipe() {

    $labels = array(
        'name'               => _x('Recipes', 'recipe'),
        'singular_name'      => _x('Recipe', 'recipe'),
        'add_new'            => _x('Add New', 'recipe'),
        'add_new_item'       => _x('Add New Recipe', 'recipe'),
        'edit_item'          => _x('Edit Recipe', 'recipe'),
        'new_item'           => _x('New Recipe', 'recipe'),
        'view_item'          => _x('View Recipe', 'recipe'),
        'search_items'       => _x('Search Recipes', 'recipe'),
        'not_found'          => _x('No recipe found', 'recipe'),
        'not_found_in_trash' => _x('No recipe found in Trash', 'recipe'),
        'parent_item_colon'  => _x('Parent Recipe:', 'recipe'),
        'menu_name'          => _x('Recipes', 'recipe'),
    );

    $args = array(
        'labels'       => $labels,
        'hierarchical' => false,

        'supports'            => array('title', 'thumbnail'),
        //'taxonomies' => array( 'post_tag' ),
        'public'              => true,
        'show_ui'             => true,
        'show_in_menu'        => true,
        'menu_position'       => 3,
        'menu_icon'           => plugins_url('/images/recipes.png', __FILE__),
        'show_in_nav_menus'   => true,
        'publicly_queryable'  => true,
        'exclude_from_search' => false,
        'has_archive'         => true,
        'query_var'           => true,
        'can_export'          => true,
        'rewrite'             => true,
        'capability_type'     => 'post'
    );

    register_post_type('recipe', $args);
}

// recipe custom meta box
add_action('admin_init', 'apicius_register_recipe_meta_boxes');

function apicius_register_recipe_meta_boxes() {
    // Check if plugin is activated or included in theme
    if (!class_exists('RW_Meta_Box')) {
        return;
    }
    $prefix = 'recipe_';

    // prep & cook times
    $meta_boxes[] = array(
        'id'       => 'times',
        'title'    => 'Prep & Cook Time',
        'pages'    => array('recipe'),
        'context'  => 'normal',
        'priority' => 'high',
        'include'  => array(
            'custom' => 'apicius_recipe_include_field'
        ),
        'fields'   => array(
            array(
                'name' => 'Prep Time (in minutes)',
                'id'   => $prefix.'preptime',
                'type' => 'number'
            ),
            array(
                'name' => 'Cook Time (in minutes)',
                'id'   => $prefix.'cooktime',
                'type' => 'number'
            )
        )
    );

    // servings
    $meta_boxes[] = array(
        'id'       => 'servings',
        'title'    => 'Servings Info',
        'pages'    => array('recipe'),
        'context'  => 'normal',
        'priority' => 'high',
        'include'  => array(
            'custom' => 'apicius_recipe_include_field'
        ),
        'fields'   => array(
            array(
                'name' => 'Serving Size',
                'id'   => $prefix.'serving_size',
                'type' => 'text',
            ),
            array(
                'name' => 'Servings',
                'id'   => $prefix.'servings',
                'type' => 'text',
            )
        )
    );

    // description
    $meta_boxes[] = array(
        'id'       => 'description',
        'title'    => 'Description',
        'pages'    => array('recipe'),
        'context'  => 'normal',
        'priority' => 'high',
        'include'  => array(
            'custom' => 'apicius_recipe_include_field'
        ),
        'fields'   => array(
            array(
                'id'   => $prefix.'description',
                'type' => 'wysiwyg',
            )
        )
    );

    // ingredients
    $meta_boxes[] = array(
        'id'       => 'ingredients',
        'title'    => 'Ingredients',
        'pages'    => array('recipe'),
        'context'  => 'normal',
        'priority' => 'high',
        'fields'   => array(
            array(
                'id'         => $prefix.'ingredients_group',
                'type'       => 'group',
                'clone'      => true,
                'sort_clone' => true,
                // List of sub-fields
                'fields'     => array(
                    array(
                        'name' => 'Ingredients Section Name',
                        'id'   => $prefix.'ing_section_name',
                        'type' => 'text',
                    ),
                    array(
                        'name'       => 'Ingredients',
                        'id'         => $prefix.'ing_list',
                        'type'       => 'text',
                        'clone'      => true,
                        'sort_clone' => true,
                    ),
                ),
            )
        )
    );

    // directions
    $meta_boxes[] = array(
        'id'       => 'directions',
        'title'    => 'Directions',
        'pages'    => array('recipe'),
        'context'  => 'normal',
        'priority' => 'high',
        'fields'   => array(
            array(
                'id'         => $prefix.'directions_group',
                'type'       => 'group',
                'clone'      => true,
                'sort_clone' => true,
                // List of sub-fields
                'fields'     => array(
                    array(
                        'name' => 'Directions Section Name (optional)',
                        'id'   => $prefix.'dir_section_name',
                        'type' => 'text',
                    ),
                    array(
                        'name' => 'Directions',
                        'id'   => $prefix.'directions',
                        'type' => 'wysiwyg',
                    ),
                ),
            )
        )
    );

    // products used
    $meta_boxes[] = array(
        'id'       => 'products',
        'title'    => 'Product(s) Used',
        'pages'    => array('recipe'),
        'context'  => 'normal',
        'priority' => 'high',
        'fields'   => array(
            array(
                'id'         => $prefix.'products',
                'type'       => 'post',
                'post_type'  => 'product',
                'field_type' => 'checkbox_list',
                'query_args' => array(
                    'post_type'      => 'product',
                    'posts_per_page' => '-1',
                    'orderby'        => 'title',
                    'order'          => 'ASC'
                )
            )
        )
    );

    // nutritional information
    $meta_boxes[] = array(
        'id'       => 'nutrition',
        'title'    => ' Nutritional Information',
        'pages'    => array('recipe'),
        'context'  => 'normal',
        'priority' => 'high',
        'include'  => array(
            'custom' => 'apicius_recipe_include_field'
        ),
        'fields'   => array(
            array(
                'name' => 'Calories',
                'id'   => $prefix.'cal',
                'type' => 'text',
            ),
            array(
                'name' => 'Fat Calories',
                'id'   => $prefix.'fatcal',
                'type' => 'text',
            ),
            array(
                'name' => 'Total Fat',
                'id'   => $prefix.'fat',
                'type' => 'text',
            ),
            array(
                'name' => 'Total Fat % DV',
                'id'   => $prefix.'fat_dv',
                'type' => 'text',
            ),
            array(
                'name' => 'Sat. Fat',
                'id'   => $prefix.'satfat',
                'type' => 'text',
            ),
            array(
                'name' => 'Sat. Fat % DV',
                'id'   => $prefix.'satfat_dv',
                'type' => 'text',
            ),
            array(
                'name' => 'Cholesterol',
                'id'   => $prefix.'chol',
                'type' => 'text',
            ),
            array(
                'name' => 'Cholesterol % DV',
                'id'   => $prefix.'chol_dv',
                'type' => 'text',
            ),
            array(
                'name' => 'Sodium',
                'id'   => $prefix.'sodium',
                'type' => 'text',
            ),
            array(
                'name' => 'Sodium % DV',
                'id'   => $prefix.'sodium_dv',
                'type' => 'text',
            ),
            array(
                'name' => 'Total Carb.',
                'id'   => $prefix.'carbs',
                'type' => 'text',
            ),
            array(
                'name' => 'Total Carb. % DV',
                'id'   => $prefix.'carbs_dv',
                'type' => 'text',
            ),
            array(
                'name' => 'Dietary Fibers',
                'id'   => $prefix.'fiber',
                'type' => 'text',
            ),
            array(
                'name' => 'Sugars',
                'id'   => $prefix.'sugar',
                'type' => 'text',
            ),
            array(
                'name' => 'Protein',
                'id'   => $prefix.'protein',
                'type' => 'text',
            ),
            array(
                'name' => 'Vitamin A %',
                'id'   => $prefix.'vitA',
                'type' => 'text',
            ),
            array(
                'name' => 'Vitamin C %',
                'id'   => $prefix.'vitC',
                'type' => 'text',
            ),
            array(
                'name' => 'Calcium %',
                'id'   => $prefix.'calcium',
                'type' => 'text',
            ),
            array(
                'name' => 'Iron %',
                'id'   => $prefix.'iron',
                'type' => 'text',
            )
        )
    );

    foreach ($meta_boxes as $meta_box) {
        new RW_Meta_Box($meta_box);
    }
}


// give them a custom taxonomy, to make categories, but locked down to only this post type
add_action('init', 'apicius_build_rec_taxonomies', 0);
function apicius_build_rec_taxonomies() {
    register_taxonomy(
        'recipe_type',
        'recipe',  // this is the custom post type(s) I want to use this taxonomy for
        array(
            'hierarchical'      => true,
            'label'             => 'Recipe Type',
            'query_var'         => true,
            'rewrite'           => true,
            'show_in_nav_menus' => true,
            'show_admin_column' => true
        )
    );
}

register_taxonomy_for_object_type('recipe_type', 'recipe');


// change the number of posts per page for recipes cpt
function apicius_rec_quant($query) {
    if (!is_admin() && is_post_type_archive('recipe')) {
        $query->set('posts_per_page', 500);

        return;
    }
}

add_action('pre_get_posts', 'apicius_rec_quant', 1);


// function which tests whether or not to show a specific meta box element in the recipe admin
function apicius_recipe_include_field($meta_box) {
    // get settings for using fields
    $settings = get_option('apicius_recipe');
    $box_slug = $meta_box['id'];

    if (isset($settings[ 'use_'.$box_slug ]) && (($settings[ 'use_'.$box_slug ] === "1") || ($settings[ 'use_'.$box_slug ] === 1))) {
        return true;
    }

    return false;
}

//endregion


//region Intuitive Custom Post Order plugin is being stubborn about order
add_filter('option_active_plugins', 'apicius_disable_intuitive_order_plugin');
function apicius_disable_intuitive_order_plugin($plugins) {
    $force_order_posttypes = array('recipe');
    if (!is_admin() && isset($_GET['post_type']) && (in_array($_GET['post_type'], $force_order_posttypes))) {
        $key = array_search('intuitive-custom-post-order/intuitive-custom-post-order.php', $plugins);
        if (false !== $key) {
            unset($plugins[ $key ]);
        }
    }

    return $plugins;
}

//endregion


/////////////////////////////////////////////////////////////////////
//region shortcode for use in WYSIWYG content for displaying recipes archive
function apicius_archive($atts, $content = null) {
    wp_enqueue_script('imagesLoaded');
    wp_enqueue_script('isotope');
    wp_enqueue_script('apicius-recipes-js');
    wp_enqueue_script('apicius-nice-select-js');

    wp_enqueue_style('apicius-bs-css');
    wp_enqueue_style('apicius-css');
    wp_enqueue_style('apicius-nice-select-css');

    global $post;

    $apicius_settings   = get_option('apicius_recipe');
    $apicius_appearance = get_option('apicius_appearance');

    //region styles
    $apicius_overall = '';

    $filter_styles = '';

    $title_styles = '';

    $tile_styles = '';

    if (!empty($apicius_appearance['apicius_bg'])) {
        $apicius_overall .= 'background-color: '.$apicius_appearance['apicius_bg'].'; ';
    }
    if (!empty($apicius_appearance['text_color'])) {
        $apicius_overall .= 'color: '.$apicius_appearance['text_color'].'; ';
    }


    if (!empty($apicius_appearance['filter_bg'])) {
        $filter_styles .= 'background-color: '.$apicius_appearance['filter_bg'].'; ';
    }
    if (!empty($apicius_appearance['filter_text'])) {
        $filter_styles .= 'color: '.$apicius_appearance['filter_text'].'; ';
    }
    if (!empty($apicius_appearance['filter_border'])) {
        $filter_styles .= 'border-color: '.$apicius_appearance['filter_border'].'; ';
    }


    if (!empty($apicius_appearance['tile_border'])) {
        $filter_styles .= 'border: 1px solid '.$apicius_appearance['tile_border'].'; ';
    }


    if (!empty($apicius_appearance['tile_title_bg'])) {
        $title_styles .= 'background-color: '.$apicius_appearance['tile_title_bg'].'; ';
    }
    if (!empty($apicius_appearance['tile_title_text'])) {
        $title_styles .= 'color: '.$apicius_appearance['tile_title_text'].'; ';
    }
    if (!empty($apicius_appearance['tile_title_border'])) {
        $title_styles .= 'border-color: '.$apicius_appearance['tile_title_border'].'; ';
    }
    //endregion

    //region get the recipes real quick, just their IDs so I can get the products used in them
    $productsUsed = array();

    $recipe_query = new WP_Query(array(
        'post_type'      => 'recipe',
        'posts_per_page' => - 1,
        'fields'         => 'ids'
    ));
    if ($recipe_query->have_posts()) {
        while ($recipe_query->have_posts()) {
            $recipe_query->the_post();
            $new_addition = rwmb_meta('recipe_products', 'type=checkbox_list');
            if (!empty($new_addition)) {
                $productsUsed = array_merge($productsUsed, $new_addition);
            }
        }
    }
    wp_reset_postdata();
    //endregion


    //region get list of products for the "filter by product" dropdown
    if (!empty($apicius_settings['exclude_prodcats'])) {
        $args = array(
            'post_type'      => 'product',
            'posts_per_page' => - 1,
            'orderby'        => 'title',
            'order'          => 'ASC',
            'include'        => $productsUsed,
            'tax_query'      => array(
                array(
                    'taxonomy' => 'product_cat',
                    'operator' => 'NOT IN',
                    'terms'    => $apicius_settings['exclude_prodcats']
                )
            )

        );
    } else {
        $args = array(
            'post_type'      => 'product',
            'posts_per_page' => - 1,
            'orderby'        => 'title',
            'order'          => 'ASC',
            'include'        => $productsUsed
        );
    }
    $products = get_posts($args);
    //endregion


    ob_start();
//    echo spitio_prettify($apicius_settings);
    ?>
	<div id="apicius" data-apicius-version="<?=APICIUS_VERSION?>" style="<?=$apicius_overall?>">
		<div id="recipes_list" class="container-fluid">
			<div id="recipes_filters" class="row"
                 <?php if ($apicius_settings['use_filter_hash'] === "1") { ?>data-usefilterhash="please"<?php } ?>>


                <?php //region recipe search ?>
                <?php if ($apicius_settings['show_recipe_search_box'] === "1") { ?>
					<div id="apicius_recipe_search_box" class="col-sm-6 col-md-4">
						<h3>Recipe Search</h3>
						<form role="search" method="get" id="searchform" action="<?php echo home_url('/'); ?>">
							<input type="hidden" name="post_type" value="recipe" />
							<input type="text" name="s" id="s" /> <input id="searchsubmit" type="submit" name="submit"
							                                             value="Search" />
						</form>
					</div>
                <?php } ?>
                <?php //endregion ?>

                <?php //region product category dropdown ?>
                <?php if ($apicius_settings['show_prod_cat_dropdown'] === "1") { ?>
					<div id="apicius_recipe_filter_prod_cat" class="col-sm-6 col-md-4">
						<h3>Product Category</h3>
						<select id="recipe_product_cat" name="recipe_product_cat" class="filter-dropdown"
						        style="<?=$filter_styles?>">
							<option value="">Any Product Category</option>
                            <?php
                            $cats = get_terms(array('taxonomy' => 'product_cat'));

                            foreach ($cats as $cat) {
                                if (!in_array($cat->term_id, $apicius_settings['exclude_prodcats'])) {

                                    echo '<option value=".prodcat-'.$cat->slug.'"';
                                    if (isset($_GET['category'])) {
                                        if ($_GET['category'] == $cat->slug) {
                                            echo ' selected="selected" ';
                                        }
                                    }
                                    echo '>'.$cat->name.'</option>'.PHP_EOL;
                                }
                            }
                            ?>
						</select>
					</div>
                <?php } ?>
                <?php //endregion ?>

                <?php //region product dropdown ?>
                <?php if ($apicius_settings['show_product_filter_dropdown'] === "1") { ?>
					<div id="apicius_recipe_filter_product" class="col-sm-6 col-md-4">
						<h3>Product Used</h3>
						<select id="recipe_product" name="recipe_product" class="filter-dropdown"
						        style="<?=$filter_styles?>">
							<option value="">Any Product</option>
                            <?php
                            foreach ($products as $prod) {
                                echo '<option value=".prod-'.basename($prod->post_name).'">'.$prod->post_title.'</option>'.PHP_EOL;
                            }
                            ?>
						</select>
						<div id="view_all" style="<?=$filter_styles?>">View All</div>
					</div>
                <?php } ?>
                <?php //endregion ?>

                <?php //region recipe type TILES ?>
                <?php if ($apicius_settings['show_recipe_cat_filter_tiles'] === "1") { ?>
					<div id="apicius_recipe_filter_recipe_type" class="col-sm-6 col-md-4">
						<h3>Recipe Type</h3>
						<div id="recipe_types" class="clearfix">
                            <?php
                            // get all recipe types (with posts in them)
                            $all_types = get_terms('recipe_type', array(
                                'orderby' => 'name'
                            ));
                            foreach ($all_types as $tag) {
                                echo '<div class="type-tile off" data-tagslug=".type-'.$tag->slug.'" style="'.$filter_styles.'">'.$tag->name.'</div>'.PHP_EOL;
                            }
                            ?>
						</div>
					</div>
                <?php } ?>
                <?php //endregion ?>

                <?php //region recipe type DROPDOWN ?>
                <?php if ($apicius_settings['show_recipe_cat_filter_dropdown'] === "1") { ?>
					<div id="apicius_recipe_filter_recipe_type_select" class="col-sm-6 col-md-4">
						<h3>Recipe Type</h3>
						<select id="recipe_type_select" name="recipe_type_select" class="filter-dropdown"
						        style="<?=$filter_styles?>">
							<option value="">Any Recipe Type</option>
                            <?php
                            // get all recipe types (with posts in them)
                            $all_types = get_terms('recipe_type', array(
                                'orderby' => 'name'
                            ));
                            foreach ($all_types as $tag) {
                                echo '<option value=".type-'.$tag->slug.'-dropdown">'.$tag->name.'</option>'.PHP_EOL;
                            }
                            ?>
						</select>
					</div>
                <?php } ?>
                <?php //endregion ?>
			</div><!-- / recipe filters -->

			<div id="recipes_header" class="row">
                <?php if ($apicius_settings['show_results_count'] === "1") { ?>
					<div id="results_count" class="col-xs-12"></div>
                <?php } ?>

				<!--<div class="col-xs-12"><h2>Recipes</h2></div>-->
			</div>

            <?php //region pagination ?>
            <?php if ($apicius_settings['show_pagination_above'] === "1" && $apicius_settings['pagination_item_count'] > 0) { ?>
				<div id="recipes_pagination_above" class="recipes_pagination row"
				     data-items-count="<?=$apicius_settings['pagination_item_count']?>"
				     data-collapse="<?=$apicius_settings['collapse_pagination'] === '1' ? 'true' : 'false'?>">
					<div></div>
				</div>
            <?php } ?>
            <?php //endregion ?>

            <?php /*
			<?php //region content above recipes list ?>
			<div id="apicius_before_recipes_content" class="row">
                <?=$apicius_settings['recipes_above_stuff']?>
			</div>
			<?php //endregion ?>
            */ ?>

			<div id="recipe_tiles" class="row">
                <?php
                // get recipes
                $recQuery = new WP_Query(array(
                    'post_type'      => 'recipe',
                    'posts_per_page' => '-1'
                ));


                if ($recQuery->have_posts()) {
                    while ($recQuery->have_posts()) {
                        $recQuery->the_post();

                        $pic = wp_get_attachment_image_src(get_post_thumbnail_id(), 'medium')[0];

                        if (!$pic) {
                            if (!empty($apicius_settings['ph_recipe'])) {
                                $pic = wp_get_attachment_image_src($apicius_settings['ph_recipe'][0])[0];
                            } else {
                                $pic = plugins_url('/images/ph_recipe.jpg', __FILE__);
                            }
                        }

                        //region products this recipe uses
                        $products_list = rwmb_meta('recipe_products', 'type=checkbox_list', $post->ID);

                        $rec_types = get_the_terms($post, 'recipe_type');

                        $tag_classes = '';
                        // this recipe's types
                        if (!empty($rec_types)) {

                            foreach ($rec_types as $tag) {
                                $tag_classes .= 'type-'.$tag->slug.' ';
                            }
                        }

                        // this only gets set to true if all of its products is in the "exclude" categories chosen in the admin
                        $skip = false;
                        // this overrides a true $skip - if there are any products in this recipe that are NOT in the
                        $skip_override = false;
                        // excluded categories, show the recipe
                        // go through each product in this recipe and add its slug and its categories
                        foreach ($products_list as $productID) {
                            // product slug
                            $tag_classes .= 'prod-'.apicius_the_slug($productID).' ';

                            // product categories
                            $prodcats = get_the_terms($productID, 'product_cat');
                            foreach ($prodcats as $cat) {
                                $tag_classes .= 'prodcat-'.$cat->slug.' ';

                                if (!empty($apicius_settings['exclude_prodcats'])) {
                                    if (in_array($cat->term_id, $apicius_settings['exclude_prodcats'])) {
                                        $skip = true;
                                    } else {
                                        $skip_override = true;
                                    }
                                }
                            }
                            if ($skip_override) {
                                $skip = false;
                            }
                        }
                        if (!$skip) {
                            ?>
							<div class="recipe-tile col-xs-6 col-sm-4 <?=$tag_classes?>" style="<?=$tile_styles?>">
								<div class="stretcher"></div>
								<a class="stretched-interior" href="<?php the_permalink(); ?>"
								   style="background-image: url(<?=$pic?>);">
									<span class="recipe-title" style="<?=$title_styles?>"><?=$post->post_title?></span>
								</a>
							</div>
                            <?php
                        }
                    }
                }
                // Restore original Post Data
                wp_reset_postdata();
                ?>
			</div><!-- /container -->
            <?php /*
			<div id="apicius_middle_recipes_content" style="display: none;">
                <?=$apicius_settings['recipes_middle_stuff']?>
			</div>
            */ ?>

            <?php //region pagination ?>
            <?php if ($apicius_settings['show_pagination_below'] === "1" && $apicius_settings['pagination_item_count'] > 0) { ?>
				<div id="recipes_pagination_below" class="recipes_pagination row"
				     data-items-count="<?=$apicius_settings['pagination_item_count']?>"
				     data-collapse="<?=$apicius_settings['collapse_pagination'] === '1' ? 'true' : 'false'?>">
					<div></div>
				</div>
            <?php } ?>
            <?php //endregion ?>


            <?php //region content above recipes list ?>
            <?php /*
			<div id="apicius_below_recipes_content" class="row">
                <?=$apicius_settings['recipes_below_stuff']?>
			</div>
            <?php //endregion ?>
            */ ?>

		</div>
	</div>
    <?php
    return preg_replace('/\s+/', ' ', ob_get_clean());
}

add_shortcode('apicius_recipes', 'apicius_archive');
//endregion

/////////////////////////////////////////////////////////////////////
//region filter to take over single posts of type "recipe"
function apicius_recipe_filter($content) {
    if (is_singular('recipe')) {

        wp_enqueue_script('imagesLoaded');
        wp_enqueue_script('apicius-recipes-js');

        wp_enqueue_style('apicius-bs-css');
        wp_enqueue_style('apicius-css');

        global $post;

// we are ditching $content entirely.  :)

        $apicius_settings = get_option('apicius_recipe');

        $entry = Array();

        $entry['types'] = wp_get_post_terms($post->ID, 'recipe_type');

// get all the extra stuff
        foreach (get_post_custom_keys($post->ID) as $post_meta_key) :
            $entry[ $post_meta_key ] = get_post_meta($post->ID, $post_meta_key, true);
        endforeach;

// get the list of products as an actual array
        $entry['products_list'] = rwmb_meta('recipe_products', 'type=checkbox_list', $post->ID);

        ob_start();
        ?>
	<div id="apicius" data-apicius-version="<?=APICIUS_VERSION?>">
		<div id="recipe_single" class="container-fluid">

        <?php if ($apicius_settings['show_prev_next_recipe_above'] === "1") {
            show_prev_next("recipe", "above");
        } ?>

		<div class="row">
			<div class="col-sm-12">
                <?php show_social("recipe"); ?>

				<div id="recipe_image_mobile" class="col-xs-12 visible-xs">
                    <?php if (has_post_thumbnail()) {
                        $imageinfo       = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'large');
                        $entry['picURL'] = $imageinfo[0];
                        ?>
						<img itemprop="image" class="recipe-hero" src="<?=$entry['picURL']?>"
						     alt="<?php the_title(); ?>" />
                    <?php } ?>
				</div>

				<div id="recipe_image" class="col-xs-12 hidden-xs">
                    <?php if (has_post_thumbnail()) {
                        // already got this above in the mobile version
                        //                            $imageinfo = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'large');
                        //                            $entry['picURL'] = $imageinfo[0];
                        ?>
						<img itemprop="image" class="recipe-hero" src="<?=$entry['picURL']?>"
						     alt="<?php the_title(); ?>" />
                    <?php } ?>
				</div>


				<div id="recipe_title" class="col-xs-12">
					<h1><span itemprop="name"><?=$post->post_title;?></span></h1>
				</div>


                <?php //region prep and cook times
                ?>
                <?php if ($apicius_settings['use_times'] === "1") { ?>
					<div id="recipe_times" class="col-xs-12">
                        <?php if (!empty($entry['recipe_preptime'])) {
                            echo 'Prep Time: '.$entry['recipe_preptime'].' minutes<br />';
                        } ?>
                        <?php if (!empty($entry['recipe_cooktime'])) {
                            echo 'Cook Time: '.$entry['recipe_cooktime'].' minutes<br />';
                        } ?>
                        <?php if (!empty($entry['recipe_servings'])) {
                            echo '<span itemprop="recipeYield">Servings: '.$entry['recipe_servings'].'</span>';
                        } ?>
					</div>
                <?php } ?>
                <?php //endregion
                ?>


                <?php //region ingredients and products used
                ?>
				<div id="recipe_ingredients" class="col-xs-12">
					<h2 class="section-title">Ingredients</h2>

                    <?php if (!empty($entry['recipe_ingredients_group'])) {
                        foreach ($entry['recipe_ingredients_group'] as $group) {
                            ?>
                            <?php
                            if (!empty($group['recipe_ing_section_name'])) {
                                echo '<h3 class="section-title">'.$group['recipe_ing_section_name'].'</h3>'.PHP_EOL;
                            }
                            ?>
							<ul>
                                <?php
                                foreach ($group['recipe_ing_list'] as $ing) {
                                    echo '<li itemprop="ingredients">'.$ing.'</li>'.PHP_EOL;
                                }
                                ?>
							</ul>
                            <?php
                        }
                    }
                    ?>

                    <?php if ((count($entry['products_list']) > 0) && $apicius_settings['show_products_used_recipe_above'] === "1") { ?>
						<h3 class="products-used">Products used in this recipe:</h3>
                        <?php
                        foreach ($entry['products_list'] as $productID) {
                            if (get_post_status($productID) === 'publish') { ?>
                                <?php
                                $prodpic = wp_get_attachment_image_src(get_post_thumbnail_id($productID), 'large')[0];
                                if (!$prodpic) {
                                    if (!empty($apicius_settings['ph_product'])) {
                                        $prodpic = wp_get_attachment_image_src($apicius_settings['ph_product'][0])[0];
                                    } else {
                                        $prodpic = plugins_url('/images/ph_product.jpg', __FILE__);
                                    }
                                }
                                ?>
								<div class="rec-product">
									<a href="<?=get_permalink($productID)?>">
										<img src="<?=$prodpic?>"
										     alt="<?=str_replace("<sup>®</sup>", "", get_the_title($productID))?>"
										     class="img-responsive printhide" />
									</a><br />
									<div class="rec-product-name"><a
												href="<?=get_permalink($productID)?>"><?=get_the_title($productID)?></a>
									</div>
								</div>

                            <?php } ?>
                        <?php } ?>
                    <?php } ?>
				</div>

                <?php //endregion
                ?>


				<div id="recipe_directions" class="col-xs-12">
					<h2 class="section-title">Directions</h2>
					<div itemprop="recipeInstructions">
                        <?php
                        if (!empty($entry['recipe_directions_group'])) {
                            foreach ($entry['recipe_directions_group'] as $group) {

                                if (!empty($group['recipe_dir_section_name'])) {
                                    echo '<h3 class="section-title">'.$group['recipe_dir_section_name'].'</h3>'.PHP_EOL;
                                }
                                echo wpautop($group['recipe_directions']);
                                // TODO this is somehow creating or allowing an extra </p> at the end. fix!
                            }
                        }
                        ?>
					</div>
				</div>

                <?php //region nutritional information
                ?>
                <?php if ($apicius_settings['use_nutrition'] === "1") { ?>
					<div id="recipe_nutrition" class="col-xs-12">
                        <?php
                        $nutrition_prefix = "recipe_";
                        include('nutrition.php');
                        ?>
					</div>
                <?php } ?>
                <?php //endregion
                ?>

			</div>
		</div>


        <?php if ((count($entry['products_list']) > 0) && $apicius_settings['show_products_used_recipe_below'] === "1") { ?>
			<h3 class="products-used">Suggested Products</h3>
			<div id="products_used_below" class="row">
                <?php
                $maxProducts = $apicius_settings['show_products_used_count'];
                $counter     = 0;
                $products    = array();


                foreach ($entry['products_list'] as $productID) {
                    // if there is no "max products" show them all
                    // if there is a max products, only show up to that amount
                    if ($counter < $maxProducts || $maxProducts == 0) {
                        if (get_post_status($productID) === 'publish') {
                            $prodpic = wp_get_attachment_image_src(get_post_thumbnail_id($productID), 'large')[0];
                            if (!$prodpic) {
                                if (!empty($apicius_settings['ph_product'])) {
                                    $prodpic = wp_get_attachment_image_src($apicius_settings['ph_product'][0])[0];
                                } else {
                                    $prodpic = plugins_url('/images/ph_product.jpg', __FILE__);
                                }
                            }

                            $products[ $counter ]['used']      = true;
                            $products[ $counter ]['pic']       = $prodpic;
                            $products[ $counter ]['title']     = get_the_title($productID);
                            $products[ $counter ]['permalink'] = get_permalink($productID);

                            $counter ++;
                        }
                    } ?>
                <?php }

                // if we don't have enough products to make up the specified quantity, fill it up with random products
                // if there is no max products, then of course $counter will be a higher value
                if ($counter < $maxProducts) {
                    // fetch a number of random products that are not the ones already used

                    $prodQuery = new WP_Query(array(
                        'post_type'      => 'product',
                        'posts_per_page' => $maxProducts - $counter,
                        'post__not_in'   => $entry['products_list'],
                        'orderby'        => 'rand'
                    ));


                    if ($prodQuery->have_posts()) {
                        while ($prodQuery->have_posts()) {
                            $prodQuery->the_post();

                            $prodpic = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'large')[0];
                            if (!$prodpic) {
                                if (!empty($apicius_settings['ph_product'])) {
                                    $prodpic = wp_get_attachment_image_src($apicius_settings['ph_product'][0])[0];
                                } else {
                                    $prodpic = plugins_url('/images/ph_product.jpg', __FILE__);
                                }
                            }

                            $products[ $counter ]['used']      = false;
                            $products[ $counter ]['pic']       = $prodpic;
                            $products[ $counter ]['title']     = get_the_title($post->ID);
                            $products[ $counter ]['permalink'] = get_permalink($post->ID);

                            $counter ++;
                        }
                    }
                    wp_reset_postdata();
                }


                // we now have the right number of products to display
                foreach ($products as $product) {
                    ?>
					<div class="rec-product below <?=$product['used'] ? "used" : "filler"?>">
						<a href="<?=$product['permalink']?>">
							<img src="<?=$product['pic']?>"
							     alt="<?=str_replace("<sup>®</sup>", "", $product['title'])?>"
							     class="img-responsive printhide" />
						</a><br />
						<div class="rec-product-name">
							<a href="<?=$product['permalink']?>"><?=$product['title']?></a>
						</div>
					</div>
                    <?php
                }

                ?>
			</div>
        <?php } ?>


        <?php if ($apicius_settings['show_related'] === "1") { ?>
            <?php
            // get the recipe type(s) so we can display related recipes
            $types     = wp_get_post_terms($post->ID, 'recipe_type');
            $firsttype = $types[0];

            $recipe_query = new WP_Query(array(
                'post_type'      => 'recipe',
                'posts_per_page' => $apicius_settings['show_related_recipes_count'],
                'post__not_in'   => array($post->ID),
                'tax_query'      => array(
                    array(
                        'taxonomy' => 'recipe_type',
                        'field'    => 'term_id',
                        'terms'    => $firsttype
                    )
                )
            ));
            ?>

            <?php if ($recipe_query->have_posts()) { ?>
				<div id="recipes_list" class="row related-recipes">

				<div class="col-xs-12">
					<h2><span>Related</span> Recipes</h2>
				</div>
                <?php
                while ($recipe_query->have_posts()) {
                    $recipe_query->the_post();

                    foreach (get_post_custom_keys($post->ID) as $post_meta_key) :
                        $recipe[ $post_meta_key ] = get_post_meta($post->ID, $post_meta_key, true);
                    endforeach;

                    $pic = wp_get_attachment_image_src(get_post_thumbnail_id(), 'medium')[0];

                    if (!$pic) {
                        if (!empty($apicius_settings['ph_recipe'])) {
                            $pic = wp_get_attachment_image_src($apicius_settings['ph_recipe'][0])[0];
                        } else {
                            $pic = plugins_url('/images/ph_recipe.jpg', __FILE__);
                        }
                    }
                    ?>


					<div class="recipe-tile col-xs-6 col-sm-4">

						<div class="stretcher"></div>
						<a class="stretched-interior" href="<?php the_permalink(); ?>"
						   style="background-image: url(<?=$pic?>);">

							<span class="recipe-title"><?=$post->post_title?></span>

						</a>

					</div>
                    <?php
                } ?>
				</div><?php /* /related_recipes */ ?>
                <?php
            }
            wp_reset_postdata();
            ?>
        <?php } ?>


        <?php if ($apicius_settings['show_prev_next_recipe_below'] === "1") {
            show_prev_next("recipe", "below");
        } ?>


		<div id="apicius_after_recipe_content">
            <?=$apicius_settings['show_after_recommended']?>
		</div>


		</div><?php /* /container-fluid */ ?>
		</div><?php /* /#recipe_single */ ?>


        <?php
        $content = ob_get_clean();

    }


    // this regular expression will strip out all the excess whitespace
    // that happens with output buffer (and gets wordpress auto-formatted)
    return preg_replace('/\s+/', ' ', $content);
}

add_filter('the_content', 'apicius_recipe_filter', 9, 1);
//endregion



