<?php
/*
Plugin Name: Connections Slim Plus - Template
Plugin URI: http://www.connections-pro.com
Description: Connections Slim Plus - Template
Version: 2.0
Author: Steven A. Zahm
Author URI: http://www.connections-pro.com
Text Domain: connections_slim

Copyright 2013  Steven A. Zahm  (email : shazahm1@hotmail.com)

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2, as
published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

if ( ! class_exists( 'CN_Slim_Plus' ) ) {

	class CN_Slim_Plus {

		/**
		 * Stores a copy of the shortcode $atts for use throughout the class.
		 *
		 * @access private
		 * @since 1.0
		 * @var (array)
		 */
		private static $atts;

		/**
		 * Stores an initialized instance of cnTemplate.
		 *
		 * @access private
		 * @since 1.0
		 * @var (object)
		 */
		private static $template;

		/**
		 * Setup the template.
		 *
		 * @access public
		 * @since 1.0
		 * @param (object) $template An initialized instance of the cnTemplate class.
		 * @return (void)
		 */
		public function __construct( $template ) {

			self::$template = $template;

			if ( ! is_admin() ) {

				// Register the required JS file.
				add_filter( 'cn_template_required_js-' . $template->getSlug(), array( __CLASS__, 'enqueueJS' ) );

				//Update the permitted shortcode attribute the user may use and override the template defaults as needed.
				add_filter( 'cn_list_atts_permitted-' . $template->getSlug() , array( __CLASS__, 'initShortcodeAtts') );
				add_filter( 'cn_list_atts-' . $template->getSlug() , array( __CLASS__, 'initTemplateOptions') );
			}
		}

		public static function register() {

			$atts = array(
				'class'       => 'CN_Slim_Plus',
				'name'        => 'Slim Plus',
				'type'        => 'all',
				'version'     => '2.0',
				'author'      => 'Steven A. Zahm',
				'authorURL'   => 'connections-pro.com',
				'description' => 'Shows the Entry\'s name and when clicked it will reveal the additional contact details.',
				'path'        => plugin_dir_path( __FILE__ ),
				'url'         => plugin_dir_url( __FILE__ ),
				);

			cnTemplateFactory::register( $atts );

			// License and Updater.
			if ( class_exists( 'cnLicense' ) ) {

				new cnLicense( __FILE__, 'Slim Plus', '2.0', 'Steven A. Zahm' );
			}
		}

		/**
		 * Enqueue the template's JS file.
		 *
		 * @access private
		 * @since 1.0
		 * @uses wp_enqueue_script()
		 * @return (void)
		 */
		public static function enqueueJS( $required ) {

			$required[] = 'jquery-chosen';

			return $required;
		}


		/**
		 * Initiate the permitted template shortcode options and load the default values.
		 *
		 * @access private
		 * @since 1.0
		 * @param  (array)  $permittedAtts The shortcode $atts array.
		 * @return (array)
		 */
		public static function initShortcodeAtts( $permittedAtts = array() ) {

			// Grab an instance of the Connections object.
			$instance = Connections_Directory();

			$addressLabel = $instance->options->getDefaultAddressValues();
			$phoneLabel   = $instance->options->getDefaultPhoneNumberValues();
			$emailLabel   = $instance->options->getDefaultEmailValues();

			$permittedAtts['enable_search']                   = TRUE;

			$permittedAtts['enable_pagination']               = TRUE;
			$permittedAtts['page_limit']                      = 20;
			$permittedAtts['pagination_position']             = 'after';

			$permittedAtts['enable_category_select']          = TRUE;
			$permittedAtts['show_empty_categories']           = TRUE;
			$permittedAtts['show_category_count']             = FALSE;
			$permittedAtts['category_select_position']        = 'before';
			$permittedAtts['enable_category_by_root_parent']  = FALSE;
			$permittedAtts['enable_category_multi_select']    = FALSE;
			$permittedAtts['enable_category_group_by_parent'] = FALSE;

			$permittedAtts['enable_bio']                      = TRUE;
			$permittedAtts['enable_bio_head']                 = TRUE;
			$permittedAtts['enable_note']                     = TRUE;
			$permittedAtts['enable_note_head']                = TRUE;

			$permittedAtts['show_title']                      = TRUE;
			$permittedAtts['show_org']                        = TRUE;
			$permittedAtts['show_contact_name']               = TRUE;
			$permittedAtts['show_family']                     = TRUE;
			$permittedAtts['show_addresses']                  = TRUE;
			$permittedAtts['show_phone_numbers']              = TRUE;
			$permittedAtts['show_email']                      = TRUE;
			$permittedAtts['show_im']                         = TRUE;
			$permittedAtts['show_social_media']               = TRUE;
			$permittedAtts['show_dates']                      = TRUE;
			$permittedAtts['show_links']                      = TRUE;

			$permittedAtts['address_types']                   = NULL;
			$permittedAtts['phone_types']                     = NULL;
			$permittedAtts['email_types']                     = NULL;
			$permittedAtts['date_types']                      = NULL;
			$permittedAtts['link_types']                      = NULL;

			$permittedAtts['image']                           = 'photo';
			$permittedAtts['image_fallback']                  = 'block';

			$permittedAtts['str_select']                      = 'Select Category';
			$permittedAtts['str_select_all']                  = 'Show All Categories';
			$permittedAtts['str_image']                       = 'No Photo Available';
			$permittedAtts['str_bio_head']                    = 'Biography';
			$permittedAtts['str_note_head']                   = 'Notes';
			$permittedAtts['str_contact']                     = 'Contact';
			$permittedAtts['str_home_addr']                   = 'Hometown';
			$permittedAtts['str_work_addr']                   = 'Current Location';
			$permittedAtts['str_school_addr']                 = $addressLabel['school'];
			$permittedAtts['str_other_addr']                  = $addressLabel['other'];
			$permittedAtts['str_home_phone']                  = $phoneLabel['homephone'];
			$permittedAtts['str_home_fax']                    = $phoneLabel['homefax'];
			$permittedAtts['str_cell_phone']                  = $phoneLabel['cellphone'];
			$permittedAtts['str_work_phone']                  = '';
			$permittedAtts['str_work_fax']                    = $phoneLabel['workfax'];
			$permittedAtts['str_personal_email']              = '';
			$permittedAtts['str_work_email']                  = '';

			$permittedAtts['name_format']                     = '%prefix% %first% %middle% %last% %suffix%';
			$permittedAtts['contact_name_format']             = '%label%: %first% %last%';
			$permittedAtts['addr_format']                     = '%label% %line1% %line2% %line3% %city% %state%  %zipcode% %country%';
			$permittedAtts['email_format']                    = '%address%';
			$permittedAtts['phone_format']                    = '%number%';
			$permittedAtts['link_format']                     = '%label%%separator% %title%';
			$permittedAtts['date_format']                     = '%label%%separator% %date%';

			$permittedAtts['color']                           = '#00508D';

			return $permittedAtts;
		}

		/**
		 * Initiate the template options using the user supplied shortcode option values.
		 *
		 * @access private
		 * @since 1.0
		 * @param  (array)  $atts The shortcode $atts array.
		 * @return (array)
		 */
		public static function initTemplateOptions( $atts ) {

			// Because the shortcode option values are treated as strings some of the values have to converted to boolean.
			cnFormatting::toBoolean( $atts['enable_search'] );
			cnFormatting::toBoolean( $atts['enable_pagination'] );
			cnFormatting::toBoolean( $atts['enable_category_select'] );
			cnFormatting::toBoolean( $atts['show_empty_categories'] );
			cnFormatting::toBoolean( $atts['show_category_count'] );
			cnFormatting::toBoolean( $atts['enable_category_by_root_parent'] );
			cnFormatting::toBoolean( $atts['enable_category_multi_select'] );
			cnFormatting::toBoolean( $atts['enable_category_group_by_parent'] );
			cnFormatting::toBoolean( $atts['enable_bio'] );
			cnFormatting::toBoolean( $atts['enable_bio_head']);
			cnFormatting::toBoolean( $atts['enable_note'] );
			cnFormatting::toBoolean( $atts['enable_note_head'] );

			cnFormatting::toBoolean( $atts['show_title'] );
			cnFormatting::toBoolean( $atts['show_org'] );
			cnFormatting::toBoolean( $atts['show_contact_name'] );
			cnFormatting::toBoolean( $atts['show_family'] );
			cnFormatting::toBoolean( $atts['show_addresses'] );
			cnFormatting::toBoolean( $atts['show_phone_numbers'] );
			cnFormatting::toBoolean( $atts['show_email'] );
			cnFormatting::toBoolean( $atts['show_im'] );
			cnFormatting::toBoolean( $atts['show_social_media'] );
			cnFormatting::toBoolean( $atts['show_dates'] );
			cnFormatting::toBoolean( $atts['show_links'] );

			// If displaying a signle entry, no need to display category select, search and pagination.
			if ( get_query_var( 'cn-entry-slug' ) ) {
				$atts['enable_search']          = FALSE;
				$atts['enable_pagination']      = FALSE;
				$atts['enable_category_select'] = FALSE;
			}

			add_filter( 'cn_phone_number' , array( __CLASS__, 'phoneLabels') );
			add_filter( 'cn_email_address' , array( __CLASS__, 'emailLabels') );
			add_filter( 'cn_address' , array( __CLASS__, 'addressLabels') );

			// Start the form.
			add_action( 'cn_action_list_before-' . self::$template->getSlug() , array( __CLASS__, 'formOpen'), -1 );

			// If search is enabled, add the appropiate filters.
			if ( $atts['enable_search'] ) {
				add_filter( 'cn_list_retrieve_atts-' . self::$template->getSlug() , array( __CLASS__, 'limitList'), 10 );
				add_action( 'cn_action_list_before-' . self::$template->getSlug() , array( __CLASS__, 'searchForm') , 1 );
			}

			// If pagination is enabled add the appropiate filters.
			if ( $atts['enable_pagination'] ) {
				add_filter( 'cn_list_retrieve_atts-' . self::$template->getSlug() , array( __CLASS__, 'limitList'), 10 );
				add_action( 'cn_action_list_' . $atts['pagination_position'] . '-' . self::$template->getSlug() , array( __CLASS__, 'listPages') );
			}

			// If the category select/filter feature is enabled, add the appropiate filters.
			if ( $atts['enable_category_select'] ) {
				add_filter( 'cn_list_retrieve_atts-' . self::$template->getSlug() , array( __CLASS__, 'setCategory') );
				add_action( 'cn_action_list_' . $atts['category_select_position'] . '-' . self::$template->getSlug() , array( __CLASS__, 'categorySelect') , 5 );
			}

			// Close the form
			add_action( 'cn_action_list_after-' . self::$template->getSlug() , array( __CLASS__, 'formClose'), 11 );

			// Store a copy of the shortcode $atts to be used in other class methods.
			self::$atts = $atts;

			return $atts;
		}

		/**
		 * Alter the Address Labels.
		 *
		 * @access private
		 * @since 1.0
		 * @param (object) $data
		 * @return (object)
		 */
		public static function addressLabels( $data ) {

			switch ( $data->type ) {
				case 'home':
					$data->name = self::$atts['str_home_addr'];
					break;
				case 'work':
					$data->name = self::$atts['str_work_addr'];
					break;
				case 'school':
					$data->name = self::$atts['str_school_addr'];
					break;
				case 'other':
					$data->name = self::$atts['str_other_addr'];
					break;
			}

			return $data;
		}

		/**
		 * Alter the Phone Labels.
		 *
		 * @access private
		 * @since 1.0
		 * @param (object) $data
		 * @return (object)
		 */
		public static function phoneLabels( $data ) {

			switch ( $data->type ) {
				case 'homephone':
					$data->name = self::$atts['str_home_phone'];
					break;
				case 'homefax':
					$data->name = self::$atts['str_home_fax'];
					break;
				case 'cellphone':
					$data->name = self::$atts['str_cell_phone'];
					break;
				case 'workphone':
					$data->name = self::$atts['str_work_phone'];
					break;
				case 'workfax':
					$data->name = self::$atts['str_work_fax'];
					break;
			}

			return $data;
		}

		/**
		 * Alter the Email Labels.
		 *
		 * @access private
		 * @since 1.0
		 * @param (object) $data
		 * @return (object)
		 */
		public static function emailLabels( $data ) {

			switch ( $data->type ) {
				case 'personal':
					$data->name = self::$atts['str_personal_email'];
					break;
				case 'work':
					$data->name = self::$atts['str_work_email'];
					break;

				default:
					$data->name = 'Email';
				break;
			}

			return $data;
		}

		/**
		 * Limit the returned results.
		 *
		 * @access private
		 * @since 1.0
		 * @param (array) $atts The shortcode $atts array.
		 * @return (array)
		 */
		public static function limitList( $atts ) {

			// $atts['limit'] = $this->pageLimit; // Page Limit
			$atts['limit'] = empty( $atts['limit'] ) ? $atts['page_limit'] : $atts['limit'];

			return $atts;
		}

		/**
		 * Echo the form beginning.
		 *
		 * @access private
		 * @since 1.0
		 * @return (void)
		 */
		public static function formOpen( $atts ) {

			cnTemplatePart::formOpen( $atts );
		}

		/**
		 * Echo the form ending.
		 *
		 * @access private
		 * @since 1.0
		 * @return (void)
		 */
		public static function formClose() {

		    cnTemplatePart::formClose();
		}

		/**
		 * Output the search input fields.
		 *
		 * @access private
		 * @since 1.0
		 * @return (void)
		 */
		public static function searchForm() {

			cnTemplatePart::search();
		}

		/**
		 * Output the pagination control.
		 *
		 * @access private
		 * @since 1.0
		 * @return (void)
		 */
		public static function listPages() {

			cnTemplatePart::pagination( array( 'limit' => self::$atts['page_limit'] ) );

		}

		/**
		 * Outputs the category select list.
		 *
		 * @access private
		 * @since 1.0
		 * @return (void)
		 */
		public static function categorySelect() {

			$atts = array(
				'default'    => self::$atts['str_select'] ,
				'select_all' => self::$atts['str_select_all'],
				'type'       => self::$atts['enable_category_multi_select'] ? 'multiselect' : 'select',
				'group'      => self::$atts['enable_category_group_by_parent'],
				'show_count' => self::$atts['show_category_count'],
				'show_empty' => self::$atts['show_empty_categories'],
				'parent_id'  => self::$atts['enable_category_by_root_parent'] ? self::$atts['category'] : array(),
				'exclude'    => self::$atts['exclude_category'],
				);

			cnTemplatePart::category( $atts );
		}

		/**
		 * Alters the shortcode attribute values before the query is processed.
		 *
		 * @access private
		 * @since 1.0
		 * @param  (array)  $atts The shortcode $atts array.
		 * @return (array)
		 */
		public static function setCategory( $atts ) {

			if ( $atts['enable_category_multi_select'] ) {

				if ( get_query_var('cn-cat') ) $atts['category_in'] = get_query_var('cn-cat');
				remove_query_arg( 'cn-cat' );

			}

			return $atts;
		}

	}

	// Register the template.
	add_action( 'cn_register_template', array( 'CN_Slim_Plus', 'register' ) );
}
