<?php //Custom Post :: TEAMS

function custom_post_type_team(){
    $labels = array(
        'name'                => __('Team', 'kipya' ),
        'add_new_item'        => __( 'Add New Member', 'kipya' ),
        'add_new'             => __( 'Add New Member', 'kipya' ),
        'edit_item'           => __( 'Edit Member', 'kipya' ),
        'update_item'         => __( 'Update Member', 'kipya' ),
        'all_items'           => __( 'Team Members', 'kipya' ),
        'search_items'        => __( 'Search ', 'kipya' ),
        'singular_name'       => __('Team'),
    );
    $supports = array(
        'title',        // Post title
        'excerpt',      // Allows short description
        'editor',      // Allows full description
        'thumbnail',    // Allows feature images

    );
    $args = array(
        'labels'              => $labels,
        'description'         => 'For all Teams and their Members', 
        'supports'            => $supports,
        'hierarchical'        => false, 
        'public'              => true,  // Makes the post type public
        'show_ui'             => true,  // Displays an interface for this post type
        'show_in_menu'        => true,  // Displays in the Admin Menu (the left panel)
        'show_in_admin_bar'   => true,  // Displays in the black admin bar
        'menu_designation'       => 9,     // The designation number in the left menu
        'menu_icon'           => 'dashicons-groups',  
        'can_export'          => true,  // Allows content export using Tools -> Export
        'has_archive'         => true,  // Enables post type archive (by month, date, or year)
        'exclude_from_search' => false, 
        'capability_type'     => 'post', // Allows read, edit, delete like “Post”
    );
    register_post_type('team', $args);

    // Register meta boxes individually
    add_action('add_meta_boxes_team', 'add_custom_meta_boxes_teams');
    add_action('add_meta_boxes_team', 'add_custom_meta_boxes_team_socials');

    //Adding Category
    $taxonomy_labels = array(
        'name'              => _x('Team Categories', 'taxonomy general name'),
        'singular_name'     => _x('Team Category', 'taxonomy singular name'),
        'search_items'      => __('Search Team Categories'),
        'all_items'         => __('All Team Categories'),
        'edit_item'         => __('Edit Team Category'),
        'update_item'       => __('Update Team Category'),
        'add_new_item'      => __('Add New Team Category'),
        'new_item_name'     => __('New Team Category Name'),
        'menu_name'         => __('Team Categories'),
    );
    $taxonomy_args = array(
        'hierarchical'      => true, 
        'labels'            => $taxonomy_labels,
        'show_ui'           => true,
        'show_in_rest'      => true, 
        'query_var'         => true,
        'rewrite'           => array('slug' => 'team-category'),
    );
    register_taxonomy('team_category', 'team', $taxonomy_args);
}
add_action('init', 'custom_post_type_team');

//Add Custom Meta Boxes on Team
function add_custom_meta_boxes_teams() {
    add_meta_box('member_details', 'Member Details', 'render_custom_meta_box_teams', 'team', 'normal', 'high');
}

// Render custom meta boxes
function render_custom_meta_box_teams($post) {
    // Get existing values
	$post_id    = $post->ID;
    $designation   = get_post_meta($post->ID, '_designation', true);
    $phone      = get_post_meta($post->ID, '_phone', true);
    $email      = get_post_meta($post->ID, '_email', true);
    $organization = get_post_meta($post->ID, '_organization', true);
    $website    = get_post_meta($post->ID, '_website', true);

    // Output fields
    ?>
    <div class="row">
        <div class="col-md-6 mb-3" style="width: 50%; margin-bottom:10px;float:left;">
            <label for="designation"><b>Designation *</b></label><br/>
            <input type="text" id="designation" name="designation" style="width: 90%;" value="<?= esc_attr($designation); ?>" required>
        </div>
        <div class="col-md-6 mb-3" style="width: 50%; margin-bottom:10px;float:left;">
            <label for="organization"><b>Organization</b></label><br/>
            <input type="text" id="organization" name="organization" style="width: 90%;" value="<?= esc_attr($organization); ?>">
        </div>
        <div class="col-md-6 mb-3" style="width: 50%; margin-bottom:10px;float:left;">
            <label for="phone" class="form-label"><b>Telephone</b></label><br/>
            <input type="text" id="phone" name="phone" style="width: 90%;" value="<?= esc_attr($phone); ?>">
        </div>
        <div class="col-md-6 mb-3" style="width: 50%; margin-bottom:10px;float:left;">
            <label for="email" class="form-label"><b>Email Address</b></label><br/>
            <input type="text" id="email" name="email" style="width: 90%;" value="<?= esc_attr($email); ?>">
        </div>
        <div class="col-md-12 mb-3">
            <label for="link" class="form-label"><b>Link</b></label><br/>
            <input type="text" id="link" name="website" style="width: 100%" value="<?= esc_attr($website); ?>">
        </div>
    </div>
    <?php
}

// Save custom meta box data
function save_custom_meta_box_teams($post_id) {
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (!current_user_can('edit_post', $post_id)) return;

    // Save custom fields
    // Define an array of field names
    $fields = array('designation', 'phone', 'email', 'organization', 'website');
    foreach ($fields as $field) {
        // Check if the field key is set in $_POST
        if (isset($_POST[$field])) {
            // If set, update post meta
            if ($field === 'designation') {
                update_post_meta($post_id, '_' . $field, wp_kses_post($_POST[$field]));
            } else {
                update_post_meta($post_id, '_' . $field, sanitize_text_field($_POST[$field]));
            }
        } else {
            // If not set, handle accordingly (you can leave it empty or provide a default value)
            update_post_meta($post_id, '_' . $field, ''); // Setting it to an empty string in this case
        }
    }
}

add_action('add_meta_boxes', 'add_custom_meta_boxes_teams');
add_action('save_post', 'save_custom_meta_box_teams');


//Add Custom Meta Boxes on Team
function add_custom_meta_boxes_team_socials() {
    add_meta_box('social_details', 'Social Details', 'render_custom_meta_box_team_socials', 'team', 'normal', 'high');
}

// Render custom meta boxes
function render_custom_meta_box_team_socials($post) {
    // Get existing values
	$post_id        = $post->ID;
    $facebook       = get_post_meta($post->ID, '_facebook', true);
    $linkedin       = get_post_meta($post->ID, '_linkedin', true);
    $instagram      = get_post_meta($post->ID, '_instagram', true);
    $x              = get_post_meta($post->ID, '_x', true);
    $whatsapp       = get_post_meta($post->ID, '_whatsapp', true);

    // Output fields
    ?>
    <div class="row">
        <div class="col-md-6 mb-3" style="width: 50%; margin-bottom:10px;float:left;">
            <label for="facebook"><b>Facebook</b></label>
            <input type="text" id="facebook" name="facebook" style="width: 60%;" value="<?= esc_attr($facebook); ?>">
        </div>
        <div class="col-md-6 mb-3" style="width: 50%; margin-bottom:10px;float:left;">
            <label for="twitter"><b>X / Twitter</b></label>
            <input type="text" id="twitter" name="x" style="width: 60%;" value="<?= esc_attr($x); ?>">
        </div>
        <div class="col-md-6 mb-3" style="width: 50%; margin-bottom:10px;float:left;">
            <label for="insta" class="form-label"><b>Instagram</b></label>
            <input type="text" id="insta" name="instagram" style="width: 60%;" value="<?= esc_attr($instagram); ?>">
        </div>
        <div class="col-md-6 mb-3" style="width: 50%; margin-bottom:10px;float:left;">
            <label for="linkedin" class="form-label"><b>LinkedIn</b></label> 
            <input type="text" id="linkedin" name="linkedin" style="width: 60%;" value="<?= esc_attr($linkedin); ?>">
        </div>
        <div class="col-md-12 mb-3">
            <label for="whatsapp" class="form-label"><b>Link</b></label>
            <input type="text" id="whatsapp" name="whatsapp" style="width: 90%" value="<?= esc_attr($whatsapp); ?>">
        </div>
    </div>
    <?php
}

// Save custom meta box data - Social Media
function save_custom_meta_box_team_socials($post_id) {
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (!current_user_can('edit_post', $post_id)) return;

    // Save custom fields - Socials
    $fields = array('facebook', 'linkedin', 'instagram', 'x', 'whatsapp');
    foreach ($fields as $field) {
        // Check if the field key is set in $_POST
        if (isset($_POST[$field])) {
            // If set, update post meta
            if ($field === 'facebook') {
                update_post_meta($post_id, '_' . $field, wp_kses_post($_POST[$field]));
            } else {
                update_post_meta($post_id, '_' . $field, sanitize_text_field($_POST[$field]));
            }
        } else {
            // If not set, handle accordingly (you can leave it empty or provide a default value)
            update_post_meta($post_id, '_' . $field, ''); // Setting it to an empty string in this case
        }
    }
}

add_action('add_meta_boxes', 'add_custom_meta_boxes_team_socials');
add_action('save_post', 'save_custom_meta_box_team_socials');


/** =============================================================
 * ADMIN DASHBOARD
 *==============================================================*/
// Add custom columns to the team post type - DASHBOARD
function add_custom_columns_to_team($columns) {
    $new_columns = array(
        'cb' => $columns['cb'],
        'photo' => __('Photo'),
        'title' => __('Name'),
        'designation' => __('designation'),
        'organization' => __('Organization'),
        'team_category' => __('Team Category'),
    );    
    return $new_columns;
}
add_filter('manage_team_posts_columns', 'add_custom_columns_to_team');


// Populate custom columns with data
function populate_custom_team_columns($column, $post_id) {
    switch ($column) {
        case 'photo':
            // Display the featured image
            $photo_url = get_the_post_thumbnail_url($post_id, 'thumbnail'); // You can adjust the image size ('thumbnail', 'medium', 'large', 'full')
            if ($photo_url) {
                echo '<img src="' . esc_url($photo_url) . '" alt="Photo" style="max-height: 50px; width: auto;" />';
            } else {
                echo 'No photo available';
            }
            break;        

        case 'title':
            // Display the start date
            $title = get_post_meta($post_id, 'title', true);
            echo esc_html($title);
            break;

        case 'designation':
            // Display the end date
            $designation = get_post_meta($post_id, '_designation', true);
            echo esc_html($designation);
            break;

        case 'organization':
                // Display the end date
                $organization = get_post_meta($post_id, '_organization', true);
                echo esc_html($organization);
                break;

        case 'team_category':
            // Display the team category
            $terms = wp_get_post_terms($post_id, 'team_category'); 
            if (!empty($terms) && !is_wp_error($terms)) {
                $categories = array();
                foreach ($terms as $term) {
                    $categories[] = $term->name;
                }
                echo esc_html(implode(', ', $categories));
            } else {
                echo 'No category';
            }
            break;
    }
}
add_action('manage_team_posts_custom_column', 'populate_custom_team_columns', 10, 2);


/** =================================================================
 *  SHORTCODE - TEAM
 *===================================================================*/
function team_shortcode($atts) {
    // Define shortcode attributes, if needed
    $atts = shortcode_atts(
        array(
            'category' => '', // Default to empty string if not specified
            'number' => 15, // Default number of posts per page
            'order' => 'DESC', //Default Descending order
        ),
        $atts,
        'team'
    );

    // Custom query to retrieve Teams
    $teams_args = array(
        'post_type' => 'team',
        'posts_per_page' => $atts['number'], // Number of posts per page
        'orderby' => 'date', // Order by date
        'order' => $atts['order'], // order
    );

    // Check if category attribute is provided and not empty
    if (!empty($atts['category'])) {
        $teams_args['tax_query'] = array(
            array(
                'taxonomy' => 'team_category',
                'field' => 'slug',
                'terms' => $atts['category'],
            ),
        );
    }

    $teams_query = new WP_Query($teams_args);

    ob_start();

    // Check if there are upcoming existing members
    if ($teams_query->have_posts()) : ?>
        <div class="row"> 
        <?php
        while ($teams_query->have_posts()) : $teams_query->the_post();
            $post_id = get_the_ID();

            $designation       = get_post_meta(get_the_ID(), '_designation', true);
            $phone          = get_post_meta(get_the_ID(), '_phone', true);
            $email          = get_post_meta(get_the_ID(), '_email', true);
            $organization     = get_post_meta(get_the_ID(), '_organization', true);
            $website        = get_post_meta(get_the_ID(), '_website', true);
            $facebook       = get_post_meta(get_the_ID(), '_facebook', true);
            $linkedin       = get_post_meta(get_the_ID(), '_linkedin', true);
            $instagram      = get_post_meta(get_the_ID(), '_instagram', true);
            $x              = get_post_meta(get_the_ID(), '_x', true);
            $whatsapp       = get_post_meta(get_the_ID(), '_whatsapp', true);
            ?>

            <div class="col-xl-6 col-lg-6 col-md-6 col-sm-6 team">
                <div class="card border-0" data-aos="fade-up">
                    <div class="row justify-content-between">
                        <div class="col-xl-5 col-lg-5 col-md-5 col-sm-5 ">
                    <div class="post-thumbnail">
                        <?php // Display the post thumbnail
                            if (has_post_thumbnail()) {
                                the_post_thumbnail(); 
                            } else {
                                echo '<img src="'. get_template_directory_uri().'/assets/images/placeholder-image.jpg" alt="HPLNOU" class="img-fluid"/>';
                            }
                        ?>
                    </div><!-- thumbnail !-->
                    </div>
                    <div class="col-xl-7 col-lg-7 col-md-7 col-sm-7 align-self-center">
                    <div class="team-details">
                    <h4><?php the_title(); ?></h4>
                    <p class="orgn"><strong>Org: </strong>(<?php echo esc_html($organization); ?>)</p>
                    <p class="desig"><strong>Designation: </strong><?php echo esc_html($designation); ?></p>
                    <button type="button" class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#teamModal-<?= $post_id; ?>">Full Profile</button>
                    </div><!-- team details !-->
                    </div>
                    </div>
                </div><!-- card !-->
            </div><!-- col !-->
            
            <!-- Full Profile Modal -->
            <div class="modal fade member-details teamPop" id="teamModal-<?= $post_id; ?>" tabindex="-1" aria-labelledby="teamModalLabel-<?= $post_id; ?>" aria-hidden="true" style="">
            <div class="modal-dialog modal-lg">
                <div class="row g-0">
                    <div class="col-sm-6">
                        <?php // Display the post thumbnail
                            if (has_post_thumbnail()) {
                                the_post_thumbnail(); 
                            } else {
                                echo '<img src="'. get_template_directory_uri().'/assets/images/placeholder-image.jpg" alt="NHP" class="img-fluid"/>';
                            }
                        ?>
                    </div><!-- col image !-->
                    <div class="col-sm-6">
                        <div class="modal-content border-0 rounded-0 h-100">
                            <button type="button" class="btn-close btx" data-bs-dismiss="modal" aria-label="Close"></button>
                            <div class="modal-body">
                                <h4 class="modal-title" id="teamModalLabel-<?= $post_id; ?>"><?php the_title(); ?></h4>
                                <p class="title"><span><?php echo esc_html($designation); ?></span></p>
                                <p><?php the_content(); ?></p>
                            </div><!-- modal body !-->
                        </div>
                    </div><!-- col details !-->
                </div><!-- row !-->
            </div><!-- modal-dialog !-->
            </div><!-- modal !-->
            <?php
        endwhile;
        wp_reset_postdata();
    else :
        echo 'No Team Members found.';
        
    endif;?>
    </div>
 <?php   
    return ob_get_clean();
}

add_shortcode('team', 'team_shortcode');
?>