<?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();


$children = get_terms([
    'taxonomy'   => 'metier',
    'child_of'   => $current_term->term_id,
    'hide_empty' => false,
]);

$metier_ids = [$current_term->term_id];
if (!empty($children)) {
    $metier_ids = array_merge($metier_ids, wp_list_pluck($children, 'term_id'));
}


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

$terms_postes = 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 id="total-result"></span>
            </div>
            <div class="filters-container">
                <div class="filter-container">
                        <div onclick="toggleFilterContainer(this)" class="filter-title">
                            <h3>Postes</h3>
                            <button  data-status="postes-container" class="chevron-toggle"></button>
                        </div>
                    <div class="input-container" id="postes-container">
                        <?php foreach ($terms_postes as $metier) : ?>
                            <div>
                                <input data-field="postes"  type="checkbox" id="<?php echo $metier->term_id; ?>" name="<?php echo $metier->name; ?>" />
                                <label for="<?php echo $metier->term_id; ?>">  <?php echo esc_html($metier->name); ?></label>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <div class="filter-container">
                    <div onclick="toggleFilterContainer(this)" class="filter-title">
                        <h3>Région</h3>
                        <button data-status="region-container" class="chevron-toggle"></button>
                    </div>
                    <div class="input-container" id="region-container">
                        <?php foreach ($terms_regions as $region) : ?>  
                            <div>
                                <input data-field="region" 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>
                <?php foreach($terms_permis as $permis_parent) : ?>
                    <?php if ($permis_parent->parent == 0) :?>
                    <div class="filter-container">
                        <div class="filter-title" onclick="toggleFilterContainer(this)">
                            <h3>Permis  <?php echo esc_html($permis_parent->name); ?></h3>
                            <button onclick="toggleFilterContainer(this)" data-status="<?php echo esc_html($permis_parent->name); ?>-permis-container" class="chevron-toggle unvisible"></button>
                        </div>
                        <div class="input-container unvisible" id="<?php echo esc_html($permis_parent->name); ?>-permis-container">
                            <div>
                                <?php foreach ($terms_permis as $permis) :?>
                                    <?php if($permis->parent == $permis_parent->term_id) :?>
                                <div>
                                    <input data-field="permis" 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>
        </div>
        <div class="list-result">
            <div class="current-filters" id="current-filters">

            </div>
            <div class="list-scroll" id="user-list">
            </div>
            <div id="loader" style="display:none;">
                <div class="typing_loader"></div>
            </div>
        </div>
    </div>
</div>

<script>
    const siteUrl = "<?php echo esc_url( site_url() ); ?>";
    const metierIds = <?php echo json_encode($metier_ids); ?>;
    const listContainerScroll = document.getElementById('user-list');
    let paged = 1;
    let loading = false;
    let filters = { metiers: metierIds };
    let has_more = false;
    let count = 0;


    function toggleFilterContainer(parent) {
        let element = parent.children[1];
        element.classList.toggle('unvisible');
        elemToHide = element.dataset.status;
        elemToHide = document.getElementById(elemToHide);
        elemToHide.classList.toggle('unvisible');
    }

    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));

        console.log(`loadUsers filters --> ${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');
        const totalContainer = document.getElementById('total-result')

        if (reset) container.innerHTML = '';
        let resultText = 'résultats'
        if (data.total <= 1) {
            resultText =  'résultat'
        }
        totalContainer.innerHTML = data.total + ' ' + resultText;
        container.insertAdjacentHTML('beforeend', data.html);
        document.getElementById('loader').style.display = 'none';

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

    listContainerScroll.addEventListener('scroll', () => {
        let lastScrollTop = 0;
        if (listContainerScroll.scrollTop < lastScrollTop){
            // upscroll 
            return;
        } 
        lastScrollTop = listContainerScroll.scrollTop <= 0 ? 0 : listContainerScroll.scrollTop;
        if (listContainerScroll.scrollTop + listContainerScroll.offsetHeight>= listContainerScroll.scrollHeight ){
            if (has_more) {
                loadUsers();
            }
        }
    });


    const form = document.getElementById("metier-select-form");
    const select = document.getElementById("metier-select");
    const filtersContainer = document.getElementById("current-filters");

    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}/metier/${slug}`;
    });

    const updateFiltersDisplay = (key, value, label, toDelete = false) => {
        let id = key + '_' + value;
        if (toDelete) {
            let tag = document.getElementById(id);
            tag.remove();
        } else {
            const filterDiv = document.createElement("div");
            filterDiv.classList.add("bubule-filter");
            filterDiv.setAttribute('id', id);
            filterDiv.innerHTML = `
                <span>${label}</span>
                <span class="cross" data-key="${key}" data-value="${value}" data-filter="${label}" >×</span>
            `;
            filtersContainer.appendChild(filterDiv);
        }
    }


    const toggleFilter = (value, label, key) => {
        let toDelete = false;

        if (key in filters) {
            if (filters[key].includes(value)) {
                const index = filters[key].indexOf(value);
                if (index > -1) {
                    filters[key].splice(index, 1);
                }
                if (filters[key].length == 0) {
                    delete filters[key];
                }
                toDelete = true;
            } else {
                filters[key].push(value);
            }
        } else {
            filters[key] = [value];
        }
        updateFiltersDisplay(key, value, label, toDelete);
        paged = 1;
        loadUsers(true);
    };

    document.querySelectorAll('.input-container input[type="checkbox"]').forEach(input => {
        input.addEventListener("change", () => toggleFilter(input.id, input.name, input.dataset.field));
    });


    filtersContainer.addEventListener("click", (e) => {
        if (e.target.classList.contains("cross")) {
            toggleFilter(e.target.dataset.value, e.target.dataset.filter, e.target.dataset.key, )
            const name = e.target.dataset.filter;
            const checkbox = document.querySelector(`input[name="${name}"]`);
            if (checkbox) checkbox.checked = false;
        }
    });

    function saveFiltersToLocalStorage (filters) {
        console.log('saveFiltersToLocalStorage')
        console.log(filters);
        localStorage.setItem('filters_focus_antilles', JSON.stringify(filters));
    }

    function restoreFiltersFromLocalStorage () {
        const saved = localStorage.getItem('filters_focus_antilles');
        if (saved) {
            const saved_filters = JSON.parse(saved);
            filters = saved_filters;
            console.log(filters);
            terms = {}
            terms['postes'] = <?php echo wp_json_encode($terms_postes); ?>;
            terms['region'] = <?php echo wp_json_encode($terms_regions); ?>;
            terms['permis'] = <?php echo wp_json_encode($terms_permis); ?>;
            console.log(terms)
            for (const [key, value] of Object.entries(saved_filters)) {
                if (key !== 'metiers') {
                    let current_terms = terms[key];
                    console.log(key)
                    console.log(current_terms)
                    for (const filter of saved_filters[key]) {
                        const match = current_terms.find(el => el.term_id == filter);
                        const label = match ? match.name : '';
                        updateFiltersDisplay(key, filter, label);
                    }
                }
            }

            loadUsers();
        }
    }

    document.addEventListener('DOMContentLoaded', () => {
        const navEntries = performance.getEntriesByType('navigation');
        const navType = navEntries[0]?.type;
        if (navType === 'back_forward') {
            restoreFiltersFromLocalStorage();
        } else {
            localStorage.removeItem('filters_focus_antilles');
            loadUsers();
        }
    });
</script>

<?php get_footer(); ?>
