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

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

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

// apicius




/////////////////////////////////////////////////////////////////////
//region updater service
require 'plugin-updates/plugin-update-checker.php';
$ExampleUpdateChecker = PucFactory::buildUpdateChecker(
    'http://wpplugs.stellarstudios.net/apicius-wc-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__),
            '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__),
            '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__),
            '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(
            'name'               => 'WooCommerce',
            'slug'               => 'woocommerce',
            '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 Apicius version number
// they will be stored in the database as an array under 'apicius_version' in the options table
// the stored array will actually resemble:
/*
array (
	'active' -> '1',
	'templatefile' -> '0'
	)

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

global $apicius_option_list;
$apicius_option_list = array(
    array(
        'db_name' => 'version',
        'init' => APICIUS_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 WC 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




/////////////////////////////////////////////////////////////////////
//region settings pages!  thank you, Meta Box Settings Page.
add_filter('mb_settings_pages', 'apicius_settings_pages');

function apicius_settings_pages($apicius_settings_pages) {
    $apicius_settings_pages[] = array(
        'id'          => 'apicius-options',
        'option_name' => 'apicius',
        'menu_title'  => __('Recipe Features', 'textdomain'),
        'parent' => 'apicius-information',
        'style'       => 'boxes',
        'columns'     => 1
    );

    $apicius_settings_pages[] = array(
        'id'          => 'apicius-appearance',
        'option_name' => 'apicius_appearance',
        'menu_title'  => __('Appearance', 'textdomain'),
        'parent' => 'apicius-information',
        'style'       => 'boxes',
        'columns'     => 1
    );

    return $apicius_settings_pages;
}



// content of settings pages
add_filter('rwmb_meta_boxes', 'apicius_options_meta_boxes');
function apicius_options_meta_boxes($meta_boxes) {

// elements to display

    // elements to use - times, servings, description, nutrition
    $meta_boxes[] = array(
        'id'             => 'elements',
        'title'          => __('Elements to Use', 'textdomain'),
        'settings_pages' => 'apicius-options',
        'fields'         => array(
            array(
                'name' => __('Prep & Cook Times', 'textdomain'),
                'id'   => 'use_times',
                'type' => 'checkbox'
            ),
            array(
                'name' => __('Servings', 'textdomain'),
                'id'   => 'use_servings',
                'type' => 'checkbox'
            ),
            array(
                'name' => __('Nutritional Information', 'textdomain'),
                'id'   => 'use_nutrition',
                'type' => 'checkbox'
            ),
            array(
                'name' => __('Description', 'textdomain'),
                'id'   => 'use_description',
                'type' => 'checkbox'
            ),
            array(
                'name' => __('Related Recipes', 'textdomain'),
                'desc' => '(on single recipe view)',
                'id'   => 'show_related',
                'type' => 'checkbox'
            )
        )
    );

    // product categories to exclude
    $meta_boxes[] = array(
        'id'             => 'categories',
        'title'          => __('Product Categories to Exclude', 'textdomain'),
        'settings_pages' => 'apicius-options',
        'fields'         => array(
            array(
                'name'       => 'EXCLUDE these product categories',
                'id'         => 'exclude_prodcats',
                'type'       => 'taxonomy',
                'taxonomy'   => 'product_cat',
                'field_type' => 'checkbox_list',
                'query_args' => array(
                    'hide_empty' => true
                )
            )
        )
    );


    // show in archive view - displaying count, prod cat filter
    $meta_boxes[] = array(
        'id'             => 'show_in_archive',
        'title'          => __('Show in Archive View', 'textdomain'),
        'settings_pages' => 'apicius-options',
        'fields'         => array(
            array(
                'name' => __('Filtered results displaying count', 'textdomain'),
                'id'   => 'show_results_count',
                'type' => 'checkbox'
            ),
            array(
                'name' => __('Product Category Dropdown Filter', 'textdomain'),
                'id'   => 'show_prod_cat_dropdown',
                'type' => 'checkbox'
            ),
            array(
                'name' => __('Make Filter Results Linkable (hash in URL)', 'textdomain'),
                'id'   => 'use_filter_hash',
                'type' => 'checkbox'
            )
        )
    );



    // social
    $meta_boxes[] = array(
        'id'             => 'social_sharing',
        'title'          => __('Social Sharing Options', 'textdomain'),
        'settings_pages' => 'apicius-options',
        'fields'         => array(
            array(
                'name' => __('Show social sharing section?', 'textdomain'),
                'desc' => 'If unchecked, nothing will show, despite what may be checked below.',
                'id'   => 'show_social',
                'type' => 'checkbox'
            ),
            array(
                'name' => __('Spacing between icons', 'textdomain'),
                'desc' => 'In pixels - if left empty, default is 8',
                'id'   => 'social_icon_spacing',
                'type' => 'number',
                'step' => 1,
                'std'  => 8

            ),
            array(
                'name' => __('Show Facebook?', 'textdomain'),
                'id'   => 'show_social_fb',
                'type' => 'checkbox'
            ),
            array(
                'name'             => 'FB Icon',
                'desc'             => 'If none specified, default will be used:<br /><img src="'.plugins_url('/images/icon-share-fb.png', __FILE__).'">',
                'id'               => 'social_icon_fb',
                'type'             => 'image_advanced',
                'max_file_uploads' => 1
            ),
            array(
                'name' => __('Show Twitter?', 'textdomain'),
                'id'   => 'show_social_tw',
                'type' => 'checkbox'
            ),
            array(
                'name'             => 'Twitter Icon',
                'desc'             => 'If none specified, default will be used:<br /><img src="'.plugins_url('/images/icon-share-tw.png', __FILE__).'">',
                'id'               => 'social_icon_tw',
                'type'             => 'image_advanced',
                'max_file_uploads' => 1
            ),
            array(
                'name' => __('Show Pinterest?', 'textdomain'),
                'id'   => 'show_social_pin',
                'type' => 'checkbox'
            ),
            array(
                'name'             => 'Pinterest Icon',
                'desc'             => 'If none specified, default will be used:<br /><img src="'.plugins_url('/images/icon-share-pin.png', __FILE__).'">',
                'id'               => 'social_icon_pin',
                'type'             => 'image_advanced',
                'max_file_uploads' => 1
            ),
            array(
                'name' => __('Show Tumblr?', 'textdomain'),
                'id'   => 'show_social_tumblr',
                'type' => 'checkbox'
            ),
            array(
                'name'             => 'Tumblr Icon',
                'desc'             => 'If none specified, default will be used:<br /><img src="'.plugins_url('/images/icon-share-tumblr.png', __FILE__).'">',
                'id'               => 'social_icon_tumblr',
                'type'             => 'image_advanced',
                'max_file_uploads' => 1
            ),
            array(
                'name' => __('Show Google Plus?', 'textdomain'),
                'id'   => 'show_social_gplus',
                'type' => 'checkbox'
            ),
            array(
                'name'             => 'G+ Icon',
                'desc'             => 'If none specified, default will be used:<br /><img src="'.plugins_url('/images/icon-share-gplus.png', __FILE__).'">',
                'id'               => 'social_icon_gplus',
                'type'             => 'image_advanced',
                'max_file_uploads' => 1
            ),
            array(
                'name' => __('Show Email?', 'textdomain'),
                'id'   => 'show_social_email',
                'type' => 'checkbox'
            ),
            array(
                'name'             => 'Email Icon',
                'desc'             => 'If none specified, default will be used:<br /><img src="'.plugins_url('/images/icon-share-email.png', __FILE__).'">',
                'id'               => 'social_icon_email',
                'type'             => 'image_advanced',
                'max_file_uploads' => 1
            )
        )
    );



// appearance page

    // element styles (colors)
    $meta_boxes[] = array(
        'id'             => 'styles',
        'title'          => __('Element Styles', 'textdomain'),
        'settings_pages' => 'apicius-appearance',
        'fields'         => array(
            array(
                'name' => __('Overall Background', 'textdomain'),
                'id'   => 'apicius_bg',
                'type' => 'color'
            ),
            array(
                'name' => __('Overall Text Color', 'textdomain'),
                'id'   => 'text_color',
                'type' => 'color'
            ),
            array(
                'name' => __('Archive Single Tile Border (leave empty for no border)', 'textdomain'),
                'id'   => 'tile_border',
                'type' => 'color',
                'std'  => ''
            ),
            array(
                'name' => __('Archive Single Tile Title Background', 'textdomain'),
                'id'   => 'tile_title_bg',
                'type' => 'color',
                'std'  => '#ffffff'
            ),
            array(
                'name' => __('Archive Single Tile Title Text', 'textdomain'),
                'id'   => 'tile_title_text',
                'type' => 'color',
                'std'  => '#000000'
            ),
            array(
                'name' => __('Archive Single Tile Title Border', 'textdomain'),
                'id'   => 'tile_title_border',
                'type' => 'color',
                'std'  => '#000000'
            ),
            array(
                'name' => __('Archive Filters Background', 'textdomain'),
                'id'   => 'filter_bg',
                'type' => 'color',
                'std'  => '#f4f4f4'
            ),
            array(
                'name' => __('Archive Filters Border', 'textdomain'),
                'id'   => 'filter_border',
                'type' => 'color',
                'std'  => '#808080'
            ),
            array(
                'name' => __('Archive Filters Text', 'textdomain'),
                'id'   => 'filter_text',
                'type' => 'color',
                'std'  => '#000000'
            )
        )
    );


    // custom placeholder images
    $meta_boxes[] = array(
        'id'             => 'custom_placeholders',
        'title'          => __('Custom Placeholder Images', 'textdomain'),
        'settings_pages' => 'apicius-appearance',
        'fields'         => array(
            array(
                'name'             => 'Recipe placeholder',
                'desc'             => 'if none specified, default will be used<br /><img src="'.plugins_url('/images/ph_recipe.jpg', __FILE__).'">',
                'id'               => 'ph_recipe',
                'type'             => 'image_advanced',
                'max_file_uploads' => 1
            ),
            array(
                'name'             => 'Product placeholder',
                'desc'             => 'if none specified, default will be used<br /><img src="'.plugins_url('/images/ph_product.jpg', __FILE__).'">',
                'id'               => 'ph_product',
                'type'             => 'image_advanced',
                'max_file_uploads' => 1
            )
        )
    );

    return $meta_boxes;
}

//endregion



/////////////////////////////////////////////////////////////////////
//region add a "Settings" link in the Apicius entry in the Plugin list
add_filter('plugin_action_links', 'apicius_plugin_action_links', 10, 2);

function apicius_plugin_action_links($links, $file) {
    static $this_plugin;

    if (!$this_plugin) {
        $this_plugin = plugin_basename(__FILE__);
    }

    if ($file == $this_plugin) {
        $settings_link = '<a href="' . get_bloginfo('wpurl') . '/wp-admin/admin.php?page=apicius-settings">Information &amp; Settings</a>';
        array_unshift($links, $settings_link);
    }

    return $links;
}
//endregion



/////////////////////////////////////////////////////////////////////
//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('packery', plugins_url('/js/packery-mode.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-js', plugins_url('/js/scripts.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__));
}

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


/////////////////////////////////////////////////////////////////////
//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'         => false,
        '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_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_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_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_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_include_field($meta_box) {
    // get settings for using fields
    $settings = get_option('apicius');
    $box_slug = $meta_box['id'];

    if (isset($settings[ 'use_'.$box_slug ]) && ($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 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 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-js');

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

    global $post;

    $apicius_settings = get_option('apicius');

    //region styles
    $apicius_overall = '';

    $filter_styles = '';

    $title_styles = '';

    $tile_styles = '';

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


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


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


    if (!empty($apicius_settings['tile_title_bg'])) {
        $title_styles .= 'background-color: '.$apicius_settings['tile_title_bg'].'; ';
    }
    if (!empty($apicius_settings['tile_title_text'])) {
        $title_styles .= 'color: '.$apicius_settings['tile_title_text'].'; ';
    }
    if (!empty($apicius_settings['tile_title_border'])) {
        $title_styles .= 'border-color: '.$apicius_settings['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);
        }

    endwhile;
    endif;
    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();
    ?>
    <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 product category dropdown ?>
                <?php if ($apicius_settings['show_prod_cat_dropdown'] === 1) { ?>
                    <div 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) {
                                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 ?>
                <div 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 //endregion ?>

                <?php //region recipe type tiles ?>
                <div 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 //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>
            <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()) {
                        // this only gets set to true if one of its products is in the "exclude" categories chosen in the admin
                        $skip = false;

                        $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.' ';
                            }
                        }
                        // 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;
                                    }
                                }
                            }
                        }
                        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 -->
        </div>
    </div>
    <?php
    return preg_replace('/\s+/', ' ', ob_get_clean());
}

add_shortcode('apicius', '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-js');

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

        global $post;

// we are ditching $content entirely.  :)

        $apicius_settings = get_option('apicius');

        $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">
                <div class="row">
                    <div class="col-sm-6">


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

                        <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 endif; ?>
                        </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 social
                        ?>
                        <?php if ($apicius_settings['show_social'] === 1) { ?>
                            <?php
                            if (!empty($apicius_settings['social_icon_spacing']) || $apicius_settings['social_icon_spacing'] === '0') {
                                $icon_spacing = 'style="margin-right: '.$apicius_settings['social_icon_spacing'].'px;"';
                            } else {
                                $icon_spacing = '';
                            }
                            ?>

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

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

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

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

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

                                <?php if (!empty($apicius_settings['show_social_email'])) { ?>
                                    <?php
                                    if (!empty($apicius_settings['social_icon_email'])) {
                                        $email_pic = wp_get_attachment_image_src($apicius_settings['social_icon_email'][0])[0];
                                    } else {
                                        $email_pic = plugins_url('/images/icon-share-email.png', __FILE__);
                                    }
                                    ?>
                                    <a href="mailto:?subject=House-Autry Recipe: <?php the_title(); ?>&body=Take a look at the <?php the_title(); ?> recipe from <?php bloginfo('name'); ?>: <?php the_permalink(); ?>"><img
                                            src="<?=$email_pic?>"
                                            <?=$icon_spacing?>
                                            alt="Share with Email" /></a>
                                <?php } ?>
                            </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) { ?>
                                <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="<?=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><br />
                                                <a class="buy-now printhide" href="<?=get_permalink($productID)?>">Buy
                                                    Now</a>
                                            </div>
                                        </div>

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

                        <?php //endregion
                        ?>
                    </div>

                    <div class="col-sm-6">
                        <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 endif; ?>
                        </div>

                        <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']);
                                    }
                                }
                                ?>
                            </div>
                        </div>

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











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

                    </div>
                </div>

                <?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' => 3,
                        '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><!-- /related_recipes -->
                        <?php
                    }
                    wp_reset_postdata();
                    ?>
                <?php } ?>


            </div><!-- /container-fluid -->
        </div><!-- /#recipe_single -->


        <?php
        $content = ob_get_clean();

    endif;


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

// override any usage of the_title() with null.
// my plugin uses $post->post_title instead.
function apicius_remove_title($title, $id = null) {
    if (is_singular('recipe') && get_post_type($id) == 'recipe') {
        return '';
    }

    return $title;
}

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






