<?php

use DWL\Wtm\Classes\Helper;

if (!defined('ABSPATH')) exit; // Exit if accessed directly

// Ensure settings and data arrays are valid
$settings = is_array($settings) ? $settings : [];
$data = (is_array($data) && isset($data['posts']) && is_array($data['posts'])) ? $data : null;

if (!$data) {
    return; // Stop execution if no posts exist
}

// Retrieve settings with default values
$image_size = $settings['dwl_team_select_image_size'][0] ?? 'thumbnail';
$show_other_info = !empty($settings['dwl_team_team_show_other_info'][0]);
$show_social = !empty($settings['dwl_team_team_show_social'][0]);
$show_read_more = empty($settings['dwl_team_team_show_read_more'][0]); 
$enable_links = (isset($settings['dwl_team_team_link_mobile_phone'][0]) && 'on' == $settings['dwl_team_team_link_mobile_phone'][0]) ? 'yes' : 'no'; 
$show_progress_bar = !empty($settings['dwl_team_show_progress_bar'][0]);
$hide_short_bio_control = !empty($settings['dwl_team_hide_short_bio'][0]);
$hide_team_show_position = !empty($settings['dwl_team_team_show_position'][0]);


// Validate and retrieve single fields with proper defaults
$tm_single_fields = get_option('tm_single_fields', ['tm_jtitle']);
$tm_single_fields = is_array($tm_single_fields) ? $tm_single_fields : ['tm_jtitle'];

// Pro feature: Disable single team member view (global setting)
$disable_single_template = Helper::is_pro_option_enabled( 'single_team_member_view' );

// Sanitize and validate column numbers
$desktop_column = isset($settings['dwl_team_desktop_columns'][0]) ? absint($settings['dwl_team_desktop_columns'][0]) : 3;
$tablet_column = isset($settings['dwl_team_tablet_columns'][0]) ? absint($settings['dwl_team_tablet_columns'][0]) : 2;
$mobile_column = isset($settings['dwl_team_mobile_columns'][0]) ? absint($settings['dwl_team_mobile_columns'][0]) : 1;
$bootstrap_class = Helper::get_grid_layout_bootstrap_class($desktop_column, $tablet_column, $mobile_column);
$selected = Helper::generate_single_fields('frontend');


// Get accessibility settings
$a11y_enabled = get_option('tm_a11y_enable', 1);
$list_roles = get_option('tm_a11y_list_roles', 1);
$screen_reader = get_option('tm_screen_reader', 1);
$keyboard_nav = get_option('tm_keyboard_nav', 1);

foreach ($data['posts'] as $teamInfo) {

    // Retrieve all post meta for the current team member in one call (if necessary)
    $post_meta = get_post_meta($teamInfo->ID);

    // Ensure post meta exists and sanitize
    $job_title = isset($post_meta['tm_jtitle'][0]) ? sanitize_text_field($post_meta['tm_jtitle'][0]) : '';
    $short_bio = $post_meta['tm_short_bio'][0] ?? '';
    $taxonomy_classes = Helper::get_team_taxonomy_classes($teamInfo->ID);

    // Prepare accessibility attributes
    $aria_attrs = '';
    $role_attr = '';
    $tabindex_attr = '';

    if ($a11y_enabled == 1) {
        if ($list_roles == 1) {
            $role_attr = ' role="listitem"';
        }
        if ($screen_reader == 1) {
            $aria_attrs = ' aria-label="' . esc_attr(sprintf(__('Team member: %s', 'wp-team-manager'), get_the_title($teamInfo->ID))) . '"';
        }
        if ($keyboard_nav == 1) {
            $tabindex_attr = ' tabindex="0"';
        }
    }

    $allowed_tags = array_merge(
        wp_kses_allowed_html( 'post' ), // All default post tags
        array(
            'progress' => array(
                'value' => true,
                'max'   => true,
                'style' => true,
            ),
        )
    );
    ?>

    <div <?php post_class("team-member-info-wrap m-0 p-2 " . esc_attr($bootstrap_class) . " " . esc_attr($taxonomy_classes)); ?> data-post-id="<?php echo esc_attr($teamInfo->ID); ?>"<?php echo wp_kses_post($role_attr . $aria_attrs . $tabindex_attr); ?>>
        <div class="team-member-info-content">
            <header>
                <?php if (!$disable_single_template): ?>
                    <a href="<?php echo esc_url(get_the_permalink($teamInfo->ID)); ?>">
                <?php endif; ?>

                <?php echo wp_kses_post(Helper::get_team_picture($teamInfo->ID, $image_size, 'dwl-box-shadow')); ?>

                <?php if (!$disable_single_template): ?>
                    </a>
                <?php endif; ?>
            </header>

            <div class="team-member-desc">
                    <?php if (!$disable_single_template): ?>
                        <a href="<?php echo esc_url(get_the_permalink($teamInfo->ID)); ?>">
                    <?php endif; ?>
                        <h2 class="team-member-title"><?php echo esc_html(get_the_title($teamInfo->ID)); ?></h2>
                    <?php if (!$disable_single_template): ?>
                        </a>
                    <?php endif; ?>
                
                <?php if (!empty($job_title)  && !$hide_team_show_position): ?>
                    <h4 class="team-position">
                        <?php echo esc_html($job_title); ?>
                    </h4>
                <?php endif; ?>
                <?php if (!$hide_short_bio_control): ?>
                    <div class="team-short-bio">
                        <?php if( !empty( $short_bio ) ): ?>
                            <?php echo apply_filters('wtm_team_short_bio_output', wp_strip_all_tags($short_bio), $short_bio, $teamInfo->ID); ?>
                        <?php else: ?>
                            <?php 
                                $post_content = !empty($teamInfo->post_excerpt) 
                                    ? $teamInfo->post_excerpt 
                                    : wp_trim_words(strip_tags($teamInfo->post_content), 40, '...');

                                echo esc_html($post_content);
                                ?>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>

                  <?php  if (!$show_other_info): 
                  echo wp_kses_post(Helper::get_team_other_infos($teamInfo->ID, $selected, $enable_links));
                 endif;  ?>

                <?php if (tmwstm_fs()->is_paying_or_trial()): ?>
                        <?php if (!$show_progress_bar): ?>
                            <div class="wtm-progress-bar">
                            <?php
                                if (class_exists('DWL_Wtm_Pro_Helper')) {

                                    echo wp_kses(DWL_Wtm_Pro_Helper::display_skills_output($teamInfo->ID), $allowed_tags);

                                } ?>
                            </div>
                        <?php endif; ?>
                    <?php endif; ?>

                <?php if (!$show_social): ?>
                    <?php echo wp_kses_post(Helper::display_social_profile_output($teamInfo->ID)); ?>
                <?php endif; ?>

                <?php if ($show_read_more && !$disable_single_template): ?>
                    <div class="wtm-read-more-wrap">
                        <a href="<?php echo esc_url(get_the_permalink($teamInfo->ID)); ?>" class="wtm-read-more">
                            <?php esc_html_e('Read More', 'wp-team-manager'); ?>
                        </a>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

<?php } ?>