<?php
/**
 * Posttype class.
 *
 * @since 1.0.0
 *
 * @package owwwlab-kenburn
 * @author  owwwlab
 */
class Owlabbulkg_Posttype {

    /**
     * Holds the class object.
     *
     * @since 1.0.0
     *
     * @var object
     */
    public static $instance;

    /**
     * Path to the file.
     *
     * @since 1.0.0
     *
     * @var string
     */
    public $file = __FILE__;

    /**
     * Holds the base class object.
     *
     * @since 1.0.0
     *
     * @var object
     */
    public $base;

    public $post_type_name = 'owlabbulkg';
    public $post_type_slug;
    public $bulk_gallery_taxonomy_name = 'owlabbulkg_category';
    public $bulk_gallery_taxonomy_slug;

    /**
     * Primary class constructor.
     *
     * @since 1.0.0
     */
    public function __construct() {

        // Load the base class object.
        $this->base = Owlabbulkg::get_instance();

        //post type slug
        $gallery_slug = $this->base->get_theme_option('bulk_gallery_slug','bulk-gallery');
        $this->post_type_slug = apply_filters( 'owlab_bulk_gallery_slug', $gallery_slug );

        //taxonomy slug 
        $bulk_gallery_taxonomy = $this->base->get_theme_option('bulk_gallery_category_slug','gallery_category');
        $this->bulk_gallery_taxonomy_slug = apply_filters('owlab_bulk_gallery_taxonomy_slug',$bulk_gallery_taxonomy);


        // register post type 
        $this->register_post_type();

        // after that 
            // 1- register the taxonomy
            $this->register_taxonomy();

            // 2- add_custom_meta_to_gallery_categories
            $this->add_custom_meta_to_gallery_categories();
        
        // columns 
        
        
    }


    /*
    * register post type
    */
    public function register_post_type(){
        // Build the labels for the post type.
        $labels = apply_filters( 'owlabbulkg_post_type_labels',
            array(
                'name'               => __( 'Bulk Gallery', 'owlabbulkg' ),
                'singular_name'      => __( 'gallery', 'owlabbulkg' ),
                'add_new'            => __( 'Add New', 'owlabbulkg' ),
                'add_new_item'       => __( 'Add New', 'owlabbulkg' ),
                'edit_item'          => __( 'Edit gallery', 'owlabbulkg' ),
                'new_item'           => __( 'New gallery', 'owlabbulkg' ),
                'view_item'          => __( 'View gallery', 'owlabbulkg' ),
                'search_items'       => __( 'Search Galleries', 'owlabbulkg' ),
                'not_found'          => __( 'No galleries found.', 'owlabbulkg' ),
                'not_found_in_trash' => __( 'No galleries found in trash.', 'owlabbulkg' ),
                'parent_item_colon'  => '',
                'menu_name'          => __( 'Bulk Gallery', 'owlabbulkg' )
            )
        );

        // Build out the post type arguments.
        $args = apply_filters( 'owlabbulkg_post_type_args',
            array(

                'labels'              => $labels,
                'public'              => true,
                'publicly_queryable'  => true,
                'exclude_from_search' => false,
                'show_ui'             => true,
                'show_in_nav_menus'   => true,
                'show_in_menu'        => true,
                'show_in_admin_bar'   => true,
                'menu_position'       => 20,
                'menu_icon'           => plugins_url( 'assets/css/images/menu-icon@2x.png', $this->base->file ),
                'can_export'          => true,
                'delete_with_user'    => false,
                'capability_type'     => 'page',
                'hierarchical'        => false,
                'has_archive'         => $this->post_type_slug,
                'rewrite'             => array( 'slug' => $this->post_type_slug ),
                'supports'            => array( 'title','thumbnail','page-attributes'),
                'taxonomies'          => array( $this->bulk_gallery_taxonomy_name ),
            )
        );
        
        // Register the post type with WordPress.
        register_post_type( $this->post_type_name , $args );
    }


    /**
     * add album taxonomy for plugin post type
     * see additional help here: http://codex.wordpress.org/Function_Reference/register_taxonomy
     *
     * @since 1.0.0
     * @param      
     * @return 
     */
    public function register_taxonomy() {
        // build out the taxonomy labels
        $labels = array(
            'name'                      => __('Bulk Gallery Categories','owlabbulkg'), //general name for the taxonomy, usually plural.
            'singular_name'             => __('category','owlabbulkg'), //name for one object of this taxonomy
            'all_items'                 => __('All Categories','owlabbulkg'),
            'edit_item'                 => __('Edit category','owlabbulkg'),
            'view_item'                 => __('View category','owlabbulkg'),
            'update_item'               => __('Update category','owlabbulkg'),
            'add_new_item'              => __('Add New category','owlabbulkg'),
            'new_item_name'             => __('New category Name','owlabbulkg'),
            'parent_item'               => __('Parent category','owlabbulkg'),
            'parent_item_colon'         => __('Parent category:','owlabbulkg'),
            'search_items'              => __('Search category','owlabbulkg'),
            'popular_items'             => __('Popular categories','owlabbulkg'),
            'separate_items_with_commas' => __('Separate categories with commas','owlabbulkg'),
            'add_or_remove_items'       => __('Add or Remove categories','owlabbulkg'),
            'not_found'                 => __('No categories found','owlabbulkg')
        );
        register_taxonomy(  
            $this->bulk_gallery_taxonomy_name,  //The name of the taxonomy. Name should be in slug form 
            $this->post_type_name,        //post type name
            array(  
                'hierarchical' => true,  
                'labels'       => $labels,
                'query_var'    => $this->bulk_gallery_taxonomy_name,
                'rewrite'      => array(
                                   'slug'       => $this->bulk_gallery_taxonomy_slug, 
                                   // 'with_front' => true,
                                   // 'hierarchical' => true
                )
            )  
        );
    }

    /**
     * adds custom meta fields for taxonomy
     * will need 3 functions
     * 1- adds a field to new page
     * 2- adds a field to edit page
     * 3- save the values of the custom field from both pages
     *
     * @since 1.1.0
     * @param      
     * @return 
     */
    public function add_custom_meta_to_gallery_categories() {
        
        //styles and scripts
        add_action( 'admin_enqueue_scripts', array( $this, '_add_styles_and_scripts'), 11 );
        

        //add field to new page
        add_action( $this->bulk_gallery_taxonomy_name.'_add_form_fields', array( $this, '_owlab_add_meta_field_to_taxonimy'), 10, 2 );
        
        // add field to edit page
        add_action( $this->bulk_gallery_taxonomy_name.'_edit_form_fields', array( $this, '_owlab_edit_meta_field_of_taxonomy'), 10, 2 );

        //save
        add_action( 'edited_'.$this->bulk_gallery_taxonomy_name, array( $this, '_save_owlab_custom_meta_of_taxonomy'), 10, 2 );  
        add_action( 'create_'.$this->bulk_gallery_taxonomy_name, array( $this, '_save_owlab_custom_meta_of_taxonomy'), 10, 2 );
    
    }

    /**
     * adds custom styles and scripts
     *
     * @since 1.1.0
     * @param      
     * @return 
     */
    public function _add_styles_and_scripts() {
       
        global $post_type;

        
        if( is_admin() && $this->post_type_name == $post_type ){

            wp_enqueue_media();

            wp_enqueue_script( 'owlabbulkg-category-upload-admin-js', plugins_url( 'assets/js/category-meta.js', $this->base->file ), array( 'jquery'), $this->base->version );
            wp_enqueue_style( 'owlabbulkg-category-upload-admin-css', plugins_url( 'assets/css/category-meta.css', $this->base->file ), array(), $this->base->version );

        } 
    
    }


    /**
     * add new fields for group taxonomy
     */
    public function _owlab_add_meta_field_to_taxonimy() {
        
        
        $out = '<div class="form-field">';
        // this will add the custom meta field to the add new term page
        wp_nonce_field( plugin_basename( __FILE__ ), 'owlabgal_media_nonce' );
                
        
        $out .= '<div class="drop_meta_item_group">
            <label for="owlabpfl_layout_type">'.__('Layout',"owlabbulkg").'</label>
            <select name="term_meta[owlabbulkg_layout_type]" id="owlabpfl_layout_type">';
                        
            $out .= $this->_get_layout_types_html();        
        
        $out .='</select>
            <br /><span class="description">'.__('Layout for this category page',"owlabbulkg").'</span></div>';

        

        $out .='</div><!-- end form-field -->';       
        echo $out;
        
    
    }

    /**
     * edit fields for taxonomy
     *
     * @since 1.0.0
     * @param      
     * @return 
     */
    public function _owlab_edit_meta_field_of_taxonomy($term) {

        // put the term ID into a variable
        $t_id = $term->term_id;

        // retrieve the existing value(s) for this meta field. This returns an array
        $term_meta = get_option( "owlab_bulkgal_cat_$t_id" );
        
        ?>

        <tr class="form-field">
            <th scope="row" valign="top">
                <label for="owlabbulkg_layout_type"><?php  _e('Layout','owlabbulkg')?> </label>
            </th>
            <td>
                <select name="term_meta[owlabbulkg_layout_type]" id="owlabbulkg_layout_type">
                    <?php $selected = esc_attr( $term_meta['owlabbulkg_layout_type'] ) ? esc_attr( $term_meta['owlabbulkg_layout_type'] ) : null; ?>
                    <?php echo $this->_get_layout_types_html($selected); ?>
                </select>
                <br/>
                <span class="description">'<?php _e('Layout for this category page',"owlabbulkg");?></span>
            </td>
        </tr>
        <?php 
    }


    /**
     * save fields for taxonomy 
     *
     * @since 1.0.0
     * @param      
     * @return 
     */
    public function _save_owlab_custom_meta_of_taxonomy($term_id) {
        
        //owlabgal_layout_type
        

        if ( isset( $_POST['term_meta'] ) ) {

            
            $t_id = $term_id;
            $term_meta = get_option( "owlab_bulkgal_cat_$t_id" );
            $cat_keys = array_keys( $_POST['term_meta'] );
            foreach ( $cat_keys as $key ) {
                if ( isset ( $_POST['term_meta'][$key] ) ) {
                    $term_meta[$key] = $_POST['term_meta'][$key];
                }
            }
            // Save the option array.
            update_option( "owlab_bulkgal_cat_$t_id", $term_meta );
        }
    
    }

    /**
     * layout types
     *
     * @since 1.0.0
     * @param      
     * @return 
     */
    public function _get_layout_types() {
    
        return array(
            'grid'       => __('Grid','owlabbulkg'),
            'vertical' => __('Vertical images - Horizaontal scrolling','owlabbulkg')
        );
    
    }


    /**
     * Print layout types
     *
     * @since 1.0.0
     * @param      
     * @return 
     */
    public function _get_layout_types_html($selected=null) {
    
        $types = $this->_get_layout_types();

        $out = '';
        $i = 0;
        foreach ( $types as $id=>$value){
            $out .= '<option value="'.$id.'" ';
            if ( isset($selected) ){
                if( $selected == $id )
                    $out .= 'selected';
            }else{
                if ($i == 0)
                   $out .= 'selected'; 
            }
            $out .='>'.$value.'</option>';
            $i++;
        }

        return $out;
    
    }

    /**
     * Returns the singleton instance of the class.
     *
     * @since 1.0.0
     *
     * @return object The owlabbulkg_Posttype object.
     */
    public static function get_instance() {

        if ( ! isset( self::$instance ) && ! ( self::$instance instanceof Owlabbulkg_Posttype ) ) {
            self::$instance = new Owlabbulkg_Posttype();
        }

        return self::$instance;

    }

}

// Load the posttype class.
$owlabbulkg_Posttype = Owlabbulkg_Posttype::get_instance();