<?php
/**
 * Plugin Name: Fe Adulta - hide imported artifacts
 * Description: Oculta en frontend artefactos importados hasta decidir una limpieza definitiva.
 */

function fea_current_request_path() {
    $path = parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH);
    return is_string($path) ? trim($path, '/') : '';
}

function fea_is_bad_imported_request_path() {
    $path = fea_current_request_path();
    return (bool)preg_match('~(^|/)tag/1/?$~', $path)
        || (bool)preg_match('~(^|/)[0-9]{2}-[0-9]{2}-[0-9]{4}/?$~', $path);
}

function fea_is_bad_imported_tag($term) {
    return $term
        && isset($term->taxonomy, $term->slug, $term->name)
        && $term->taxonomy === 'post_tag'
        && ($term->slug === '1' || $term->name === '1');
}

add_filter('get_the_terms', function($terms, $post_id, $taxonomy) {
    if (is_admin() || $taxonomy !== 'post_tag' || empty($terms) || is_wp_error($terms)) {
        return $terms;
    }

    return array_values(array_filter($terms, function($term) {
        return !fea_is_bad_imported_tag($term);
    }));
}, 10, 3);

add_filter('get_terms', function($terms, $taxonomies) {
    if (is_admin() || is_wp_error($terms) || empty($terms) || !in_array('post_tag', (array)$taxonomies, true)) {
        return $terms;
    }

    return array_values(array_filter($terms, function($term) {
        return !fea_is_bad_imported_tag($term);
    }));
}, 10, 2);

add_filter('redirect_canonical', function($redirect_url) {
    return fea_is_bad_imported_request_path() ? false : $redirect_url;
}, 10);

add_filter('do_redirect_guess_404_permalink', function($do_redirect) {
    return fea_is_bad_imported_request_path() ? false : $do_redirect;
}, 10);

add_filter('wp_redirect', function($location) {
    return fea_is_bad_imported_request_path() ? false : $location;
}, 0);

add_action('template_redirect', function() {
    if (!is_tag('1') && !fea_is_bad_imported_request_path()) {
        return;
    }

    global $wp_query;
    $wp_query->set_404();
    status_header(404);
    nocache_headers();
}, 0);
