<?php 
$default_user_img_url = get_stylesheet_directory_uri() . '/assets/pictures/default-img-user.png';

// Récupération du terme courant (le métier sur lequel on est)
$current_term = get_queried_object();

// 🔹 2. Tous les termes enfants
$children = get_terms([
    'taxonomy'   => 'metier',
    'child_of'   => $current_term->term_id,
    'hide_empty' => false,
]);

// IDs du parent + des enfants
$metier_ids = [$current_term->term_id];
if (!empty($children)) {
    $metier_ids = array_merge($metier_ids, wp_list_pluck($children, 'term_id'));
}

// 🔹 3. Recherche d’utilisateurs
$args = [
    'meta_query' => [
        'relation' => 'OR',
        [
            'key'     => 'poste_principal',
            'value'   => $metier_ids,
            'compare' => 'IN'
        ],
        [
            'key'     => 'user_postes',
            'value'   => serialize($metier_ids),
            'compare' => 'LIKE'
        ]
    ],
    'fields' => 'all_with_meta',
];

$users = get_users($args);
$count = count($users);

$data = [];
$i = 0;
foreach ($users as $user) {
    $data[] = [
        'id' => $user->ID,
        'name' => $user->display_name,
        'first_name' => get_user_meta($user->ID, 'first_name', true),
        'last_name' => get_user_meta($user->ID, 'last_name', true),
        'photo' => get_user_meta($user->ID, 'profile_photo', true),
        'region' => get_user_meta($user->ID, 'region', true),
        'permis' => get_user_meta($user->ID, 'user_permis', true),
    ];
    
    if (!empty($data[$i]['region'])) {
        $data[$i]['region_label'] = '';
        $term = get_term($data[$i]['region'], 'region');
        $data[$i]['region_label'] = $term->name;
    };

    ++$i;
}

// Récupération de tous les métiers
$metiers = get_terms(array(
    'taxonomy' => 'metier',
    'parent'   => 0,
    'hide_empty' => false
));

$submetiers = get_terms(array(
    'taxonomy' => 'metier',
    'hide_empty' => false,
    'child_of'      => $current_term->term_id
));

// Récuperer la liste des permis
$terms_permis = get_terms(array(
    'taxonomy' => 'permis',
    'parent' => '',
    'hide_empty' => false
));

// Récuperer la liste des regions
$terms_regions = get_terms(array(
    'taxonomy' => 'region',
    'parent' => '',
    'hide_empty' => false
));

get_header(); 
?>

<div class="department p-r-l-40 max-height">
    <form class="select-dep" id="metier-select-form" method="get">
        <div class="select">
            <select id="metier-select">
                <?php foreach ($metiers as $metier) : 
                    $selected = ($metier->term_id === $current_term->term_id) ? 'selected' : '';
                    $url = esc_url(get_term_link($metier));
                ?>
                    <option data-slug="<?php echo esc_attr($metier->slug)  ?>" value="<?php echo $url; ?>" <?php echo $selected; ?>>
                        <?php echo esc_html($metier->name); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <button class="button" type="submit">Rechercher</button>
    </form>
    <div class="list-container">
        <div class="filters">
            <div class="title-result">
                <h3>Filtres</h3>
                <span><?php echo $count ?> résultat<?php echo $count > 1 ? 's' : ''; ?></span>
            </div>
            <?php foreach($terms_permis as $permis_parent) : ?>
                <?php if ($permis_parent->parent == 0) :?>
                <div class="filter-container">
                    <h3>Permis  <?php echo esc_html($permis_parent->name); ?></h3>
                    <div class="input-container">
                        <div>
                            <?php foreach ($terms_permis as $permis) :?>
                                <?php if($permis->parent == $permis_parent->term_id) :?>
                            <div>
                                <input type="checkbox" id="<?php echo $permis->term_id?>" name="<?php echo $permis->name?>" />
                                <label for="<?php echo $permis->term_id?>"><?php echo esc_html($permis->name) ?></label>
                            </div>
                            <?php endif; endforeach; ?>
                                
                        </div>
                    </div>
                </div>
            <?php endif; endforeach; ?>
            <div class="filter-container">
                <h3>Postes</h3>
                <div class="input-container">
                    <?php foreach ($submetiers as $metier) : ?>
                        <div>
                            <input  type="checkbox" id="<?php echo esc_html($metier->slug); ?>" name="<?php echo esc_html($metier->name); ?>" />
                            <label for="<?php echo esc_html($metier->slug); ?>">  <?php echo esc_html($metier->name); ?></label>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <div class="filter-container">
                <h3>Région</h3>
                <div class="input-container">
                    <?php foreach ($terms_regions as $region) : ?>  
                        <div>
                            <input type="checkbox" id="<?php echo esc_html($region->term_id); ?>" name="<?php echo esc_html($region->name); ?>" />
                            <label for="<?php echo esc_html($region->term_id); ?>"><?php echo esc_html($region->name); ?></label>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        <div class="list-result">
            <div class="current-filters" id="current-filters">

            </div>
            <div class="list-scroll" id="user-list">
                <?php foreach ($data as $user) :?>
                <div class="tech-card">
                    <a href='<?php echo site_url('profil') . '?id=' . esc_html($user['id']); ?>'>
                        <div class="background-picture" style="background-image: url('<?php echo !empty($user['photo']) ? esc_url($user['photo']) :  esc_url($default_user_img_url); ?>');">
                            <!-- <div>
                                <h4>Jean-Pierre Garbin</h4>
                                <span>Guadeloupe</span>
                            </div> -->
                        </div>
                        <div class="etiquette">
                            <h4><?php echo esc_html($user['first_name']) . ' ' . esc_html($user['last_name']); ?></h4>
                            <span><?php echo esc_html($user['region_label']); ?></span>
                        </div>
                    </a>
                </div>
                <?php endforeach; ?>
            </div>
            <div id="loader" style="display:none;">Chargement...</div>
        </div>
    </div>
</div>

<script>
    const siteUrl = "<?php echo esc_url( site_url() ); ?>";
</script>

<script>

document.addEventListener("DOMContentLoaded", () => {
    const form = document.getElementById("metier-select-form");
    const select = document.getElementById("metier-select");
    const filtersContainer = document.getElementById("current-filters");
    let filters = new Set(); // 👈 évite les doublons automatiquement

    // ---------------------
    // 1️⃣ Changement de département
    // ---------------------
    select.addEventListener("change", () => {
        const selectedOption = select.options[select.selectedIndex];
        select.dataset.slug = selectedOption.getAttribute("data-slug");
    });

    form.addEventListener("submit", (e) => {
        e.preventDefault();
        const slug = select.dataset.slug;
        if (!slug) return;
        window.location.href = `${siteUrl}/index.php/metier/${slug}`;
    });

    // ---------------------
    // 2️⃣ Ajout / Suppression de filtres
    // ---------------------
    const updateFiltersDisplay = () => {
        filtersContainer.innerHTML = ""; // reset affichage

        filters.forEach((filterName) => {
            const filterDiv = document.createElement("div");
            filterDiv.classList.add("bubule-filter");
            filterDiv.innerHTML = `
                <span>${filterName}</span>
                <span class="cross" data-filter="${filterName}">X</span>
            `;
            filtersContainer.appendChild(filterDiv);
        });
    };

    const toggleFilter = (id, name) => {
        if (filters.has(name)) {
            filters.delete(name);
        } else {
            filters.add(name);
        }
        updateFiltersDisplay();
    };

    // ---------------------
    // 3️⃣ Gestion des inputs
    // ---------------------
    document.querySelectorAll('.input-container input[type="checkbox"]').forEach(input => {
        input.addEventListener("change", () => toggleFilter(input.id, input.name));
    });

    // ---------------------
    // 4️⃣ Délégation d'événement pour bulles dynamiques
    // ---------------------
    filtersContainer.addEventListener("click", (e) => {
        if (e.target.classList.contains("cross")) {
            const name = e.target.dataset.filter;
            filters.delete(name);
            // Décoche aussi la checkbox correspondante
            const checkbox = document.querySelector(`input[name="${name}"]`);
            if (checkbox) checkbox.checked = false;
            updateFiltersDisplay();
        }
    });
});
</script>

<script>
let paged = 1;
let loading = false;
let filters = {};

async function loadUsers(reset = false) {
    if (loading) return;
    loading = true;
    document.getElementById('loader').style.display = 'block';

    const formData = new FormData();
    formData.append('action', 'load_users');
    formData.append('paged', paged);
    formData.append('filters', JSON.stringify(filters));

    const response = await fetch("<?php echo admin_url('admin-ajax.php'); ?>", {
        method: 'POST',
        body: formData
    });

    const data = await response.json();
    const container = document.getElementById('user-list');

    if (reset) container.innerHTML = '';

    container.insertAdjacentHTML('beforeend', data.html);
    document.getElementById('loader').style.display = 'none';

    loading = false;
    if (data.has_more) paged++;
}

window.addEventListener('scroll', () => {
    if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight - 100 && !loading) {
        loadUsers();
    }
});

// Premier chargement
loadUsers();

// Exemple : changement d’un filtre
document.querySelectorAll('.filter').forEach(el => {
    el.addEventListener('change', e => {
        const key = e.target.name;
        const val = e.target.value;
        filters[key] = val;
        paged = 1;
        loadUsers(true);
    });
});
</script>

<?php get_footer(); ?>
