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

if (!is_user_logged_in()) {
    wp_safe_redirect(site_url('index.php/connexion'));
    exit;
}

$current_user = wp_get_current_user();
$user_id = $current_user->ID;
$default_doc_img_url = get_stylesheet_directory_uri() . '/assets/pictures/default-img-doc.png';

// Récuperer la photo de profile
$photo_url = get_user_meta($user_id, 'profile_photo', true) ?: [];

// Récuperer le show phone et show email
$show_phone = get_user_meta($user_id, 'show_phone', true);
$show_email = get_user_meta($user_id, 'show_email', true);

// Récuperer la région
$region = get_user_meta($user_id, 'region', true);
if (!empty($region)) {
    $region = get_term($region, 'region');
    $region = $region->term_id;
}

$poste_principal = get_user_meta($user_id, 'poste_principal', true);

$stored_permis = get_user_meta(get_current_user_id(), 'user_permis', true);
if (!is_array($stored_permis)) $stored_permis = [];

$stored_postes = get_user_meta($user_id, 'user_postes', true); // ex: [12, 45, 78]
if (!is_array($stored_postes)) $stored_postes = [];

// Récupérer les termes correspondants
$selected_terms = [];
foreach ($stored_postes as $term_id) {
    $term = get_term($term_id, 'metier');
    if ($term && !is_wp_error($term)) {
        $selected_terms[] = [
            'id' => $term->term_id,
            'name' => $term->name,
        ];
    }
}

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

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

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

// Récuperer les experiences 
$experiences_existantes = get_user_meta($user_id, 'experiences', true);
if (!is_array($experiences_existantes)) {
    $experiences_existantes = [];
}

// Récuperer les competences actuels 
$competences_actuels = get_user_meta($user_id, 'competences', true) ?: [];

$competences_converted = implode(", ", $competences_actuels);
// Récuperer la photo du maateriel

$file_url = get_user_meta($user_id, 'fichier_supplementaire', true) ?: [];

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


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


// SUBMIT
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_profile'])) {

    
    if (empty($_POST['first_name'])) {
        $firstNameErr = 'Prénom obligatoire';
    } else {
        update_user_meta($user_id, 'first_name', sanitize_text_field($_POST['first_name']));
    }

    if (empty($_POST['last_name'])) {
        $lastNameErr = 'Nom obligatoire';
    } else {
        update_user_meta($user_id, 'last_name', sanitize_text_field($_POST['last_name']));
    }

    if (empty($_POST['email'])) {
        $emailErr = 'Email obligatoire';
    } else {
        wp_update_user([
            'ID' => $user_id,
            'user_email' => sanitize_email($_POST['email'])
        ]);
    }

    if (empty($_POST['region'])) {
        $regionErr = 'Région obligatoire';
    } else {
        update_user_meta($user_id, 'region', sanitize_text_field($_POST['region']));
    }

    
    if (empty($_POST['display_name'])) {
        $displayNameErr = 'Nom d\'utilisateur obligatoire';
    } else {
        wp_update_user([
            'ID' => $user_id,
            'display_name' => sanitize_text_field($_POST['display_name'])
        ]);
    }

    

    // INFO PRINCIPALE

    if (!empty($_FILES['profile_photo']['name'])) {
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        $upload = wp_handle_upload($_FILES['profile_photo'], ['test_form' => false]);
        if (!isset($upload['error']) && isset($upload['url'])) {
            update_user_meta($user_id, 'profile_photo', esc_url($upload['url']));
        }
    }
    update_user_meta($user_id, 'telephone', sanitize_text_field($_POST['telephone']));
    update_user_meta($user_id, 'user_email', sanitize_email($_POST['email']));


    // INFO PUBLIQUE
    $show_phone_stocked = isset($_POST['show_phone']) ? true : false;
    update_user_meta($user_id, 'show_phone', $show_phone_stocked);

    $show_email = isset($_POST['show_email']) ? true : false;
    update_user_meta($user_id, 'show_email', $show_email);


    update_user_meta($user_id, 'poste_principal', intval($_POST['poste_principal']));


    if (!empty($_POST['permis'])) {
        $permis = isset($_POST['permis']) ? $_POST['permis'] : [];        
        update_user_meta(get_current_user_id(), 'user_permis', $permis);
    } else {
        update_user_meta(get_current_user_id(), 'user_permis', []);
    }

    $raw_postes = sanitize_text_field($_POST['postesInput'] ?? '');
    $postes_ids = array_filter(array_map('intval', explode(',', $raw_postes)));
    // 2️⃣ Mise à jour dans la base
    update_user_meta($user_id, 'user_postes', $postes_ids);   
    $experiences = [];
    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]),
            ];
        }
    }
    update_user_meta($user_id, 'experiences', $experiences);
    

    $competences = array_filter(array_map('sanitize_text_field', explode(',', $_POST['competences'] ?? '')));
    update_user_meta($user_id, 'competences', $competences);

    update_user_meta($user_id, 'presentation', sanitize_textarea_field($_POST['presentation']));

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

    if (empty($firstNameErr) && empty($lastNameErr) && empty($emailErr) && empty($displayNameErr) && empty($regionErr)) {
        wp_safe_redirect(site_url('index.php/profil'));
    } else {
        print_r('oh oh');
    };
}

get_header();
?>

<div class="edit-profile-page p-r-l-40">
    <div class="container">
        <form method="POST" enctype="multipart/form-data">
            <div class="section global-info">
                <h3>Informations principales</h3>
                <div class="child-section">
                    <div class="upload-file profile-picture-upload">
                        <img id="profile-preview" class="<?php if (empty($photo_url)) { echo 'empty'; } ?>"  src="<?php if (empty($photo_url)) { echo esc_url( get_stylesheet_directory_uri() . '/assets/icons/telecharger.png' ); } else { echo esc_url($photo_url); } ?>" alt="Photo de profil" />
                        <input type="file" id="profile-photo" name="profile_photo" accept="image/*" hidden>
                    </div>
                    <div class="input-section">
                        <div class="input">
                            <label for="display_name">Nom d'utilisateur <span class="displayNameErr">* <?php echo $displayNameErr ?></span></label>
                            <input type="text" name="display_name" value="<?php echo esc_attr($current_user->display_name); ?>">
                        </div>
                        <div class="input">
                            <label for="first_name">Prénom <span class="firstNameErr">* <?php echo $firstNameErr ?></span></label>
                            <input type="text" name="first_name" value="<?php echo esc_attr($current_user->first_name);  ?>">
                        </div>
                        <div class="input">
                            <label for="last_name">Nom <span class="lastNameErr">* <?php echo $lastNameErr ?></span></label>
                            <input type="text" name="last_name" value="<?php  echo esc_attr($current_user->last_name); ?>">
                        </div>
                        <div class="input">
                            <label for="telephone">Téléphone </label>
                            <input type="text" name="telephone" value="<?php echo esc_attr($current_user->telephone); ?>">
                        </div>
                        <div class="input">
                            <label for="email">Email <span class="emailErr">* <?php echo $emailErr ?></span></label>
                            <input type="email" name="email" value="<?php echo esc_attr($current_user->user_email); ?>">
                        </div>
                        <div class="input">
                            <label for="region">Région <span id="regionErr">* <?php echo $regionErr ?></span></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">
                                <span class="info-text">
                                    Précisez la région dans laquelle vous résidez
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="section public-info">
                <h3>Informations publiques</h3>
                <div class="child-section padding-b-10">
                    <div class="input-section">
                        <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, $stored_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>

                            <!-- Conteneur pour les tags -->

                            <!-- Champ caché pour envoi -->
                            <input type="hidden" id="postesInput" name="postesInput" value="<?php echo implode(',', $stored_postes); ?>" />
                        </div>
                        <div class="custom-select">
                            <div id="selectedTags" class="tags-container"></div>
                        </div>
                    </div>
                </div>
                <div class="child-section">
                    <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>
                            <span class="info-text">
                                Si vous ne cocher aucune des deux options, vous serrez injoignable via le site
                            </span>
                        </div>
                    </div>
                    <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">
                                <span class="info-text">
                                    Poste que vous occupez actuellement
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="child-section">
                    <div class="checkbox">
                        <span>Permis Classique</span>
                        <div>
                            <?php foreach ($terms_permis as $permis) :?>
                                <?php if($permis->parent == 67) :?>
                            <div>
                                <input type='checkbox' name='permis[]' value='<?php echo $permis->term_id?>' <?php checked(in_array($permis->term_id, $stored_permis)); ?>>
                                <label><?php echo esc_html($permis->name) ?></label>
                            </div>
                            <?php endif; endforeach; ?>
                        </div>
                    </div>
                    <div class="checkbox">
                        <span>Permis CACES</span>
                        <div>
                            <?php foreach ($terms_permis as $permis) :?>
                                <?php if($permis->parent == 66) :?>
                            <div>
                                <input type='checkbox' name='permis[]' value='<?php echo $permis->term_id?>' <?php checked(in_array($permis->term_id, $stored_permis)); ?>>
                                <label><?php echo esc_html($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_existantes)) : ?>
                        <?php foreach ($experiences_existantes 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 button"><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">
                        <span class="info-text">
                        Vous pouvez listez ici vos compétences annexes par exemple conduite de drone, maquillage fx etc.
                        </span>
                    </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>
                        <span id="add-competences" class="button">+</span>
                    </div>
                    <div id="comptetences-container">
                        <?php if (!empty($competences_actuels)) : ?>
                            <?php foreach ($competences_actuels as $annexe) : ?>
                                <div class="bubule"><span><?php echo $annexe ?></span><span class="cross" data-filter="<?php echo $annexe ?>">X</span></div>
                            <?php endforeach; ?>
                        <?php endif ?>
                    </div>
                </div>
            </div>
            <div class="half-child">
                <div class="section section-presentation split-section">
                    <h3>Présentation</h3>
                    <div class="presentation-container">
                        <div class="info">
                            <span class="info-text">
                                Dites nous en plus sur vous
                            </span>
                        </div>
                        <textarea name="presentation" rows="5"><?php echo esc_textarea(get_user_meta($user_id, 'presentation', true)); ?></textarea>
                    </div>
                </div>
                <div class="section section-materiel split-section">
                    <h3>Mon matériel</h3>
                    <div class="materiel-container">
                        <div class="info">
                            <span class="info-text">
                            Si vous disposez de matériel vous pouvez télécharger un document les listant ci-dessous
                            </span>
                        </div>
                        <div class="materiel">
                            <div class="upload-file file-upload">
                                <img id="file-trigger" class="<?php if (empty($file_url)) { echo 'empty'; } ?>"  src="<?php if (empty($file_url)) { echo esc_url( get_stylesheet_directory_uri() . '/assets/icons/telecharger.png' ); } else { echo esc_url($file_url); } ?>" alt="Liste materiel" />
                                <input type="file" id="fichier_supplementaire" name="fichier_supplementaire" hidden>
                            </div>
                            <div id="remove-img" class="remove-img"><img src="<?php echo get_stylesheet_directory_uri(); ?>/assets/icons/poubelle.png" alt=""></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 profileUpload = document.getElementById('profile-preview');   
    const profileInput = document.getElementById('profile-photo');
    profileUpload.addEventListener('click', () => profileInput.click());
    const tagsContainer = document.getElementById("selectedTags");
    const inputHidden = document.getElementById("postesInput");
    const selectedFromPHP = <?php echo json_encode($selected_terms); ?>;
    let selected = selectedFromPHP || [];

    const fileTrigger = document.getElementById('file-trigger');
    const fileInput = document.getElementById('fichier_supplementaire');
    const fileRemove = document.getElementById('remove-img');

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

        const addCompetences = document.getElementById('add-competences');
        const competencesContainer = document.getElementById('comptetences-container');
        const competencesInput = document.getElementById('hidden-input-competence')
        let inputHiddenValue = competencesInput.value.split(",");

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

        competencesContainer.addEventListener('click', (e) => {
            if (e.target.classList.contains("cross")) {
                e.target.closest('.bubule').remove();
            }
        });

        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 + '">X</span></div>';
                inputHiddenValue.push(input.value)
                competencesContainer.insertAdjacentHTML('beforeEnd', toInsert);
                competencesInput.value = inputHiddenValue;
                input.value = "";
            }
        });

        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
    profileInput.addEventListener('change', (e) => {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = (event) => {
                profileUpload.src = event.target.result;
            };
            reader.readAsDataURL(file);
            profileUpload.classList.remove("empty");
        }
        
    });

    fileTrigger.addEventListener('click', () => fileInput.click());

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

    fileInput.addEventListener('change', (e) => {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            if (file.type == 'application/pdf' || file.type == 'image/heic') {
                fileTrigger.src = '<?php echo $default_doc_img_url ?>';
            } else {
                reader.onload = (event) => {
                    fileTrigger.src = event.target.result;
                };
            }
            
            reader.readAsDataURL(file);
            fileTrigger.classList.remove("empty");
            
        }
        
    });


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

        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();
        }
    });
    
    
</script>

<?php get_footer(); ?>
