<?php
/*
Plugin Name: Apicius Products & Recipes
Description: Management of recipes related/linked with products
Version:	 0.12.0
Author: Christy.pw
Author URI: http://christy.pw
*/


defined('ABSPATH') or die('No script kiddies please!');

if (!defined('APICIUS_VERSION')) {
    define('APICIUS_VERSION', '0.12.0');
}

/////////////////////////////////////////////////////////////////////
//region load in js
function apicius_scripts_important() {

    if (!is_admin()) {
        wp_register_script('imagesLoaded', plugins_url('/js/imagesloaded.pkgd.min.js', __FILE__), array('jquery'), true);
        wp_register_script('isotope', plugins_url('/js/isotope.pkgd.min.js', __FILE__), array('jquery'), true);
        wp_register_script('apicius-recipes-js', plugins_url('/js/recipes.js', __FILE__), array('jquery'));
        wp_register_script('apicius-products-js', plugins_url('/js/products.js', __FILE__), array('jquery'));
        wp_register_script('apicius-posts-js', plugins_url('/js/posts.js', __FILE__), array('jquery'));
        wp_register_script('apicius-widgets-js', plugins_url('/js/widgets.js', __FILE__), array('jquery'));
        wp_register_script('apicius-nice-select-js', plugins_url('/js/jquery.nice-select.min.js', __FILE__), array('jquery'));
    }
}

add_action('wp_enqueue_scripts', 'apicius_scripts_important', 10);
//endregion

//region load in styles
function apicius_styles() {
    wp_register_style('apicius-bs-css', plugins_url('/css/bootstrap.css', __FILE__));
    wp_register_style('apicius-css', plugins_url('/css/styles.css', __FILE__));
    wp_register_style('apicius-nice-select-css', plugins_url('/css/nice-select.css', __FILE__));
    wp_register_style('apicius-widget-css', plugins_url('/css/apicius-widget.css', __FILE__));
}

add_action('wp_enqueue_scripts', 'apicius_styles');
//endregion

require_once('recipes.php');

require_once('products.php');

require_once('apicius-widgets.php');

/////////////////////////////////////////////////////////////////////
//region updater service
require 'plugin-updates/plugin-update-checker.php';
$ExampleUpdateChecker = PucFactory::buildUpdateChecker(
    'http://wpplugs.stellarstudios.net/apicius-products-recipes/info.json',
    __FILE__
);
//endregion


/////////////////////////////////////////////////////////////////////
//region make other plugins required.
/**
 * Include the TGM_Plugin_Activation class.
 */
require_once dirname(__FILE__).'/class-tgm-plugin-activation.php';

add_action('tgmpa_register', 'apicius_register_required_plugins');
/**
 * Register the required plugins for this theme.
 *
 * The variable passed to tgmpa_register_plugins() should be an array of plugin
 * arrays.
 *
 * This function is hooked into tgmpa_init, which is fired within the
 * TGM_Plugin_Activation class constructor.
 */
function apicius_register_required_plugins() {
    /*
     * Array of plugin arrays. Required keys are name and slug.
     * If the source is NOT from the .org repo, then source is also required.
     */
    $plugins = array(
        array(
            'name'               => 'Meta Box',
            'slug'               => 'meta-box',
            'required'           => true,
            'force_activation'   => true,
            'force_deactivation' => false,
        ),
        array(
            'name'               => 'Meta Box Group',
            'slug'               => 'meta-box-group',
            'source'             => plugins_url('/packaged/meta-box-group.zip', __FILE__),
            'version'            => '1.1.6',
            'required'           => true,
            'force_activation'   => true,
            'force_deactivation' => false,
        ),
        array(
            'name'               => 'MB Settings Page',
            'slug'               => 'mb-settings-page',
            'source'             => plugins_url('/packaged/mb-settings-page.zip', __FILE__),
            'version'            => '1.1.4',
            'required'           => true,
            'force_activation'   => true,
            'force_deactivation' => false,
        ),
        array(
            'name'               => 'MB Include Exclude',
            'slug'               => 'meta-box-include-exclude',
            'source'             => plugins_url('/packaged/meta-box-include-exclude.zip', __FILE__),
            'version'            => '1.0.7',
            'required'           => true,
            'force_activation'   => true,
            'force_deactivation' => false,
        ),
        array(
            'name'               => 'WP Extended Search',
            'slug'               => 'wp-extended-search',
            'required'           => true,
            'force_activation'   => true,
            'force_deactivation' => false,
        ),
        array(
            'name'               => 'Intuitive Custom Post Order',
            'slug'               => 'intuitive-custom-post-order',
            'required'           => true,
            'force_activation'   => false,
            'force_deactivation' => false,
        )
    );

    /*
     * Array of configuration settings. Amend each line as needed.
     */
    $config = array(
        'id'           => 'apicius',
        // Unique ID for hashing notices for multiple instances of TGMPA.
        'default_path' => '',
        // Default absolute path to bundled plugins.
        'menu'         => 'tgmpa-install-plugins',
        // Menu slug.
        'parent_slug'  => 'plugins.php',
        // Parent menu slug.
        'capability'   => 'edit_theme_options',
        // Capability needed to view plugin install page, should be a capability associated with the parent menu used.
        'has_notices'  => true,
        // Show admin notices or not.
        'dismissable'  => true,
        // If false, a user cannot dismiss the nag message.
        'dismiss_msg'  => '',
        // If 'dismissable' is false, this message will be output at top of nag.
        'is_automatic' => true,
        // Automatically activate plugins after installation or not.
        'message'      => ''
        // Message to output right before the plugins table.
    );
    tgmpa($plugins, $config);
}

//endregion\


/////////////////////////////////////////////////////////////////////
//region store and check Apicius version number

global $apicius_save_as; // the `option_name` field in the `wp_options` table
$apicius_save_as = 'apicius_version';

function apicius_check_version() {
    global $apicius_save_as;
    if (APICIUS_VERSION !== get_option($apicius_save_as)) {
        // if there is no version number saved, or if it's not the current one
        $existing_apicius_option = get_option('apicius');

//        update_option('apicius_copy', '+: '.$existing_apicius_option);

		// if the db has the 'apicius'  entry in the wp_options table, need to deal with that
        if ($existing_apicius_option) {
//        	update_option('apicius_needs_update', 'yes');
        	// there's recipes settings lumped in with product options
            // they need to be pulled out and separated into apicius_recipe and apicius_product
            // and get rid of 'apicius' options entry (it has both recipe and product settings in it)


            $build_new_recipes_option = array(
                'use_times'                       => $existing_apicius_option['use_times'],
                'use_servings'                    => $existing_apicius_option['use_servings'],
                'use_nutrition'                   => $existing_apicius_option['use_nutrition'],
                'use_description'                 => $existing_apicius_option['use_description'],
                'show_related'                    => $existing_apicius_option['show_related'],
                'show_related_recipes_count'      => $existing_apicius_option['show_related_recipes_count'],
                'show_prev_next_recipe_above'     => $existing_apicius_option['show_prev_next_recipe_above'],
                'show_prev_next_recipe_below'     => $existing_apicius_option['show_prev_next_recipe_below'],
                'show_products_used_recipe_above' => $existing_apicius_option['show_products_used_recipe_above'],
                'show_products_used_recipe_below' => $existing_apicius_option['show_products_used_recipe_below'],
                'show_products_used_count'        => $existing_apicius_option['show_products_used_count'],
                'show_after_recommended'          => $existing_apicius_option['show_after_recommended'],
                'exclude_prodcats'                => $existing_apicius_option['exclude_prodcats'],
                'show_recipe_search_box'          => $existing_apicius_option['show_recipe_search_box'],
                'show_product_filter_dropdown'    => $existing_apicius_option['show_product_filter_dropdown'],
                'show_recipe_cat_filter_tiles'    => $existing_apicius_option['show_recipe_cat_filter_tiles'],
                'show_recipe_cat_filter_dropdown' => $existing_apicius_option['show_recipe_cat_filter_dropdown'],
                'show_results_count'              => $existing_apicius_option['show_results_count'],
                'show_prod_cat_dropdown'          => $existing_apicius_option['show_prod_cat_dropdown'],
                'use_filter_hash'                 => $existing_apicius_option['use_filter_hash'],
                'show_pagination_above'           => $existing_apicius_option['show_pagination_above'],
                'show_pagination_below'           => $existing_apicius_option['show_pagination_below'],
                'collapse_pagination'             => $existing_apicius_option['collapse_pagination'],
                'pagination_item_count'           => $existing_apicius_option['pagination_item_count'],
                'show_social'                     => $existing_apicius_option['show_social'],
                'social_icon_spacing'             => $existing_apicius_option['social_icon_spacing'],
                'show_social_fb'                  => $existing_apicius_option['show_social_fb'],
                'social_icon_fb'                  => $existing_apicius_option['social_icon_fb'],
                'show_social_tw'                  => $existing_apicius_option['show_social_tw'],
                'social_icon_tw'                  => $existing_apicius_option['social_icon_tw'],
                'show_social_pin'                 => $existing_apicius_option['show_social_pin'],
                'social_icon_pin'                 => $existing_apicius_option['social_icon_pin'],
                'show_social_tumblr'              => $existing_apicius_option['show_social_tumblr'],
                'social_icon_tumblr'              => $existing_apicius_option['social_icon_tumblr'],
                'show_social_gplus'               => $existing_apicius_option['show_social_gplus'],
                'social_icon_gplus'               => $existing_apicius_option['social_icon_gplus'],
                'show_social_email'               => $existing_apicius_option['show_social_email'],
                'social_icon_email'               => $existing_apicius_option['social_icon_email']
            );

            update_option('apicius_recipe', $build_new_recipes_option);

            // pull out the products settings from 'apicius'
            $build_new_products_option = array(
                'show_in_archive'                    => $existing_apicius_option['show_in_archive'],
                'show_results_count_product'         => $existing_apicius_option['show_results_count_product'],
                'prod_show_product_cat_filter_tiles' => $existing_apicius_option['prod_show_product_cat_filter_tiles'],
                'use_filter_hash_product'            => $existing_apicius_option['use_filter_hash_product'],
                'show_product_ingredients'           => $existing_apicius_option['show_product_ingredients'],
                'show_product_nutrition'             => $existing_apicius_option['show_product_nutrition'],
                'show_product_recipes'               => $existing_apicius_option['show_product_recipes'],
                'show_prod_recipes_count'            => $existing_apicius_option['show_prod_recipes_count'],
                'show_prev_next_product_above'       => $existing_apicius_option['show_prev_next_product_above'],
                'show_prev_next_product_below'       => $existing_apicius_option['show_prev_next_product_below'],
                'show_after_recommended'             => $existing_apicius_option['show_after_recommended'],
                'show_social_product'                => $existing_apicius_option['show_social_product'],
                'social_icon_spacing_product'        => $existing_apicius_option['social_icon_spacing_product'],
                'show_social_fb_product'             => $existing_apicius_option['show_social_fb_product'],
                'social_icon_fb_product'             => $existing_apicius_option['social_icon_fb_product'],
                'show_social_tw_product'             => $existing_apicius_option['show_social_tw_product'],
                'social_icon_tw_product'             => $existing_apicius_option['social_icon_tw_product'],
                'show_social_pin_product'            => $existing_apicius_option['show_social_pin_product'],
                'social_icon_pin_product'            => $existing_apicius_option['social_icon_pin_product'],
                'show_social_tumblr_product'         => $existing_apicius_option['show_social_tumblr_product'],
                'social_icon_tumblr_product'         => $existing_apicius_option['social_icon_tumblr_product'],
                'show_social_gplus_product'          => $existing_apicius_option['show_social_gplus_product'],
                'social_icon_gplus_product'          => $existing_apicius_option['social_icon_gplus_product'],
                'show_social_email_product'          => $existing_apicius_option['show_social_email_product'],
                'social_icon_email_product'          => $existing_apicius_option['social_icon_email_product'],
                'archive_location'                   => $existing_apicius_option['archive_location']
            );

            update_option('apicius_product', $build_new_products_option);



            // remove the 'apicius' option entirely
	        delete_option('apicius');

        }

        // and now, update the version number
         update_option($apicius_save_as, APICIUS_VERSION);
    }
}

add_action('plugins_loaded', 'apicius_check_version');


//endregion


/////////////////////////////////////////////////////////////////////
//region WP Admin top level page to show information
add_action('admin_menu', 'apicius_info_page');
function apicius_info_page() {
//    add_options_page( 'Apicius Information', 'Information', 'manage_options', 'apicius-menu', 'apicius_info_content' );
    add_menu_page('Apicius Information', 'Apicius Info & Settings', 'manage_options', 'apicius-information', 'apicius_info_content', plugins_url('/images/recipes.png', __FILE__), 4);
}


function apicius_info_content() {
    ?>
	<div class="wrap">
		<h2>Apicius Products Recipes Information</h2>
		<div class="postbox" style="white-space: pre-wrap;">
			<div class="inside" style="margin-top: 0px;"><?php include('readme.txt'); ?></div>
		</div>
	</div>
    <?php
}

//endregion


require_once('settings.php');


/////////////////////////////////////////////////////////////////////
//region function to get the slug of a post by id
function apicius_the_slug($id) {
    $post_data = get_post($id, ARRAY_A);
    $slug      = $post_data['post_name'];

    return $slug;
}

//endregion


/////////////////////////////////////////////////////////////////////
//region filters for recipes and products; remove theme's usage of the title

// override any usage of the_title() with null.
// my plugin uses $post->post_title instead.
function apicius_remove_title($title, $id = null) {
    if (!in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins')))) {
        if ((is_singular('product') && get_post_type($id) == 'product') || (is_singular('recipe') && get_post_type($id) == 'recipe')) {
            return '';
        }
    } else {
        if (is_singular('recipe') && get_post_type($id) == 'recipe') {
            return '';
        }
    }

    return $title;
}

add_filter('the_title', 'apicius_remove_title', 10, 2);


//endregion


function show_social($type) {
    global $post;
    if ($type == "product") {
        $postfix     = "_product";
        $share_id    = "single_product_share";
        $option_name = "apicius_product";
    }
    if ($type == "recipe") {
        $postfix     = "";
        $share_id    = "single_recipe_share";
        $option_name = "apicius_recipe";
    }

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

    $apicius_settings = get_option($option_name);
    if ($apicius_settings[ 'show_social'.$postfix ] === "1") { ?>
        <?php
        if (!empty($apicius_settings[ 'social_icon_spacing'.$postfix ]) || $apicius_settings[ 'social_icon_spacing'.$postfix ] === '0') {
            $icon_spacing = 'style="margin-right: '.$apicius_settings[ 'social_icon_spacing'.$postfix ].'px;"';
        } else {
            $icon_spacing = '';
        }
        ?>

		<div id="<?=$share_id?>" class="printhide clearfix col-xs-12">
			<p>Share:</p>
            <?php if (!empty($apicius_settings[ 'show_social_fb'.$postfix ])) { ?>
                <?php
                if (!empty($apicius_settings[ 'social_icon_fb'.$postfix ])) {
                    $fb_pic = wp_get_attachment_image_src($apicius_settings[ 'social_icon_fb'.$postfix ][0])[0];
                } else {
                    $fb_pic = plugins_url('/images/icon-share-fb.png', __FILE__);
                }
                ?>
				<a href="https://www.facebook.com/sharer/sharer.php?u=<?=get_the_permalink($post->ID)?>">
					<img src="<?=$fb_pic?>" <?=$icon_spacing?> alt="Share on Facebook" />
				</a>
            <?php } ?>

            <?php if (!empty($apicius_settings[ 'show_social_tw'.$postfix ])) { ?>
                <?php
                if (!empty($apicius_settings[ 'social_icon_tw'.$postfix ])) {
                    $tw_pic = wp_get_attachment_image_src($apicius_settings[ 'social_icon_tw'.$postfix ][0])[0];
                } else {
                    $tw_pic = plugins_url('/images/icon-share-tw.png', __FILE__);
                }
                ?>
				<a href="https://twitter.com/home?status=Check%20out%20this%20<?=$post->post_title?>%20<?=$type?>%20at%20<?=get_the_permalink($post->ID)?>">
					<img src="<?=$tw_pic?>" <?=$icon_spacing?> alt="Share on Twitter" />
				</a>
            <?php } ?>

            <?php if (!empty($apicius_settings[ 'show_social_pin'.$postfix ])) { ?>
                <?php
                if (!empty($apicius_settings[ 'social_icon_pin'.$postfix ])) {
                    $pin_pic = wp_get_attachment_image_src($apicius_settings[ 'social_icon_pin'.$postfix ][0])[0];
                } else {
                    $pin_pic = plugins_url('/images/icon-share-pin.png', __FILE__);
                }
                ?>
				<a href="http://pinterest.com/pin/create/button/?url=<?=get_the_permalink($post->ID)?>&media=<?=$entry['picURL'] ? $entry['picURL'] : ''?>&description=<?=urlencode($post->post_title)?>">
					<img src="<?=$pin_pic?>" <?=$icon_spacing?> alt="Pin on Pinterest" />
				</a>
            <?php } ?>

            <?php if (!empty($apicius_settings[ 'show_social_tumblr'.$postfix ])) { ?>
                <?php
                if (!empty($apicius_settings[ 'social_icon_tumblr'.$postfix ])) {
                    $tumblr_pic = wp_get_attachment_image_src($apicius_settings[ 'social_icon_tumblr'.$postfix ][0])[0];
                } else {
                    $tumblr_pic = plugins_url('/images/icon-share-tumblr.png', __FILE__);
                }
                ?>
				<a href="http://www.tumblr.com/share/link?url=<?=get_the_permalink($post->ID)?>">
					<img src="<?=$tumblr_pic?>" <?=$icon_spacing?> alt="Share on Tumblr" />
				</a>
            <?php } ?>

            <?php if (!empty($apicius_settings[ 'show_social_gplus'.$postfix ])) { ?>
                <?php
                if (!empty($apicius_settings[ 'social_icon_gplus'.$postfix ])) {
                    $gplus_pic = wp_get_attachment_image_src($apicius_settings[ 'social_icon_gplus'.$postfix ][0])[0];
                } else {
                    $gplus_pic = plugins_url('/images/icon-share-gplus.png', __FILE__);
                }
                ?>
				<a href="https://plus.google.com/share?url=<?=get_the_permalink($post->ID)?>">
					<img src="<?=$gplus_pic?>" <?=$icon_spacing?> alt="Share on Google Plus" />
				</a>
            <?php } ?>

            <?php if (!empty($apicius_settings[ 'show_social_email'.$postfix ])) { ?>
                <?php
                if (!empty($apicius_settings[ 'social_icon_email'.$postfix ])) {
                    $email_pic = wp_get_attachment_image_src($apicius_settings[ 'social_icon_email'.$postfix ][0])[0];
                } else {
                    $email_pic = plugins_url('/images/icon-share-email.png', __FILE__);
                }
                ?>
				<a href="mailto:?subject=<?=ucfirst($type)?>: <?=$post->post_title?>&body=Take a look at the <?=$post->post_title?> <?=$type?> from <?php bloginfo('name'); ?>: <?=get_the_permalink($post->ID)?>">
					<img src="<?=$email_pic?>" <?=$icon_spacing?> alt="Share with Email" />
				</a>
            <?php } ?>
		</div>
    <?php }
}


function show_prev_next($type, $location) {
    ?>
	<div class="apicius_prev_next <?=$location?>">
		<div class="row">
			<div class="apicius_prev col-sm-6">
                <?php previous_post_link('%link', 'Previous '.ucfirst($type)); ?>
			</div>
			<div class="apicius_next col-sm-6">
                <?php next_post_link('%link', 'Next '.ucfirst($type)); ?>
			</div>
		</div>
	</div>
    <?php
}


/////////////////////////////////////////////////////////////////////
//region give standard posts the ability to choose related recipes/products/posts
add_action('admin_init', 'apicius_register_post_meta_boxes');

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

    // products used
    $meta_boxes[] = array(
        'id'       => 'products',
        'title'    => 'Related Products, Recipes, or Posts',
        'desc'     => 'Displays in blocks beneath the post content',
        'pages'    => array('post'),
        'context'  => 'normal',
        'priority' => 'high',
        'fields'   => array(
            array(
                'id'         => $prefix.'related',
                'type'       => 'post',
                'post_type'  => array('product', 'recipe', 'post'),
                'field_type' => 'select_advanced',
                'allowClear' => true,
                'clone'      => true
            )
        )
    );

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

//endregion


/////////////////////////////////////////////////////////////////////
//region filter to take over single posts of "post" type, to put in the related thingies

function apicius_post_filter($content) {
    if (is_singular('post')) {

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

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

        global $post;

        $related = rwmb_meta('apicius_post_related', $post->ID);

        if (count($related) > 0 && $related != null) {
            $counter = 0;
            $items   = array();

            foreach ($related as $itemID) {
                if (get_post_status($itemID) === 'publish') {
                    $itemPic = wp_get_attachment_image_src(get_post_thumbnail_id($itemID), 'large')[0];
                    if (!$itemPic) {
                        if (get_post_type($itemID) === 'product') {
                            if (!empty($apicius_settings['ph_product'])) {
                                $itemPic = wp_get_attachment_image_src($apicius_settings['ph_product'][0])[0];
                            } else {
                                $itemPic = plugins_url('/images/ph_product.jpg', __FILE__);
                            }
                        } else if (get_post_type($itemID) === 'recipe') {
                            if (!empty($apicius_settings['ph_recipe'])) {
                                $itemPic = wp_get_attachment_image_src($apicius_settings['ph_recipe'][0])[0];
                            } else {
                                $itemPic = plugins_url('/images/ph_recipe.jpg', __FILE__);
                            }
                        }
                    }

                    $items[ $counter ]['pic']       = $itemPic;
                    $items[ $counter ]['title']     = get_the_title($itemID);
                    $items[ $counter ]['permalink'] = get_permalink($itemID);
                    $counter ++;
                }
            }

            if (count($items) > 0) {
                ob_start();
                ?>
				<div id="apicius">
					<h3 class="apicius_related">Related:</h3>
					<div id="apicius_related_things_below" class="row">
                        <?php
                        foreach ($items as $item) {
                            ?>
							<div class="apicius-related related-post-tile below col-xs-6 col-sm-4">
								<div class="stretcher"></div>
								<a class="stretched-interior" href="<?=$item['permalink']?>"
								   style="background-image: url(<?=$item['pic']?>);">
									<span class="apicius-related-item-name"><?=$item['title']?></span>
								</a>
							</div>
                            <?php
                        }
                        ?>
					</div>
				</div>
                <?php
                return $content.ob_get_clean();
            }
        }
    }

    return $content;
}

add_filter('the_content', 'apicius_post_filter', 9, 1);

//endregion



