<?php


/////////////////////////////////////////////////////////////////////
//region Products Custom Post Type with Meta Boxes
if (!in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
    add_action('init', 'apicius_register_cpt_product');
    function apicius_register_cpt_product() {
        $labels = array(
            'name'               => _x('Products', 'product'),
            'singular_name'      => _x('Product', 'product'),
            'add_new'            => _x('Add New', 'product'),
            'add_new_item'       => _x('Add New Product', 'product'),
            'edit_item'          => _x('Edit Product', 'product'),
            'new_item'           => _x('New Product', 'product'),
            'view_item'          => _x('View Product', 'product'),
            'search_items'       => _x('Search Products', 'product'),
            'not_found'          => _x('No product found', 'product'),
            'not_found_in_trash' => _x('No product found in Trash', 'product'),
            'parent_item_colon'  => _x('Parent Product:', 'product'),
            'menu_name'          => _x('Products', 'product'),
        );

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

            'supports'            => array('title', 'thumbnail', 'editor'),
            //'taxonomies' => array( 'post_tag' ),
            'public'              => true,
            'show_ui'             => true,
            'show_in_menu'        => true,
            'menu_position'       => 3,
            'menu_icon'           => 'dashicons-carrot',
            'show_in_nav_menus'   => true,
            'publicly_queryable'  => true,
            'exclude_from_search' => false,
            'has_archive'         => false,
            'query_var'           => true,
            'can_export'          => true,
            'rewrite'             => true,
            'capability_type'     => 'post'
        );

        register_post_type('product', $args);
    }


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

    register_taxonomy_for_object_type('product_cat', 'product');

}

//endregion


/////////////////////////////////////////////////////////////////////
//region product ingredients and nutritional information
// product custom meta box
add_action('admin_init', 'apicius_register_product_meta_boxes');

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


    // ingredients
    $meta_boxes[] = array(
        'id'       => 'product_ingredients',
        'title'    => 'Ingredients',
        'pages'    => array('product'),
        'context'  => 'normal',
        'priority' => 'high',
        'include'  => array(
            'custom' => 'apicius_product_include_field'
        ),
        '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,
                    ),
                ),
            )
        )
    );

    // nutritional information
    $meta_boxes[] = array(
        'id'       => 'product_nutrition',
        'title'    => ' Nutritional Information',
        'pages'    => array('product'),
        'context'  => 'normal',
        'priority' => 'high',
        'include'  => array(
            'custom' => 'apicius_product_include_field'
        ),
        'fields'   => array(
            array(
                'name' => 'Serving Size',
                'id'   => $prefix.'serving_size',
                'type' => 'text',
            ),
            array(
                'name' => 'Number of Servings',
                'id'   => $prefix.'servings',
                'type' => 'text',
            ),
            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);
    }
}


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

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

    return false;
}


/////////////////////////////////////////////////////////////////////
//region shortcode for use in WYSIWYG content for displaying products archive
if (!in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
    function apicius_prod_archive($atts, $content = null) {
        wp_enqueue_script('imagesLoaded');
        wp_enqueue_script('isotope');
        wp_enqueue_script('apicius-products-js');

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

        global $post;

        $apicius_settings   = get_option('apicius_product');
        $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


        ob_start();
//    echo spitio_prettify($apicius_settings);
        ?>
		<div id="apicius" data-apicius-version="<?=APICIUS_VERSION?>" style="<?=$apicius_overall?>">
			<div id="products_list" class="container-fluid">


				<div id="products_filters" class="row"
                     <?php if ($apicius_settings['use_filter_hash_product'] === "1") { ?>data-usefilterhash="please"<?php } ?>>


                    <?php //region product type tiles ?>
                    <?php if ($apicius_settings['prod_show_product_cat_filter_tiles'] === "1") { ?>
						<div class="col-sm-6 col-md-4">
							<h3>Product Category</h3>
							<div id="product_types" class="clearfix">
                                <?php
                                // get all product types (with posts in them)
                                $all_types = get_terms('product_cat', 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 ?>
				</div><!-- / product filters -->

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

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

                <?php //region pagination ?>
                <?php if ($apicius_settings['show_pagination_above'] === "1" && $apicius_settings['pagination_item_count'] > 0) { ?>
					<div id="products_pagination_above" class="products_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 ?>


				<div id="product_tiles" class="row">
                    <?php
                    // get products
                    $prodQuery = new WP_Query(array(
                        'post_type'      => 'product',
                        'posts_per_page' => '-1'
                    ));


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

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

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


                            $tag_classes = '';
                            // product categories

                            $prodcats = get_the_terms($post, 'product_cat');
                            foreach ($prodcats as $cat) {
                                $tag_classes .= 'type-'.$cat->slug.' ';
                            }


                            ?>
							<div class="product-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="product-title" style="<?=$title_styles?>"><?=$post->post_title?></span>
								</a>

							</div>
                            <?php

                        }
                    }
                    // Restore original Post Data
                    wp_reset_postdata();
                    ?>
				</div><!-- /container -->


                <?php //region pagination ?>
                <?php if ($apicius_settings['show_pagination_below'] === "1" && $apicius_settings['pagination_item_count'] > 0) { ?>
					<div id="products_pagination_below" class="products_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 ?>

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

    add_shortcode('apicius_products', 'apicius_prod_archive');
}
//endregion


/////////////////////////////////////////////////////////////////////
//region filter to take over single posts of type "product" if WooCommerce isn't active
if (!in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
    function apicius_product_filter($content) {
        if (is_singular('product')) {

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

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

            global $post;

// we are ditching $content entirely.  :)

            $apicius_settings = get_option('apicius_product');

            $entry = Array();

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

            // 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;

            if (has_post_thumbnail()) {
                $imageinfo       = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'large');
                $entry['picURL'] = $imageinfo[0];
            }


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

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

			        <div class="row">
				        <div class="col-sm-6">

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


                            <?php show_social("product"); ?>

				        </div>

				        <div class="col-sm-6">
					        <div id="product_image" class="col-xs-12 hidden-xs">
                                <?php if (has_post_thumbnail()) {
                                    ?>
							        <img itemprop="image" class="product-hero" src="<?=$entry['picURL']?>"
							             alt="<?=str_replace("<sup>®</sup>", "", $post->post_title)?>" />
                                <?php } ?>
					        </div>
				        </div>
			        </div>

			        <div class="row">
				        <div id="product_content" class="col-xs-12">
                            <?php echo $post->post_content; ?>
				        </div>
			        </div>

                    <?php if ($apicius_settings['show_product_ingredients'] === "1" && !empty($entry['product_ingredients_group'])) { ?>
				        <div id="product_ingredients" class="col-xs-12">
					        <h2 class="section-title">Ingredients</h2>

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


                    <?php if ($apicius_settings['show_product_nutrition'] === "1" && !empty($entry['product_cal'])) { ?>
				        <div id="product_nutrition" class="col-xs-12">
                            <?php
                            $nutrition_prefix = "product_";
                            include('nutrition.php');
                            ?>
				        </div>
                    <? } ?>


                    <?php show_product_recipes(); ?>


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

                    <?php show_apicius_product_stuff_after(); ?>

		        </div><!-- /#product_single -->
	        </div><!-- /#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_product_filter', 9, 1);
}
//endregion


//region add stuff to woocommerce product view
add_action('woocommerce_after_single_product', 'apicius_add_to_wc', 1);
function apicius_add_to_wc() {
    wp_enqueue_style('apicius-css');
    wp_enqueue_style('apicius-bs-css');

    $apicius_settings = get_option('apicius_product');

    echo '<div id="apicius">';

    // get all the extra stuff
    foreach (get_post_custom_keys(get_the_ID()) as $post_meta_key) :
        $entry[ $post_meta_key ] = get_post_meta(get_the_ID(), $post_meta_key, true);
    endforeach;
    ?>
    <?php if ($apicius_settings['show_product_ingredients'] === "1") { ?>
		<div id="product_ingredients" class="col-xs-12">
			<h2 class="section-title">Ingredients</h2>

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


    <?php if ($apicius_settings['show_product_nutrition'] === "1") { ?>
		<div id="product_nutrition" class="col-xs-12">
            <?php
            $nutrition_prefix = "product_";
            include('nutrition.php');
            ?>
		</div>
    <? } ?>

    <?php
    show_social("product");

    show_product_recipes();

    show_prev_next("product", get_the_ID());

    show_apicius_product_stuff_after();

    echo '</div>';
}

//endregion


// show recipes at the bottom of a single product
function show_product_recipes() {
    global $post;

    $apicius_settings = get_option('apicius_product');

    if ($apicius_settings['show_product_recipes'] === "1") {

        $product_title = $post->post_title;

        ?>
		<div id="recipes_list" class="row related-recipes">

			<div class="col-xs-12">
                <?php /* <h2><span>Recipes Using <?=$product_title?></span></h2> */ ?>
				<h2><span>Suggested Recipes</span></h2>
			</div>
            <?php

            // even if there aren't any recipes that use this product, or aren't enough to meet the "show_prod_recipes_count"
            // fill it in with random recipes (that haven't already been used)
            $maxRecipes = $apicius_settings['show_prod_recipes_count'];
            $counter    = 0;
            $recipes    = array();

            // keep track of the IDs of recipes already chosen
            $recipesShowingIDs = array();

            // get recipes that use this product
            $recQuery = new WP_Query(array(
                'post_type'      => 'recipe',
                'posts_per_page' => $maxRecipes,
                'orderby'        => 'rand',
                'meta_key'       => 'recipe_products',
                'meta_value'     => $post->ID,
                'meta_compare'   => 'IN'
            ));

            if ($recQuery->have_posts()) {
                while ($recQuery->have_posts()) {
                    $recQuery->the_post();
                    // add this recipe's ID to $recipesShowingIDs to make sure they are not repeated
                    $recipesShowingIDs[] = $post->ID;

                    $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__);
                        }
                    }
                    $recipes[ $counter ]["used"]      = true;
                    $recipes[ $counter ]["pic"]       = $pic;
                    $recipes[ $counter ]["permalink"] = get_the_permalink();
                    $recipes[ $counter ]["title"]     = get_the_title();

                    $counter ++;
                }
            }
            wp_reset_postdata();


            // if we have not yet shown enough recipes (show_prod_recipes_count),
            // get some random recipes (that aren't in $recipesShowingIDs)
            if ($counter < $maxRecipes) {
                $recQuery = new WP_Query(array(
                    'post_type'      => 'recipe',
                    'posts_per_page' => $maxRecipes - $counter,
                    'orderby'        => 'rand',
                    'post__not_in'   => $recipesShowingIDs
                ));
                if ($recQuery->have_posts()) {
                    while ($recQuery->have_posts()) {
                        $recQuery->the_post();
                        // add this recipe's ID to $recipesShowingIDs to make sure they are not repeated
                        $recipesShowingIDs[] = $post->ID;

                        $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__);
                            }
                        }
                        $recipes[ $counter ]["used"]      = false;
                        $recipes[ $counter ]["pic"]       = $pic;
                        $recipes[ $counter ]["permalink"] = get_the_permalink();
                        $recipes[ $counter ]["title"]     = get_the_title();

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


            // show the recipes
            foreach ($recipes as $recipe) {
                ?>
				<div class="recipe-tile col-xs-6 col-sm-4 <?=$recipe['used'] ? "used" : "filler"?>">
					<div class="stretcher"></div>
					<a class="stretched-interior" href="<?=$recipe['permalink']?>"
					   style="background-image: url(<?=$recipe['pic']?>);">
						<span class="recipe-title"><?=$recipe['title']?></span>
					</a>
				</div>
                <?php
            }


            ?> </div> <?php
    }
}


// show content given by admin beneath everything else
function show_apicius_product_stuff_after() {
    $apicius_settings = get_option('apicius_product');
    ?>
	<div id="apicius_after_product_content">
        <?=$apicius_settings['show_after_recommended']?>
	</div>
    <?php
}
