<?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_position'       => 9,     // The position 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;
    $position   = get_post_meta($post->ID, '_position', true);
    $phone      = get_post_meta($post->ID, '_phone', true);
    $email      = get_post_meta($post->ID, '_email', true);
    $department = get_post_meta($post->ID, '_department', 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="position"><b>Position *</b></label><br/>
            <input type="text" id="position" name="position" style="width: 90%;" value="<?= esc_attr($position); ?>" required>
        </div>
        <div class="col-md-6 mb-3" style="width: 50%; margin-bottom:10px;float:left;">
            <label for="department"><b>Department</b></label><br/>
            <input type="text" id="department" name="department" style="width: 90%;" value="<?= esc_attr($department); ?>">
        </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('position', 'phone', 'email', 'department', '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 === 'position') {
                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>WhatsApp</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'),
        'position' => __('Position'),
        'department' => __('Department'),
        '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 'position':
            // Display the end date
            $position = get_post_meta($post_id, '_position', true);
            echo esc_html($position);
            break;

        case 'department':
                // Display the end date
                $department = get_post_meta($post_id, '_department', true);
                echo esc_html($department);
                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' => 4, // 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 events
    if ($teams_query->have_posts()) :?>
        <div class="row">
        <?php
        while ($teams_query->have_posts()) : $teams_query->the_post();
            $post_id = get_the_ID();

            $position       = get_post_meta(get_the_ID(), '_position', true);
            $phone          = get_post_meta(get_the_ID(), '_phone', true);
            $email          = get_post_meta(get_the_ID(), '_email', true);
            $department     = get_post_meta(get_the_ID(), '_department', 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-3 col-lg-4 col-md-4 col-sm-6 team">
                
                <div class="card shadow-sm mb-3 border-0" data-aos="fade-up">
                    <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="Afiego" class="img-fluid"/>';
							}
						?>
					</div><!-- thumbnail !-->
                    <div class="team-details">
                    <h4><?php the_title(); ?></h4>
                    <p><?php echo esc_html($position); ?></p>
                    <button type="button" class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#teamModal-<?= $post_id; ?>">Read More</button>
                    </div><!-- team details !-->
                </div><!-- card !-->
            </div><!-- col !-->

            <!-- Full Profile  Modal -->
            <div class="modal fade member-details" id="teamModal-<?= $post_id; ?>" tabindex="-1" aria-labelledby="teamModalLabel-<?= $post_id; ?>" aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <div class="row g-0 mb-3">
                    <div class="col-sm-4">
                        <?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="Afiego" class="img-fluid"/>';
							}
						?>
                    </div><!-- col image !-->
                    <div class="col-sm-8">
                        <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 fs-3" id="teamModalLabel-<?= $post_id; ?>"><?php the_title(); ?></h4>
                                <span><?php echo esc_html($position); ?></span>
                                <hr />
                                <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.';
        echo '</div>';
    endif;

    return ob_get_clean();
}

add_shortcode('team', 'team_shortcode');


/** =================================================================
 *  SHORTCODE - Partners - Home PAGE
 *===================================================================*/
function partner_shortcode($atts) {

    $atts = shortcode_atts(
        array(
            'category' => 'partners', // Default to empty string if not specified
            'number' => 14, // Default number of posts per page
            'order' => 'DESC', //Default Descending order
        ),
        $atts,
        'team'
    );

    // Custom query to retrieve Teams
    $partners_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'])) {
        $partners_args['tax_query'] = array(
            array(
                'taxonomy' => 'team_category',
                'field' => 'slug',
                'terms' => $atts['category'],
            ),
        );
    }

    $partners_query = new WP_Query($partners_args);

    ob_start();

    // Check if there are upcoming events
    if ($partners_query->have_posts()) :?>
        <div class="row">
        <div class="col-xl-12  align-self-center" data-aos="fade-up">
        
        <div class="partner">
        <?php
        while ($partners_query->have_posts()) : $partners_query->the_post();
            $post_id = get_the_ID();

            $position       = get_post_meta(get_the_ID(), '_position', true);
            $website        = get_post_meta(get_the_ID(), '_website', true);
            ?>
            <a href="<?= $website; ?>" alt="<?php the_title(); ?>" title="<?php the_title(); ?>" target="_blank">
            <div class="card  mb-3 border-0" >
				<?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="Afiego" class="img-fluid"/>';
					}
				?>
            </div><!-- card !-->
            </a>
                
            

            <?php
        endwhile;
        wp_reset_postdata();
        ?>
        </div>
    <?php else : ?>
        No Partners found
    </div><!-- col !--> 
    </div><!-- row!-->
    <?php endif; 

    return ob_get_clean(); 
} 

add_shortcode('partners', 'partner_shortcode');


/** =================================================================
 *  SHORTCODE - Partners LIST PAGE
 *===================================================================*/
function partnerlist_shortcode($atts) {

    $atts = shortcode_atts(
        array(
            'category' => 'partners', // Default to empty string if not specified
            'number' => 14, // Default number of posts per page
            'order' => 'DESC', //Default Descending order
        ),
        $atts,
        'team'
    );

    // Custom query to retrieve Teams
    $partners_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'])) {
        $partners_args['tax_query'] = array(
            array(
                'taxonomy' => 'team_category',
                'field' => 'slug',
                'terms' => $atts['category'],
            ),
        );
    }

    $partners_query = new WP_Query($partners_args);

    ob_start();

    // Check if there are upcoming events
    if ($partners_query->have_posts()) :?>
        <div class="row">

       
        <?php
        while ($partners_query->have_posts()) : $partners_query->the_post();
            $post_id = get_the_ID();

            $position       = get_post_meta(get_the_ID(), '_position', true);
            $website        = get_post_meta(get_the_ID(), '_website', true);
            ?>
            <div class="col-md-4 col-sm-6 col-6 mb-3 align-self-center partnerlist" data-aos="fade-up">
            <a href="<?= $website; ?>" alt="<?php the_title(); ?>" title="<?php the_title(); ?>" target="_blank">
				<?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="Afiego" class="img-fluid"/>';
					}
				?>
            </a>
            </div><!-- col !-->
            

            <?php
        endwhile;
        wp_reset_postdata();
        ?>
    <?php else : ?>
        No Partners found
    </div><!-- row!-->
    <?php endif; 

    return ob_get_clean(); 
} 

add_shortcode('partners-list', 'partnerlist_shortcode');
?>