<?php
/**
 * Register YOLO Event.
 * This file register Item and Category for YOLO Event.
 *
 * @package    YOLO Framework
 * @subpackage YOLO Event
 * @version    1.0.0
 * @author     GDragon <longdt@yolotheme.com>
 * @copyright  Copyright (c) 2015, YoloTheme
 * @license    http://opensource.org/licenses/gpl-2.0.php GPL v2 or later
 * @link       http://yolotheme.com
 */

if( !class_exists('Yolo_Event') ):

    class Yolo_Event {

        public function __construct(){
            add_action( 'init', array($this, 'yolo_event_register_post_type' ));
            add_action( 'save_post', array( &$this, 'yolo_event_save_activities_meta_box'), 1, 2 );
            add_action( 'save_post', array( &$this, 'yolo_event_save_event_contact_meta_box'), 1, 2 );
            add_action ( 'admin_enqueue_scripts', array( &$this,'yolo_admin_enqueue_scripts' ));
            if( is_admin() ){
                add_action('add_meta_boxes', array($this,'yolo_event_register_meta_box'));
            }
        }

        public function yolo_admin_enqueue_scripts(){
            wp_register_style( 'yolo-style-admin', YOLO_PLUGIN_PATH . '/assets/css/yolo-admin.css' );
            wp_enqueue_style( 'yolo-style-admin' );
            wp_enqueue_script('yolo-properties-admin', YOLO_PLUGIN_PATH . '/assets/js/properties.js', array('jquery'), null, true );

        }

        public function yolo_event_register_post_type() {

            // Text for YOLO Event.
            $event_labels = array(
                'name'                  => __('Events', 'yolo-kidzone') ,
                'singular_name'         => __('Events', 'yolo-kidzone') ,
                'menu_name'             => __('Events', 'yolo-kidzone') ,
                'add_new'               => __('Add New', 'yolo-kidzone') ,
                'add_new_item'          => __('Add New Event Item', 'yolo-kidzone') ,
                'edit_item'             => __('Edit Event Item', 'yolo-kidzone') ,
                'new_item'              => __('Add New Event Item', 'yolo-kidzone') ,
                'view_item'             => __('View Event', 'yolo-kidzone') ,
                'search_items'          => __('Search Event', 'yolo-kidzone') ,
                'not_found'             => __('No Event items found', 'yolo-kidzone') ,
                'not_found_in_trash'    => __('No Event items found in trash', 'yolo-kidzone') ,
                'parent_item_colon'     => ''
            );

            $admin_icon = YOLO_PLUGIN_PATH . '/assets/images/yolo20x20.png';
            if ( floatval( get_bloginfo( 'version' ) ) >= 3.8 ) {
                $admin_icon = 'dashicons-camera';
            }

            $event_slug = 'yolo-event';

            // Options
            $event_args = array(
                'labels'                => $event_labels,
                'public'                => true,
                'publicly_queryable'    => true,
                'show_ui'               => true,
                'show_in_nav_menus'     => true,
                'show_in_menu'          => true,
                'menu_position'         => 5,
                'menu_icon'             => $admin_icon,
                'capability_type'       => 'post',
                'hierarchical'          => false,
                'supports'              => array(
                    'title',
                    'editor',
                    'excerpt',
                    'thumbnail',
                    'comments',
                    'revisions'
                ) ,
                'has_archive'           => true,
                'rewrite'               => array(
                    'slug'          => $event_slug,
                    'with_front'    => false
                )
            );

            register_post_type('event', $event_args);

            // Register a taxonomy for Event Categories.
            $category_labels = array(
                'name'                          => __('Event Categories', 'yolo-kidzone') ,
                'singular_name'                 => __('Event Category', 'yolo-kidzone') ,
                'menu_name'                     => __('Event Categories', 'yolo-kidzone') ,
                'all_items'                     => __('All Event Categories', 'yolo-kidzone') ,
                'edit_item'                     => __('Edit Event Category', 'yolo-kidzone') ,
                'view_item'                     => __('View Event Category', 'yolo-kidzone') ,
                'update_item'                   => __('Update Event Category', 'yolo-kidzone') ,
                'add_new_item'                  => __('Add New Event Category', 'yolo-kidzone') ,
                'new_item_name'                 => __('New Event Category Name', 'yolo-kidzone') ,
                'parent_item'                   => __('Parent Event Category', 'yolo-kidzone') ,
                'parent_item_colon'             => __('Parent Event Category:', 'yolo-kidzone') ,
                'search_items'                  => __('Search Event Categories', 'yolo-kidzone') ,
                'popular_items'                 => __('Popular Event Categories', 'yolo-kidzone') ,
                'separate_items_with_commas'    => __('Separate Event Categories with commas', 'yolo-kidzone') ,
                'add_or_remove_items'           => __('Add or remove Event Categories', 'yolo-kidzone') ,
                'choose_from_most_used'         => __('Choose from the most used Event Categories', 'yolo-kidzone') ,
                'not_found'                     => __('No Event Categories found', 'yolo-kidzone') ,
            );

            $category_args = array(
                'labels'                        => $category_labels,
                'public'                        => true,
                'show_ui'                       => true,
                'show_in_nav_menus'             => false,
                'show_tagcloud'                 => false,
                'show_admin_column'             => true,
                'hierarchical'                  => true,
                'query_var'                     => true,
                'rewrite'                       => array(
                    'slug'          => 'event_category',
                    'with_front'    => false
                ) ,
            );

            register_taxonomy('event_category', array( 'event' ) , $category_args);

            // Register a taxonomy for Event Location
            $location_labels = array(
                'name'                          => __( 'Event Location', 'yolo-kidzone' ),
                'singular_name'                 => __( 'Event Location', 'yolo-kidzone' ),
                'menu_name'                     => __( 'Event Location', 'yolo-kidzone' ) ,
                'all_items'                     => __( 'All Event Location', 'yolo-kidzone' ) ,
                'edit_item'                     => __( 'Edit Event Location', 'yolo-kidzone' ) ,
                'view_item'                     => __( 'View Event Location', 'yolo-kidzone' ) ,
                'update_item'                   => __( 'Update Event Location', 'yolo-kidzone' ) ,
                'add_new_item'                  => __( 'Add New Event Location', 'yolo-kidzone' ) ,
                'new_item_name'                 => __( 'New Event Location Name', 'yolo-kidzone' ) ,
                'parent_item'                   => __( 'Parent Event Location', 'yolo-kidzone' ) ,
                'parent_item_colon'             => __( 'Parent Event Location:', 'yolo-kidzone' ) ,
                'search_items'                  => __( 'Search Event Location', 'yolo-kidzone' ) ,
                'popular_items'                 => __( 'Popular Event Location', 'yolo-kidzone' ) ,
                'separate_items_with_commas'    => __( 'Separate Event Location with commas', 'yolo-kidzone' ) ,
                'add_or_remove_items'           => __( 'Add or remove Event Location', 'yolo-kidzone' ) ,
                'choose_from_most_used'         => __( 'Choose from the most used Event Location', 'yolo-kidzone' ) ,
                'not_found'                     => __( 'No Event Location found', 'yolo-kidzone' )
            );

            $location_args = array(
                'labels'                        => $location_labels,
                'public'                        => false,
                'show_ui'                       => true,
                'show_in_nav_menus'             => false,
                'show_tagcloud'                 => false,
                'show_admin_column'             => true,
                'hierarchical'                  => true,
                'query_var'                     => true,
                'rewrite'                       => array(
                    'slug'          => 'event_location',
                    'with_front'    => false
                ) ,
            );

            register_taxonomy('event_location', array( 'event' ) , $location_args);
        }

        public function yolo_event_register_meta_box() {
            // Declare helper object
            $prefix = '_yolo_wp_post';
            $helper = new YOLO_Meta_Boxes_Helper($prefix, array(
                'page' => 'event'
            ));
            // Information fields
            $meta_box = array(
                'id'                => "{$prefix}_meta_box_event",
                'title'             => __('Event options', 'yolo-kidzone'),
                'fields'            => array(
                    array(
                        'id'    => "{$prefix}_start_time",
                        'label' => __( 'Start Time', 'yolo-kidzone' ),
                        'type'  => 'datetimepicker',
                    ),
                    array(
                        'id'    => "{$prefix}_end_time",
                        'label' => __( 'End Time', 'yolo-kidzone' ),
                        'type'  => 'datetimepicker',
                    ),
                    array(
                        'id'    => "{$prefix}_address",
                        'label' => __( 'Event Address', 'yolo-kidzone' ),
                        'type'  => 'text',
                    ),
                    array(
                        'id'    => "{$prefix}_phone",
                        'label' => __( 'Event Phone', 'yolo-kidzone' ),
                        'type'  => 'text',
                    ),
                    array(
                        'id'    => "{$prefix}_email",
                        'label' => __( 'Event Email', 'yolo-kidzone' ),
                        'type'  => 'text',
                    )
                )
            );

            $helper->add_meta_box( $meta_box );

            // Event Contact Form
            $meta_box = array(
                'id'        => "{$prefix}_meta_box_event_contact",
                'title'     => __('Event Contact Form', 'yolo-kidzone'),
                'fields'    => array(
                    array(
                        'id'        => "{$prefix}_event_contact",
                        'type'      => 'contact',
                        'callback'  =>  array($this,'yolo_event_contact_meta_box_callback')
                    )
                )
            );

            $helper->add_meta_box( $meta_box );

            // Event Activities
            $meta_box = array(
                'id'        => "{$prefix}_meta_box_activities",
                'title'     => __('Event Activities', 'yolo-kidzone'),
                'fields'    => array(
                    array(
                        'id'        => "{$prefix}_event_activities",
                        'type'      => 'activities',
                        'callback'  =>  array($this,'yolo_event_meta_box_callback')
                    )
                )
            );

            $helper->add_meta_box( $meta_box );

            // Google map
            $meta_box = array(
                'id'                => "{$prefix}_meta_box_map",
                'title'             => __('Place in Map', 'yolo-kidzone'),
                'fields'            => array(
                    array(
                        'id'    => "{$prefix}_google_maps",
                        'type'  => 'google_map'
                    ),    
                    array( 
                        'id' => '_gmap_latitude',
                        'default'=>'40.71421714027808',
                        'type' => 'hidden',
                    ),
                    array( 
                        'id' => '_gmap_longitude',
                        'default'=>'-74.00538682937622',
                        'type' => 'hidden',
                    ),
                    array( 
                        'label' => __( 'Enable Google Street View', 'yolo-kidzone' ), 
                        'id' => '_gmap_street_view', 
                        'type' => 'checkbox' )
                    )
            );

            $helper->add_meta_box( $meta_box );

            // Page setting - Single Event
            $meta_box = array(
                'id' => "{$prefix}_meta_box_single_page",
                'title' => esc_html__( 'Page Settings: Single Event', 'yolo-kidzone' ),
                'description' => esc_html__( 'Choose various setting for your Single Event page.', 'yolo-kidzone' ),
                'fields' => array(
                    array(
                        'label' => esc_html__( 'Page Layout', 'yolo-kidzone' ),
                        'id' => "{$prefix}_global_setting",
                        'type' => 'page_layout',
                    ),
                    array(
                        'label' => esc_html__( 'Override Global Settings?', 'yolo-kidzone' ),
                        'id' => "{$prefix}_override_layout",
                        'type' => 'checkbox',
                        'child-fields' => array(
                            'on' => "{$prefix}_layout,{$prefix}_sidebar"
                        ),
                    ),
                    array(
                        'label' => esc_html__( 'Page Layout', 'yolo-kidzone' ),
                        'id' => "{$prefix}_layout",
                        'type' => 'radio',
                        'std' => 'sidebar',
                        'options' => array(
                            'fullwidth' => array(
                                'label' => esc_html__( 'Full-Width', 'yolo-kidzone' ),
                                'value' => 'fullwidth',
                            ),
                            'sidebar' => array(
                                'label' => esc_html__( 'With Right Sidebar', 'yolo-kidzone' ),
                                'value' => 'sidebar',
                            ),
                            'left_sidebar' => array(
                                'label' => esc_html__( 'With Left Sidebar', 'yolo-kidzone' ),
                                'value' => 'left_sidebar',
                            ),
                        ),
                        // 'child-fields' => array(
                        //  'sidebar' => "{$prefix}_sidebar",
                        //  'left_sidebar' => "{$prefix}_sidebar",
                        // ),
                        
                    ),
                    array(
                        'label' => esc_html__( 'Event Sidebar', 'yolo-kidzone' ),
                        'id' => "{$prefix}_sidebar",
                        'type' => 'sidebars',
                        'std' => 'sidebar-main'
                    ),
                )
            );

            if( yolo_get_option('yolo_page_heading', true) ) {
                $meta_box['fields'][] = array( 'type' => 'divider' );
                $meta_box['fields'][] = array(
                                    'id'    => '_heading_image',
                                    'label' => esc_html__( 'Heading Background Image', 'yolo-kidzone' ),
                                    'desc'  => esc_html__( 'An unique heading image for this post. If leave it blank, the default heading image of Blog ( in Customizer settings ) will be used.', 'yolo-kidzone'),
                                    'type'  => 'image',
                                );
            }

            $helper->add_meta_box( $meta_box );
        }

        // Event Activities Functions
        function yolo_event_meta_box_callback( $post, $id, $type, $meta, $std, $field ) {
            ?>
            <div class="yolo-activities-meta-box">
                <strong><?php _e('Event Activities:','yolo-kidzone')?></strong><br>
                <?php wp_nonce_field( '_yolo_activities_meta_box_save', '_yolo_activities_meta_box_nonce' ); ?>
                <table class="widefat">
                    <thead>
                    <tr>
                        <th class="sort">&nbsp;</th>
                        <th width="70%" colspan="2"><?php _e( 'Activities', 'yolo-kidzone' ); ?> </th>
                        <th>&nbsp;</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php
                    $activities = get_post_meta( $post->ID, '_event_activities', true );

                    if($activities){
                        foreach ( (array)$activities as $key => $activity ) :
                            echo $this->yolo_event_activities_meta_box_row( $key, $activity );
                        endforeach;
                    }
                    ?>
                    </tbody>
                    <tfoot>
                    <tr>
                        <th colspan="5">
                            <a href="#" class="button insert" data-row="<?php echo esc_attr($this->yolo_event_activities_meta_box_row( $key='', $activity='' )); ?>"><?php _e( 'Add Activities', 'yolo-kidzone' ); ?></a>
                        </th>
                    </tr>
                    </tfoot>
                </table>
            </div>
            <?php
        }

        function yolo_event_activities_meta_box_row( $key, $activity ) {
            ob_start();
            ?>
            <tr>
                <td class="sort"></td>
                <td class="file_value">
                    <input type="text" class="input_text" placeholder="<?php _e( 'Activity Name', 'yolo-kidzone' ); ?>" name="_yolo_event_activities_name[]" value="<?php if( isset($key) && $key !='' ): echo esc_attr($key); endif; ?>" />
                    <input type="text" class="input_text" placeholder="Value" name="_yolo_event_activities_value[]" value="<?php if( isset($activity) && $activity !='' ): echo esc_attr($activity); endif; ?>">
                </td>
                <td width="1%"><a href="#" class="delete"><?php _e( 'Delete', 'yolo-kidzone' ); ?></a></td>
            </tr>
            <?php
            return ob_get_clean();
        }

        function yolo_event_save_activities_meta_box($post_id, $post) {


            if ( defined( 'DOING_AUTOSAVE' ) || is_int( wp_is_post_revision( $post ) ) || is_int( wp_is_post_autosave( $post ) ) ) {
                return;
            }

            if ( ! isset( $_POST['_yolo_activities_meta_box_nonce'] ) || ! isset( $_POST['_yolo_activities_meta_box_nonce'] ) || ! wp_verify_nonce( $_POST['_yolo_activities_meta_box_nonce'], '_yolo_activities_meta_box_save' ) )
                return;
            // Check the post being saved == the $post_id to prevent triggering this call for other save_post events
            if ( empty( $_POST['post_ID'] ) || $_POST['post_ID'] != $post_id ) {
                return;
            }
            // Check user has permission to edit
            if ( ! current_user_can( 'edit_post', $post_id ) ) {
                return;
            }

            $activities = array();
            $activities_name           = isset( $_POST['_yolo_event_activities_name'] )  ? array_map( 'trim', $_POST['_yolo_event_activities_name'] ) : array();
            $activities_value           = isset( $_POST['_yolo_event_activities_value'] )  ? array_map( 'trim', $_POST['_yolo_event_activities_value'] ) : array();
            $activities_value_size       = sizeof( $activities_value );

            for ( $i = 0; $i < $activities_value_size; $i ++ ) {
                if ( ! empty( $activities_value[ $i ] ) ) {
                    $name                   = sanitize_text_field( $activities_name[ $i ] );
                    $value                  = sanitize_text_field( $activities_value[ $i ] );
                    $activities[$name]          = $value; 
                    // $pro_hash               = $post_id.'_'.$value.wp_rand(0,100);
                    // $activities[ $pro_hash ]    = $value;
                }
            }

            update_post_meta( $post_id, '_event_activities', $activities );
        }

        // Event Contact Function
        function yolo_event_contact_meta_box_callback( $post, $id, $type, $meta, $std, $field ) {
            $post_contact = $this->yolo_get_posts_post_type( 'wpcf7_contact_form' );
            $event_contact = get_post_meta( $post->ID, '_event_contact', true );
        ?>
            <select id="yolo_event_contact" name="_yolo_event_contact_id">
                    <option value=""><?php _e( 'Select Contact Form', 'yolo-kidzone' ); ?></option>
            <?php if( $post_contact->have_posts() ) : 
                while( $post_contact->have_posts() ) :
                    $post_contact->the_post();
                ?>
                    <option value="<?php the_ID(); ?>" class="<?php echo $event_contact;  ?>" <?php selected( get_the_ID(), $event_contact, true ); ?> ><?php echo esc_html( the_title() ); ?></option>';
            <?php 
                endwhile;
            endif;
            ?>
            </select>
        <?php }

        function yolo_get_posts_post_type( $type ) {
            $yolo_args = array(
                'post_type'     => $type,
                'post_status'   => 'publish'
            );
            $yolo_query = new WP_Query( $yolo_args );

            return $yolo_query;
        }

        function yolo_event_save_event_contact_meta_box( $post_id, $post ) {

            if ( defined( 'DOING_AUTOSAVE' ) || is_int( wp_is_post_revision( $post ) ) || is_int( wp_is_post_autosave( $post ) ) ) {
                return;
            }

            // Check the post being saved == the $post_id to prevent triggering this call for other save_post events
            if ( empty( $_POST['post_ID'] ) || $_POST['post_ID'] != $post_id ) {
                return;
            }
            // Check user has permission to edit
            if ( ! current_user_can( 'edit_post', $post_id ) ) {
                return;
            }

            // Update only if post type is event - all other post type run over here (generate metabox cause this in $_POST)
            if ( get_post_type( $post ) == 'event' ) {
                $contact_id = sanitize_text_field( $_POST['_yolo_event_contact_id'] );
                update_post_meta( $post_id, '_event_contact', $contact_id );
            }
        }

    }
    new Yolo_Event();
endif;

