<?php
/**
 * Plugin Name: TD Laboratoires
 * Description: Gestion et affichage de laboratoires en carrousel
 * Version: 1.0.1
 * Author: Thomas Dufranne
 * Author URI: https://td-plugins.com
 * Text Domain: td-laboratoires
 */

if (!defined('ABSPATH')) {
    exit;
}

// Enregistrement du Custom Post Type
function td_register_laboratoire_cpt() {
    $labels = [
        'name' => 'Laboratoires',
        'singular_name' => 'Laboratoire',
        'add_new' => 'Ajouter un laboratoire',
        'add_new_item' => 'Ajouter un nouveau laboratoire',
        'edit_item' => 'Modifier le laboratoire',
        'new_item' => 'Nouveau laboratoire',
        'view_item' => 'Voir le laboratoire',
        'search_items' => 'Rechercher un laboratoire',
        'not_found' => 'Aucun laboratoire trouvé',
        'not_found_in_trash' => 'Aucun laboratoire dans la corbeille'
    ];

    $args = [
        'labels' => $labels,
        'public' => true,
        'show_ui' => true,
        'show_in_menu' => true,
        'menu_icon' => 'dashicons-building',
        'supports' => ['title', 'thumbnail', 'editor'],
        'show_in_rest' => true,
        'has_archive' => true,
        'rewrite' => ['slug' => 'laboratoire'],
        'publicly_queryable' => true
    ];

    register_post_type('td_laboratoire', $args);
}
add_action('init', 'td_register_laboratoire_cpt');

// Exposition des meta dans l'API REST
function td_register_laboratoire_meta() {
    register_post_meta('td_laboratoire', '_td_lab_ville', [
        'show_in_rest' => true,
        'single' => true,
        'type' => 'string',
        'default' => ''
    ]);
    
    register_post_meta('td_laboratoire', '_td_lab_description', [
        'show_in_rest' => true,
        'single' => true,
        'type' => 'string',
        'default' => ''
    ]);
    
    register_post_meta('td_laboratoire', '_td_lab_lien', [
        'show_in_rest' => true,
        'single' => true,
        'type' => 'string',
        'default' => ''
    ]);
    
   
}
add_action('init', 'td_register_laboratoire_meta');

// Ajouter les métadonnées dans la réponse REST API
function td_add_laboratoire_meta_to_rest() {
    register_rest_field('td_laboratoire', 'laboratoire_meta', [
        'get_callback' => function($post) {
            return [
                'ville' => get_post_meta($post['id'], '_td_lab_ville', true) ?: '',
                'description' => get_post_meta($post['id'], '_td_lab_description', true) ?: '',
                'lien' => get_post_meta($post['id'], '_td_lab_lien', true) ?: ''
              
            ];
        },
        'schema' => [
            'description' => 'Métadonnées du laboratoire',
            'type' => 'object'
        ]
    ]);
}
add_action('rest_api_init', 'td_add_laboratoire_meta_to_rest');

// Ajout des meta boxes
function td_add_laboratoire_meta_boxes() {
    add_meta_box(
        'td_laboratoire_details',
        'Informations du laboratoire',
        'td_laboratoire_meta_box_callback',
        'td_laboratoire',
        'normal',
        'high'
    );
}
add_action('add_meta_boxes', 'td_add_laboratoire_meta_boxes');

// Affichage du formulaire dans la meta box
function td_laboratoire_meta_box_callback($post) {
    wp_nonce_field('td_laboratoire_save_meta', 'td_laboratoire_nonce');
    
    $ville = get_post_meta($post->ID, '_td_lab_ville', true);
    $description = get_post_meta($post->ID, '_td_lab_description', true);
    $lien = get_post_meta($post->ID, '_td_lab_lien', true);
  
    
    ?>
    <table class="form-table">
        <tr>
            <th><label for="td_lab_ville">Ville</label></th>
            <td><input type="text" id="td_lab_ville" name="td_lab_ville" value="<?php echo esc_attr($ville); ?>" class="regular-text"></td>
        </tr>
        <tr>
            <th><label for="td_lab_description">Description</label></th>
            <td><textarea id="td_lab_description" name="td_lab_description" rows="4" class="large-text"><?php echo esc_textarea($description); ?></textarea></td>
        </tr>
        <tr>
            <th><label for="td_lab_lien">Lien</label></th>
            <td><input type="url" id="td_lab_lien" name="td_lab_lien" value="<?php echo esc_url($lien); ?>" class="regular-text" placeholder="https://"></td>
        </tr>
        
    </table>
    <p><strong>Note :</strong> Le logo se définit via l'image mise en avant.</p>
    <?php
}

// Sauvegarde des meta données
function td_save_laboratoire_meta($post_id) {
    if (!isset($_POST['td_laboratoire_nonce'])) {
        return;
    }
    
    if (!wp_verify_nonce($_POST['td_laboratoire_nonce'], 'td_laboratoire_save_meta')) {
        return;
    }
    
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }
    
    if (!current_user_can('edit_post', $post_id)) {
        return;
    }
    
    $fields = ['ville', 'description', 'lien'];
    
    foreach ($fields as $field) {
        if (isset($_POST["td_lab_{$field}"])) {
            $value = sanitize_text_field($_POST["td_lab_{$field}"]);
            if ($field === 'description') {
                $value = sanitize_textarea_field($_POST["td_lab_{$field}"]);
            }
            if ($field === 'lien') {
                $value = esc_url_raw($_POST["td_lab_{$field}"]);
            }
            update_post_meta($post_id, "_td_lab_{$field}", $value);
        }
    }
}
add_action('save_post_td_laboratoire', 'td_save_laboratoire_meta');

// Ajouter une colonne pour l'image à la une dans la liste admin
function td_add_laboratoire_columns($columns) {
    $new_columns = [];
    foreach ($columns as $key => $value) {
        if ($key === 'title') {
            $new_columns['thumbnail'] = 'Logo';
        }
        $new_columns[$key] = $value;
    }
    return $new_columns;
}
add_filter('manage_td_laboratoire_posts_columns', 'td_add_laboratoire_columns');

// Afficher l'image à la une dans la colonne
function td_display_laboratoire_thumbnail_column($column, $post_id) {
    if ($column === 'thumbnail') {
        $thumbnail_id = get_post_thumbnail_id($post_id);
        if ($thumbnail_id) {
            $thumbnail = wp_get_attachment_image($thumbnail_id, [60, 60], false, ['style' => 'width:60px;height:auto;']);
            echo $thumbnail;
        } else {
            echo '—';
        }
    }
}
add_action('manage_td_laboratoire_posts_custom_column', 'td_display_laboratoire_thumbnail_column', 10, 2);

// Rendre la colonne triable (optionnel)
function td_laboratoire_thumbnail_column_width() {
    echo '<style>.column-thumbnail { width: 80px; text-align: center; }</style>';
}
add_action('admin_head', 'td_laboratoire_thumbnail_column_width');

// Enregistrement du bloc
function td_register_laboratoires_block() {
    if (!function_exists('register_block_type')) {
        return;
    }
    
    wp_register_script(
        'td-laboratoires-block-editor',
        plugins_url('block-editor.js', __FILE__),
        ['wp-blocks', 'wp-element', 'wp-block-editor', 'wp-api-fetch'],
        '1.0.3',
        false
    );
    
    wp_register_script(
        'td-laboratoires-carousel',
        plugins_url('carousel.js', __FILE__),
        [],
        '1.0.1',
        true
    );
    
    wp_register_style(
        'td-laboratoires-carousel',
        plugins_url('carousel.css', __FILE__),
        [],
        '1.0.1'
    );
    
    register_block_type('td/laboratoires-carousel', [
        'editor_script' => 'td-laboratoires-block-editor',
        'script' => 'td-laboratoires-carousel',
        'style' => 'td-laboratoires-carousel',
        'render_callback' => 'td_render_laboratoires_carousel'
    ]);
}
add_action('init', 'td_register_laboratoires_block');

// Enregistrement du bloc liste
function td_register_laboratoires_liste_block() {
    if (!function_exists('register_block_type')) {
        return;
    }
    
    wp_register_script(
        'td-laboratoires-liste-editor',
        plugins_url('liste-editor.js', __FILE__),
        ['wp-blocks', 'wp-element', 'wp-block-editor', 'wp-api-fetch'],
        '1.0.2',
        false
    );
    
    wp_register_style(
        'td-laboratoires-liste',
        plugins_url('liste.css', __FILE__),
        [],
        '1.0.0'
    );
    
    register_block_type('td/laboratoires-liste', [
        'editor_script' => 'td-laboratoires-liste-editor',
        'style' => 'td-laboratoires-liste',
        'render_callback' => 'td_render_laboratoires_liste'
    ]);
}
add_action('init', 'td_register_laboratoires_liste_block');

// Rendu de la liste complète
function td_render_laboratoires_liste($attributes) {
    $laboratoires = get_posts([
        'post_type' => 'td_laboratoire',
        'posts_per_page' => -1,
        'orderby' => 'title',
        'order' => 'ASC',
        'post_status' => 'publish'
    ]);
    
    if (empty($laboratoires)) {
        return '<p>Aucun laboratoire à afficher.</p>';
    }
    
    wp_enqueue_style('td-laboratoires-liste');
    
    ob_start();
    ?>
    <div class="td-lab-liste">
        <?php foreach ($laboratoires as $lab) : 
            $ville = get_post_meta($lab->ID, '_td_lab_ville', true);
            $description = get_post_meta($lab->ID, '_td_lab_description', true);
            $lien = get_post_meta($lab->ID, '_td_lab_lien', true);
            
            $logo_id = get_post_thumbnail_id($lab->ID);
            $logo_url = $logo_id ? wp_get_attachment_image_url($logo_id, 'medium') : '';
        ?>
        <div class="td-lab-item">
            <?php if ($logo_url) : ?>
                <div class="td-lab-item-logo">
                    <img src="<?php echo esc_url($logo_url); ?>" alt="<?php echo esc_attr(get_the_title($lab)); ?>">
                </div>
            <?php endif; ?>
            <div class="td-lab-item-content">
                <h3 class="td-lab-item-title"><?php echo esc_html(get_the_title($lab)); ?></h3>
                <?php if ($ville) : ?>
                    <p class="td-lab-item-ville"><strong>Ville :</strong> <?php echo esc_html($ville); ?></p>
                <?php endif; ?>
                <?php if ($description) : ?>
                    <p class="td-lab-item-description"><?php echo esc_html($description); ?></p>
                <?php endif; ?>
               
                <?php if ($lien) : ?>
                    <p class="td-lab-item-link">
                        <a href="<?php echo esc_url($lien); ?>" target="_blank" rel="noopener noreferrer">Visiter le site</a>
                    </p>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
    <?php
    return ob_get_clean();
}

// Rendu du carrousel
function td_render_laboratoires_carousel($attributes) {
    $laboratoires = get_posts([
        'post_type' => 'td_laboratoire',
        'posts_per_page' => -1,
        'orderby' => 'title',
        'order' => 'ASC',
        'post_status' => 'publish'
    ]);
    
    if (empty($laboratoires)) {
        return '<p>Aucun laboratoire à afficher.</p>';
    }
    
    wp_enqueue_script('td-laboratoires-carousel');
    wp_enqueue_style('td-laboratoires-carousel');
    
    ob_start();
    ?>
    <div class="td-lab-carousel">
        <button class="td-lab-prev" aria-label="Laboratoire précédent">‹</button>
        <div class="td-lab-track">
            <?php foreach ($laboratoires as $lab) : 
                $ville = get_post_meta($lab->ID, '_td_lab_ville', true);
                $logo_id = get_post_thumbnail_id($lab->ID);
                $logo_url = $logo_id ? wp_get_attachment_image_url($logo_id, 'medium') : '';
            ?>
            <div class="td-lab-slide">
                <?php if ($logo_url) : ?>
                    <img src="<?php echo esc_url($logo_url); ?>" alt="<?php echo esc_attr(get_the_title($lab)); ?>">
                <?php endif; ?>
                <h3><?php echo esc_html(get_the_title($lab)); ?></h3>
                <?php if ($ville) : ?>
                    <p class="td-lab-ville"><?php echo esc_html($ville); ?></p>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
        </div>
        <button class="td-lab-next" aria-label="Laboratoire suivant">›</button>
    </div>
    <?php
    return ob_get_clean();
}
