<?php
/**
 * Confort back-office : filtrage des layouts du flexible par type de contenu
 * (table « Filtrage BO » du SCHEMA — n'affecte pas le schéma GraphQL)
 * + colonne « Slug » dans les listings admin.
 */

defined('ABSPATH') || exit;

add_filter('acf/load_field/name=sections', 'cvb_filter_sections_layouts');

function cvb_filter_sections_layouts(array $field): array {
    // Uniquement le flexible content du BO — jamais en GraphQL/front
    // (le repeater `sections` du layout contenu_seo matche aussi ce filtre, d'où le test de key).
    if (!is_admin() || ($field['key'] ?? '') !== 'field_cvb_sections' || empty($field['layouts'])) {
        return $field;
    }

    $post_type = cvb_current_admin_post_type();
    if (!$post_type) {
        return $field;
    }

    $exclusions = [
        'page'      => ['specs_techniques', 'variantes_produit', 'fiche_chantier'],
        'produit'   => ['fiche_chantier'],
        'toiture'   => ['specs_techniques', 'certifications', 'variantes_produit', 'fiche_chantier'],
        'industrie' => ['specs_techniques', 'certifications', 'variantes_produit', 'fiche_chantier', 'avant_apres'],
        'reference' => ['specs_techniques', 'variantes_produit', 'grille_secteurs'],
    ];

    if (!isset($exclusions[$post_type])) {
        return $field;
    }

    $excluded = $exclusions[$post_type];

    $field['layouts'] = array_filter(
        $field['layouts'],
        static fn(array $layout): bool => !in_array($layout['name'], $excluded, true)
    );

    return $field;
}

/** Type de contenu de l'écran admin courant. */
function cvb_current_admin_post_type(): ?string {
    if (function_exists('get_current_screen')) {
        $screen = get_current_screen();
        if ($screen && $screen->post_type) {
            return $screen->post_type;
        }
    }
    if (!empty($_GET['post'])) {
        return get_post_type((int) $_GET['post']) ?: null;
    }
    if (!empty($_GET['post_type'])) {
        return sanitize_key((string) $_GET['post_type']);
    }
    global $typenow;

    return $typenow ?: null;
}

// Colonne « Slug » sur les listings des types éditoriaux.
add_action('admin_init', 'cvb_register_slug_columns');

function cvb_register_slug_columns(): void {
    foreach (['page', 'produit', 'toiture', 'industrie', 'reference', 'formulaire_hubspot'] as $post_type) {
        add_filter("manage_{$post_type}_posts_columns", 'cvb_add_slug_column');
        add_action("manage_{$post_type}_posts_custom_column", 'cvb_render_slug_column', 10, 2);
    }
}

function cvb_add_slug_column(array $columns): array {
    $date = $columns['date'] ?? null;
    unset($columns['date']);
    $columns['cvb_slug'] = 'Slug';
    if ($date !== null) {
        $columns['date'] = $date;
    }

    return $columns;
}

function cvb_render_slug_column(string $column, int $post_id): void {
    if ($column === 'cvb_slug') {
        echo '<code>' . esc_html(get_post_field('post_name', $post_id)) . '</code>';
    }
}
