
<?php
/* Template Name: Page Edit Profil */

if (!is_user_logged_in()) {
    wp_safe_redirect(site_url('connexion'));
    exit;
}

// ATTENTION 
// J'avais ça a la recuperation des competences


// DEFAULT FIELDS
$default_doc_img_url = get_stylesheet_directory_uri() . '/assets/pictures/default-img-doc.png';

// CURRENT USER INFO
$current_user = wp_get_current_user();
$user_id = $current_user->ID;

// FIELDS INITIALIZED
$profile_picture = initField('profile_picture', []);
$display_name = $current_user->display_name;
$first_name = $current_user->first_name;
$last_name  = $current_user->last_name;
$phone = initField('phone', '');
$email = $current_user->user_email;
$region = initField('region', '');
$postes = initField('postes', []);
$show_phone = initField('show_phone', false);
$show_email = initField('show_email', false);
$poste_principal = initField('poste_principal', '');
$permis = initField('permis', []);
$experiences = initField('experiences', []);
$competences = initField('competences', []);
$description = initField('description', '');
$additionnal_file = initField('additionnal_file', []);

$competences_converted = implode(", ", $competences);


function initField($field_name, $type) {
    global $user_id;
    return get_user_meta($user_id, $field_name, true) ?: $type;
}

// INIT SPECIFIQUE 

if(!empty($additionnal_file) && !is_array(getimagesize($additionnal_file))){
    $additionnal_file= $default_doc_img_url;
};

// RECUPERER LES TERMES (region, postes)

if (!empty($region)) {
    $region = get_term($region, 'region');
    $region = $region->term_id;
}

$postes_terms = [];
foreach ($postes as $term_id) {
    $term = get_term($term_id, 'metier');
    if ($term && !is_wp_error($term)) {
        $postes_terms[] = [
            'id' => $term->term_id,
            'name' => $term->name,
        ];
    }
}

// RECUPERER TOUT LES METIERS
$metiers = get_terms(array(
    'taxonomy' => 'metier',
    'parent' => '',
    'hide_empty' => false
));


// RECUPERER TOUT LES PERMIS
$terms_permis = get_terms(array(
    'taxonomy' => 'permis',
    'parent' => '',
    'hide_empty' => false,
));

// RECUPERER TOUTES LES RÉGIONS
$terms_regions = get_terms(array(
    'taxonomy' => 'region',
    'parent' => '',
    'hide_empty' => false
));



// CHECK REQUIRED 
$firstNameErr = $lastNameErr = $emailErr = $displayNameErr = $regionErr= "";

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_profile'])) {
    // RECUPERATION ET NETTOYAGE DES VALEURS 

    $display_name = sanitize_text_field($_POST['display_name'] ?? '');
    $first_name = sanitize_text_field($_POST['first_name'] ?? '');
    $last_name = sanitize_text_field($_POST['last_name'] ?? '');
    $email = sanitize_text_field($_POST['email'] ?? '');
    $phone = sanitize_text_field($_POST['phone'] ?? '');
    $region = (int)$_POST['region'];
    $show_phone = isset($_POST['show_phone']) ? true : false;
    $show_email = isset($_POST['show_email']) ? true : false;
    $poste_principal = (int)$_POST['poste_principal'];
    $description = sanitize_textarea_field($_POST['description'] ?? '');
    $permis = isset($_POST['permis']) ? $_POST['permis'] : []; 

    // GESTION ERREUR

    $errors = [];

    if (empty($display_name)) $errors['display_name'] = "Le nom d’utilisateur est obligatoire.";
    if (empty($first_name)) $errors['first_name'] = "Le prénom est obligatoire.";
    if (empty($last_name)) $errors['last_name'] = "Le nom est obligatoire.";
    if (empty($email)) $errors['email'] = "le email est obligatoire.";
    if (empty($region)) $errors['region'] = "la région est obligatoire.";

    if (empty($errors)) {
        // PROFILE PICTURE UPDATE
        if (!empty($_FILES['profile_picture']['name'])) {
            require_once(ABSPATH . 'wp-admin/includes/file.php');
            $upload = wp_handle_upload($_FILES['profile_picture'], ['test_form' => false]);
            if (!isset($upload['error']) && isset($upload['url'])) {
                updateField('profile_picture', esc_url($upload['url']));
                $profile_picture = esc_url($upload['url']);
            }
        }

        // ADDITIONNAL FILE UPDATE
        if (!empty($_FILES['additionnal_file']['name'])) {
            require_once(ABSPATH . 'wp-admin/includes/file.php');
            $upload = wp_handle_upload($_FILES['additionnal_file'], ['test_form' => false]);
            if (!isset($upload['error']) && isset($upload['url'])) {
                updateField('additionnal_file', esc_url($upload['url']));
                $additionnal_file = esc_url($upload['url']);
            }
        }


        // // Mettre à jour les champs du profil
        wp_update_user([
            'ID'           => $user_id,
            'display_name' => $display_name,
            'user_email'   => $email,
            'first_name'   => $first_name,
            'last_name'    => $last_name,
        ]);

        // METTRE A JOUR LES CHAMPS
        updateField('phone', $phone);
        updateField('region', $region);
        updateField('show_phone', $show_phone);
        updateField('show_email', $show_email);
        updateField('poste_principal', $poste_principal);
        updateField('description', $description);
        updateField('permis', $permis);

        // SPECIFIQUE
        // POSTES
        $raw_postes = sanitize_text_field($_POST['postesInput'] ?? '');
        $postes_ids = array_filter(array_map('intval', explode(',', $raw_postes)));
        updateField('postes', $postes_ids);
        
        // EXPERIENCES 
        $experiences = [];


        // re faire ce truc
        if (!empty($_POST['experience_titre'])) {
            foreach ($_POST['experience_titre'] as $i => $titre) {
                $experiences[] = [
                    'titre' => sanitize_text_field($titre),
                    'year' => sanitize_text_field($_POST['experience_year'][$i]),
                    'real' => sanitize_text_field($_POST['experience_real'][$i]),
                    'prod' => sanitize_text_field($_POST['experience_prod'][$i]),
                    'poste' => sanitize_text_field($_POST['experience_poste'][$i]),
                    'poste_chef' => sanitize_text_field($_POST['experience_poste_chef'][$i]),
                    'poste_chef' => sanitize_text_field($_POST['experience_poste_chef'][$i]),
                ];
            }
        }
        updateField('experiences', $experiences);
        
        // COMPETENCES
        $competences = array_filter(array_map('sanitize_text_field', explode(',', $_POST['competences'] ?? '')));
        updateField('competences', $competences);

        wp_safe_redirect(site_url('profil'));
    }
}

function updateField($field_name, $value) {
    global $user_id;
    update_user_meta($user_id, $field_name, $value);
}

get_header();
?>

<div class="edit-profile-page p-r-l-40">
    <div class="container">
        <form onsubmit="return validateForm();" method="POST" enctype="multipart/form-data">
            <div class="section global-info">
                <h3>Informations principales</h3>
                <div class="child-section">
                    <div>
                        <div class="upload-file profile-picture-upload">
                            <img id="profile-preview" class="<?php if (empty($profile_picture)) { echo 'empty'; } ?>"  src="<?php if (empty($profile_picture)) { echo esc_url( get_stylesheet_directory_uri() . '/assets/icons/telecharger.png' ); } else { echo esc_url($profile_picture); } ?>" alt="Photo de profil" />
                            <input type="file" id="profile-picture" name="profile_picture" accept="image/*" hidden>
                        </div>
                        <div id="remove-profile-picture" class="remove-img"><img src="<?php echo get_stylesheet_directory_uri(); ?>/assets/icons/poubelle.png" alt=""></div>                    
                        <div id="upload-profile-picture-error" class="info">
                        </div>                           
                    </div>
                    <div class="input-section">
                        <div class="input">
                            <label for="display_name">
                                Nom d'utilisateur *
                            </label>
                            <input id="input-display-name" type="text" name="display_name" value="<?php echo $display_name; ?>">
                        </div>
                        <div class="input" >
                            <label for="first_name">Prénom *</label>
                            <input id="input-first-name" type="text" name="first_name" value="<?php echo $first_name;  ?>">
                        </div>
                        <div class="input">
                            <label for="last_name">Nom *</label>
                            <input id="input-last-name" type="text" name="last_name" value="<?php  echo $last_name; ?>">
                        </div>
                        <div class="input">
                            <label for="phone">Téléphone </label>
                            <input type="text" name="phone"  value="<?php echo $phone; ?>">
                        </div>
                        <div class="input" >
                            <label for="email">Email *</label>
                            <input id="input-email" type="email" name="email" value="<?php echo $email; ?>">
                        </div>
                        <div class="input">
                            <label for="region">Région *</label>
                            <select name="region" id="region">
                                <option value="">Choisir une région</option>
                                <?php foreach($terms_regions as $region_child) :?>
                                    <option value="<?php echo esc_attr($region_child->term_id); ?>" <?php selected($region, $region_child->term_id); ?>><?php echo esc_html($region_child->name); ?></option>
                                <?php endforeach; ?>
                            </select>
                            <div class="info">
                                <p class="info-text">
                                    Précisez la région dans laquelle vous résidez
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="section public-info">
                <h3>Informations publiques</h3>
                <div class="child-section margin-b-20">
                    <div class="input-section no-gap">
                        <div class="input">
                            <label for="postes">Postes</label>
                            <select id="postes" name="postes" class="options-list">
                                <option value="">Choisir un poste</option>
                                <?php foreach ($metiers as $category) : 
                                    if ($category->parent == 0) :
                                        echo '<optgroup label="'. esc_attr($category->name) .'">';
                                        foreach ($metiers as $subcategory) :
                                            if ($subcategory->parent == $category->term_id) :
                                                $is_selected = in_array($subcategory->term_id, $postes) ? 'selected' : '';
                                                echo '<option data-id="'. esc_attr($subcategory->term_id) .'" value="'. esc_attr($subcategory->term_id) .'" '. $is_selected .'>
                                                        '. esc_html($subcategory->name) .'
                                                    </option>';
                                            endif;
                                        endforeach;
                                        echo '</optgroup>';
                                    endif;
                                endforeach; ?>
                            </select>
                            <input type="hidden" id="postesInput" name="postesInput" value="<?php echo implode(',', $postes); ?>" />
                        </div>
                        <div class="custom-select">
                            <div id="selectedTags" class="tags-container"></div>
                        </div>
                    </div>
                </div>
                <div class="child-section margin-b-20">
                    <div class="input-section">
                        <div class="input">
                            <label for="poste_principal">Poste principal</label>
                            <?php 
                                if ( !empty($metiers) ) :
                                    $output = '<select id="poste_principal" name="poste_principal">';
                                    $output.= '<option value=""> Choisir un poste principal</option>';
                                    foreach( $metiers as $category ) {
                                        if( $category->parent == 0 ) {
                                            $output.= '<optgroup label="'. esc_attr( $category->name ) .'">';
                                            foreach( $metiers as $subcategory ) {
                                                if($subcategory->parent == $category->term_id) {
                                                $output.= '<option value="'. esc_attr( $subcategory->term_id ) .'"
                                                    '. selected($poste_principal, $subcategory->term_id, false) . ' >
                                                    '. esc_html( $subcategory->name ) .'</option>';
                                                }
                                            }
                                            $output.='</optgroup>';
                                        }
                                    }
                                    $output.='</select>';
                                    echo $output;
                                endif;
                            ?>
                            <div class="info">
                                <p class="info-text">
                                    Poste que vous occupez actuellement
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="child-section margin-b-20">
                    <div class="toggle-section">
                        <div>
                            <label class="switch">
                                <input name="show_phone" type="checkbox" <?php checked($show_phone, true); ?>>
                                <span class="slider round"></span>
                            </label>
                            <span class="label">
                                Afficher mon numéro de téléphone
                            </span>
                        </div>
                        <div>
                            <label class="switch">
                                <input name="show_email" type="checkbox" <?php checked($show_email, true); ?>>
                                <span class="slider round"></span>
                            </label>
                            <span class="label">
                                Afficher mon email
                            </span>
                        </div>
                        <div class="info">
                            <span class="info-icon">
                                <img src="<?php echo esc_url( get_stylesheet_directory_uri() . '/assets/icons/attention.png' ); ?>" alt="">
                            </span>
                            <p class="info-text">
                                Si vous ne cocher aucune des deux options, vous serrez injoignable via le site
                            </p>
                        </div>
                    </div>
                </div>
                <div class="child-section">
                    <div class="checkbox">
                        <span>Permis Classique</span>
                        <div>
                            <?php foreach ($terms_permis as $term_permis) :?>
                                <?php if($term_permis->parent == 67) :?>
                            <div class="checkbox-container">
                                <input type='checkbox' name='permis[]' value='<?php echo $term_permis->term_id?>' <?php checked(in_array($term_permis->term_id, $permis)); ?>>
                                <label><?php echo esc_html($term_permis->name) ?></label>
                            </div>
                            <?php endif; endforeach; ?>
                        </div>
                    </div>
                    <div class="checkbox">
                        <span>Permis CACES</span>
                        <div>
                            <?php foreach ($terms_permis as $term_permis) :?>
                                <?php if($term_permis->parent == 66) :?>
                            <div class="checkbox-container">
                                <input type='checkbox' name='permis[]' value='<?php echo $term_permis->term_id?>' <?php checked(in_array($term_permis->term_id, $permis)); ?>>
                                <label><?php echo esc_html($term_permis->name) ?></label>
                            </div>
                            <?php endif; endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>
            <div class="section section-experience">
                <h3>Experiences</h3>
                <div id="experience-container">
                    <?php if (!empty($experiences)) : ?>
                        <?php foreach ($experiences as $index => $exp) : ?>
                            <div class="experience">
                                <div class="experience-input">
                                    <div class="input">
                                        <label for="experience_titre[]">Nom</label>
                                        <input type="text" name="experience_titre[]" value="<?php echo esc_attr($exp['titre']); ?>">
                                    </div>
                                    <div class="input">
                                        <label for="experience_year[]">Année</label>
                                        <input type="text" name="experience_year[]" value="<?php echo esc_attr($exp['year']); ?>">
                                    </div>
                                    <div class="input">
                                        <label for="experience_real[]">Réalisateur</label>
                                        <input type="text" name="experience_real[]" value="<?php echo esc_attr($exp['real']); ?>">
                                    </div>
                                    <div class="input">
                                        <label for="experience_prod[]">Production</label>
                                        <input type="text" name="experience_prod[]" value="<?php echo esc_attr($exp['prod']); ?>">
                                    </div>
                                    <div class="input">
                                        <label for="experience_poste[]">Poste</label>
                                        <input type="text" name="experience_poste[]" value="<?php echo esc_attr($exp['poste']); ?>">
                                    </div>
                                    <div class="input">
                                        <label for="experience_poste_chef[]">Chef de poste</label>
                                        <input type="text" name="experience_poste_chef[]" value="<?php echo esc_attr($exp['poste_chef']); ?>">
                                    </div>
                                </div>
                                <div class="remove-exp"><img src="<?php echo get_stylesheet_directory_uri(); ?>/assets/icons/poubelle.png" alt=""></div>                           
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
                <button type="button" id="add-experience">+</button>
            </div>
            <div class="section section-annexe">
                <h3>Compétences annexes</h3>
                <div class="annexe-container">
                    <div class="info">
                        <p class="info-text">
                        Vous pouvez listez ici vos compétences annexes par exemple conduite de drone, maquillage fx etc.
                        </p>
                    </div>
                    <div class="annex-input">
                        <div class="input">
                            <input type="hidden" name="competences" value="<?php echo $competences_converted ?>" id="hidden-input-competence">
                            <input class="input" type="text" for="annexe" id="add-annexe-input">
                        </div>
                        <p id="add-competences" class="button">+</p>
                    </div>
                    <div id="comptetences-container">
                        <?php if (!empty($competences)) : ?>
                            <?php foreach ($competences as $annexe) : ?>
                                <div class="bubule"><span><?php echo $annexe ?></span><span class="cross" data-filter="<?php echo $annexe ?>">×</span></div>
                            <?php endforeach; ?>
                        <?php endif ?>
                    </div>
                </div>
            </div>
            <div class="half-child">
                <div class="section section-description split-section">
                    <h3>Présentation</h3>
                    <div class="description-container">
                        <div class="info">
                            <p class="info-text">
                                Dites nous en plus sur vous
                            </p>
                        </div>
                        <textarea name="description" rows="5"><?php echo esc_textarea($description); ?></textarea>
                    </div>
                </div>
                <div class="section section-materiel split-section">
                    <h3>Mon matériel</h3>
                    <div class="materiel-container">
                        <div class="info">
                            <p class="info-text">
                            Si vous disposez de matériel vous pouvez télécharger un document les listant ci-dessous
                            </p>
                        </div>
                        <div class="materiel">
                            <div class="upload-file file-upload">
                                <img id="file-preview" class="<?php if (empty($additionnal_file)) { echo 'empty'; } ?>"  src="<?php if (empty($additionnal_file)) { echo esc_url( get_stylesheet_directory_uri() . '/assets/icons/telecharger.png' ); } else { echo esc_url($additionnal_file); } ?>" alt="Liste materiel" />
                                <input type="file" id="additionnal-file" name="additionnal_file" hidden>
                            </div>
                            <div id="remove-additionnal-file" class="remove-img"><img src="<?php echo get_stylesheet_directory_uri(); ?>/assets/icons/poubelle.png" alt=""></div>                           
                            <div id="upload-additionnal-file-error" class="info">
                            </div>
                        </div>
                        
                    </div>
                </div>
            </div>
            <div class="fixed-button">
                <button type="submit" name="update_profile" class="button">Mettre à jour</button>
            </div>
        </form>
    </div>
</div>

<script>
    const submitButton = document.getElementById('submit-button');
    const profileUploadPreview = document.getElementById('profile-preview');   
    const profilePictureInput = document.getElementById('profile-picture');
    const profilePictureRemove = document.getElementById('remove-profile-picture');
    profileUploadPreview.addEventListener('click', () => profilePictureInput.click());

    const selectedFromPHP = <?php echo json_encode($postes_terms); ?>;
    let selected = selectedFromPHP || [];

    const tagsContainer = document.getElementById("selectedTags");
    const inputHidden = document.getElementById("postesInput");

    const addCompetences = document.getElementById('add-competences');
    const competencesContainer = document.getElementById('comptetences-container');
    const competencesInput = document.getElementById('hidden-input-competence')
    let inputHiddenValue = competencesInput.value.split(",");
                  
    const filePreview = document.getElementById('file-preview');
    const fileInput = document.getElementById('additionnal-file');
    const fileRemove = document.getElementById('remove-additionnal-file');
    filePreview.addEventListener('click', () => fileInput.click());


    function validateForm() {
        errors = document.getElementsByClassName('error');

            // CHECK FOR DISPLAY NAME
            inputDisplayName = document.getElementById('input-display-name');
            errorDisplayName = document.getElementById('error-display-name');

            inputFirstName = document.getElementById('input-first-name');
            errorFirstName = document.getElementById('error-first-name');

            inputLastName = document.getElementById('input-last-name');
            errorLastName= document.getElementById('error-last-name');

            inputEmail = document.getElementById('input-email');
            errorEmail= document.getElementById('error-email');

            region = document.getElementById('region');
            errorRegion = document.getElementById('error-region');

            if (!inputDisplayName.value && !errorDisplayName) {
                error = 'Le nom d’utilisateur est obligatoire.';
                spanError = document.createElement('span')
                spanError.innerHTML = error;
                spanError.setAttribute('id', 'error-display-name')
                spanError.classList.add('error')
                inputDisplayName.parentNode.appendChild(spanError)
            }

            if (!inputFirstName.value && !errorFirstName) {
                error = 'Le prénom est obligatoire.';
                spanError = document.createElement('span')
                spanError.innerHTML = error;
                spanError.setAttribute('id', 'error-first-name')
                spanError.classList.add('error')
                inputFirstName.parentNode.appendChild(spanError)
            }

            if (!inputLastName.value && !errorLastName) {
                error = 'Le nom est obligatoire.';
                spanError = document.createElement('span')
                spanError.innerHTML = error;
                spanError.setAttribute('id', 'error-last-name')
                spanError.classList.add('error')
                inputLastName.parentNode.appendChild(spanError)
            }

            if (!inputEmail.value && !errorEmail) {
                error = 'L\'email est obligatoire.';
                spanError = document.createElement('span')
                spanError.innerHTML = error;
                spanError.setAttribute('id', 'error-email')
                spanError.classList.add('error')
                inputEmail.parentNode.appendChild(spanError)
            }

            if (!region.value && !errorRegion) {
                error = 'La région est obligatoire.';
                spanError = document.createElement('span')
                spanError.innerHTML = error;
                spanError.setAttribute('id', 'error-region')
                spanError.classList.add('error')
                region.parentNode.appendChild(spanError)
            }

            if (inputDisplayName.value && inputFirstName.value && inputLastName.value && inputEmail.value && region.value) {
                return true;
            } else {
                return false;
            }

    }

    const postes = document.getElementById('postes');
    postes.addEventListener('change', (e) => {
        console.log('allo allo ?')

        const selectedOption = postes.options[postes.selectedIndex];
        const option = e.target.closest("option[data-id]");
        if (!selectedOption) return;

        const id = selectedOption.dataset.id;
        const name = selectedOption.textContent.trim();
        
        if (selected.find(s => s.id === id)) {
            selected = selected.filter(s => s.id !== id);
            selectedOption.classList.remove("selected");
        } else {
            selected.push({ id, name });
            selectedOption.classList.add("selected");
        }

        updateTags()
    });

    function updateTags() {
        tagsContainer.innerHTML = "";
        selected.forEach(item => {
        const tag = document.createElement("div");
        tag.classList.add("tag");
        tag.innerHTML = `<span> ${item.name} </span><span class="remove" data-id="${item.id}">×</span>`;
        tagsContainer.appendChild(tag);
        });
        inputHidden.value = selected.map(s => s.id).join(",");
    }

    tagsContainer.addEventListener("click", (e) => {
        if (e.target.classList.contains("remove")) {
            let id = e.target.dataset.id;
            id = parseInt(id);
            selected = selected.filter(s => parseInt(s.id) !== id);
            document.querySelector(`.options-list option[data-id="${id}"]`)?.classList.remove("selected");
            updateTags();
        }
    });



    document.addEventListener("DOMContentLoaded", () => {
        const expContainer = document.getElementById('experience-container');
        const expAddBtn = document.getElementById('add-experience');

        expAddBtn.addEventListener('click', () => {
            expContainer.insertAdjacentHTML('beforeend', `
                <div class="experience">
                    <div class="experience-input">
                        <div class="input">
                            <label for="experience_titre[]">Nom</label>
                            <input type="text" name="experience_titre[]">
                        </div>
                        <div class="input">
                            <label for="experience_year[]">Année</label>
                            <input type="text" name="experience_year[]">
                        </div>
                        <div class="input">
                            <label for="experience_real[]">Réalisateur</label>
                            <input type="text" name="experience_real[]">
                        </div>
                        <div class="input">
                            <label for="experience_prod[]">Production</label>
                            <input type="text" name="experience_prod[]">
                        </div>
                        <div class="input">
                            <label for="experience_poste[]">Poste</label>
                            <input type="text" name="experience_poste[]">
                        </div>
                        <div class="input">
                            <label for="experience_poste_chef[]">Chef de poste</label>
                            <input type="text" name="experience_poste_chef[]">
                        </div>
                    </div>
                    <div class="remove-exp button"><img src="<?php echo get_stylesheet_directory_uri(); ?>/assets/icons/poubelle.png" alt=""></div>
                </div>
            `);
        });

        expContainer.addEventListener('click', (e) => {
            if (e.target.classList.contains('remove-exp')) {
                e.target.closest('.experience').remove();
            }
        });

        if (selected.length > 0) {
            updateTags();
            // Marque les <option> déjà sélectionnées
            selected.forEach(item => {
                const option = document.querySelector(`#postes option[data-id="${item.id}"]`);
                if (option) option.classList.add("selected");
            });
        }


        // Preview photo de profil
        profilePictureInput.addEventListener('change', (e) => {
            errorDiv = document.getElementById('upload-profile-picture-error')
            errorDiv.innerHTML = '';
            const file = e.target.files[0];
            if (file) {
                if (file.size > 5 * 1024 * 1024) {
                    errorDivContent = document.createElement('p')
                    errorDivContent.classList.add('info-text')
                    errorDivContent.innerHTML = 'Le fichier dépasse la taille maximale autorisée de 5 Mo.';
                    errorDiv.appendChild(errorDivContent)
                } else {
                    const reader = new FileReader();
                    reader.onload = (event) => {
                        profileUploadPreview.src = event.target.result;
                    };
                    reader.readAsDataURL(file);
                    profileUploadPreview.classList.remove("empty");
                }
                
            }
            
        });

        profilePictureRemove.addEventListener('click', (e) => {
            <?php $profile_picture = []; ?>
            profileUploadPreview.classList.add("empty");
            profileUploadPreview.src = '<?php echo esc_url( get_stylesheet_directory_uri() . '/assets/icons/telecharger.png') ?>';
        });

        fileRemove.addEventListener('click', (e) => {
            <?php $file_url = []; ?>
            filePreview.classList.add("empty");
            filePreview.src = '<?php echo esc_url( get_stylesheet_directory_uri() . '/assets/icons/telecharger.png') ?>';
        });

        fileInput.addEventListener('change', (e) => {
            errorDiv = document.getElementById('upload-additionnal-file-error')
            errorDiv.innerHTML = '';

            const file = e.target.files[0];
            if (file) {
                if (file.size > 5 * 1024 * 1024) {
                    errorDivContent = document.createElement('p')
                    errorDivContent.classList.add('info-text')
                    errorDivContent.innerHTML = 'Le fichier dépasse la taille maximale autorisée de 5 Mo.';
                    errorDiv.appendChild(errorDivContent)
                } else {
                    const reader = new FileReader();
                    if (file.type == 'application/pdf' || file.type == 'image/heic') {
                        filePreview.src = '<?php echo $default_doc_img_url ?>';
                    } else {
                        reader.onload = (event) => {
                            filePreview.src = event.target.result;
                        };
                    }
                    
                    reader.readAsDataURL(file);
                    filePreview.classList.remove("empty");
                }
            }
        });




        competencesContainer.addEventListener('click', (e) => {
            if (e.target.classList.contains("cross")) {
                e.target.closest('.bubule').remove();
                let value = competencesInput.value.split(",");
                let data = e.target.dataset.filter;
                
                if (value.includes(e.target.dataset.filter)) {
                    const index = value.indexOf(data);
                    value.splice(index, 1);
                    competencesInput.value = value;
                }
            }
        });

        addCompetences.addEventListener('click', () => {
            const input = document.getElementById('add-annexe-input');
            if (input.value != '') {
                var toInsert = '<div class="bubule"><span>' + input.value + '</span><span class="cross" data-filter="' +  input.value + '">×</span></div>';
                inputHiddenValue.push(input.value)
                competencesContainer.insertAdjacentHTML('beforeEnd', toInsert);
                competencesInput.value = inputHiddenValue;
                input.value = "";
            }
        });
        
    });

</script>

<?php get_footer(); ?>
