<?php
/**
 * Taxonomies du SCHEMA : secteur, type_support + seed des termes initiaux.
 */

defined('ABSPATH') || exit;

add_action('init', 'cvb_register_taxonomies');

function cvb_register_taxonomies(): void {
    register_taxonomy('secteur', ['reference', 'industrie'], [
        'labels' => [
            'name'          => 'Secteurs',
            'singular_name' => 'Secteur',
            'menu_name'     => 'Secteurs',
        ],
        'hierarchical'        => true,
        'public'              => true,
        'publicly_queryable'  => false,
        'show_admin_column'   => true,
        'show_in_rest'        => true,
        'show_in_graphql'     => true,
        'graphql_single_name' => 'secteur',
        'graphql_plural_name' => 'secteurs',
        'rewrite'             => false,
    ]);

    register_taxonomy('type_support', ['reference', 'produit', 'toiture'], [
        'labels' => [
            'name'          => 'Types de support',
            'singular_name' => 'Type de support',
            'menu_name'     => 'Types de support',
        ],
        'hierarchical'        => true,
        'public'              => true,
        'publicly_queryable'  => false,
        'show_admin_column'   => true,
        'show_in_rest'        => true,
        'show_in_graphql'     => true,
        'graphql_single_name' => 'typeSupport',
        'graphql_plural_name' => 'typesSupport',
        'rewrite'             => false,
    ]);
}

// Seed des termes initiaux : une seule fois (flag option) + garde get_term_by.
add_action('init', 'cvb_seed_terms', 20);

function cvb_seed_terms(): void {
    if (get_option('cvb_terms_seeded')) {
        return;
    }

    $seed = [
        'secteur' => [
            'industrie'     => 'Industrie',
            'logistique'    => 'Logistique',
            'distribution'  => 'Distribution',
            'tertiaire'     => 'Tertiaire',
            'collectivites' => 'Collectivités',
            'agricole'      => 'Agricole',
            'erp'           => 'ERP',
        ],
        'type_support' => [
            'bitume'        => 'Bitume',
            'bac-acier'     => 'Bac acier',
            'fibrociment'   => 'Fibrociment',
            'tuiles-ciment' => 'Tuiles ciment',
            'toiture-plate' => 'Toiture plate',
            'epdm'          => 'EPDM',
            'pvc'           => 'PVC',
            'zinc'          => 'Zinc',
        ],
    ];

    foreach ($seed as $taxonomy => $terms) {
        if (!taxonomy_exists($taxonomy)) {
            return; // taxos pas encore enregistrées : on retentera au prochain init
        }
        foreach ($terms as $slug => $label) {
            if (!get_term_by('slug', $slug, $taxonomy)) {
                wp_insert_term($label, $taxonomy, ['slug' => $slug]);
            }
        }
    }

    update_option('cvb_terms_seeded', COVALBA_CORE_VERSION);
}
