<?php
/**
 * ACRIB Core MU-Plugin
 * Always-on: custom footer, security hardening, performance tweaks.
 * @version 1.4
 */

// --- Remove Kadence default copyright footer ---
// template-hooks.php is included at the root of functions.php, so the action
// is added before after_setup_theme fires. Priority 999 removes it after.
add_action('after_setup_theme', function () {
    remove_action('kadence_footer', 'Kadence\footer_markup');
    remove_action('kadence_footer_html', 'Kadence\footer_html');
}, 999);

// --- Transparent header body class on homepage + its Polylang translations ---
// Kadence's layout/component.php adds non-transparent-header at priority 10.
// We run at 999 to remove it and add transparent-header (used by Kadence JS).
add_filter('body_class', function ($classes) {
    $is_front = is_front_page();
    // Also detect translated homepages via Polylang
    $is_front_translation = false;
    if (!$is_front && is_singular() && function_exists('pll_get_post_translations')) {
        $front_id = (int) get_option('page_on_front');
        if ($front_id) {
            $translations = pll_get_post_translations($front_id);
            $is_front_translation = in_array(get_the_ID(), $translations, true);
        }
    }
    if ($is_front || $is_front_translation) {
        $classes = array_diff($classes, ['non-transparent-header', 'mobile-non-transparent-header']);
        $classes[] = 'transparent-header';
        $classes[] = 'mobile-transparent-header';
    }
    return $classes;
}, 999);

// --- Footer: bottom bar with legal links + Cloud Host credit ---
add_action('wp_footer', function () {
    $year       = date('Y');
    $legal_url  = home_url('/aviso-legal/');
    $pp_url     = home_url('/politica-privacidad/');
    $cookie_url = home_url('/politica-cookies/');
    ?>
    <div class="acrib-footer-bottom">
      <div class="acrib-footer-bottom-inner">
        <p class="acrib-footer-copyright">
          &copy; <?php echo $year; ?> <strong>ACRIB</strong> &mdash; Asociaci&oacute;n Casa Rom&acirc;neasc&#259; de las Islas Baleares
        </p>
        <a class="acrib-footer-fb" href="https://www.facebook.com/profile.php?id=61583585888787" target="_blank" rel="noopener noreferrer" aria-label="ACRIB en Facebook"><svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/></svg></a>
          <ul class="acrib-footer-legal-links">
          <li><a href="<?php echo esc_url($legal_url); ?>">Aviso Legal</a></li>
          <li><a href="<?php echo esc_url($pp_url); ?>">Privacidad</a></li>
          <li><a href="<?php echo esc_url($cookie_url); ?>">Cookies</a></li>
        </ul>
        <p class="acrib-footer-hosted">
          Hosted &amp; Maintained by <a href="https://cloudhost.es" target="_blank" rel="noopener noreferrer">Cloud Host</a>
        </p>
      </div>
    </div>
    <?php
}, 100);

// --- Security headers ---
add_action('send_headers', function () {
    if (!is_admin()) {
        header('X-Frame-Options: SAMEORIGIN');
        header('X-Content-Type-Options: nosniff');
        header('Referrer-Policy: strict-origin-when-cross-origin');
        header('Permissions-Policy: camera=(), microphone=(), geolocation=()');
    }
});

// --- Disable XML-RPC ---
add_filter('xmlrpc_enabled', '__return_false');
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'wp_generator');
remove_action('wp_head', 'wp_shortlink_wp_head');

// --- Disable REST API user enumeration ---
add_filter('rest_endpoints', function ($endpoints) {
    unset($endpoints['/wp/v2/users'], $endpoints['/wp/v2/users/(?P<id>[\d]+)']);
    return $endpoints;
});

// --- Disable emoji (reduces ~20KB page weight) ---
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('wp_print_styles', 'print_emoji_styles');
remove_action('admin_print_scripts', 'print_emoji_detection_script');
remove_action('admin_print_styles', 'print_emoji_styles');
remove_filter('the_content_feed', 'wp_staticize_emoji');
remove_filter('comment_text_rss', 'wp_staticize_emoji');
remove_filter('wp_mail', 'wp_staticize_emoji_for_email');

// --- Limit post revisions ---
if (!defined('WP_POST_REVISIONS')) {
    define('WP_POST_REVISIONS', 3);
}

// --- Global: hide Kadence title section on pages with custom heroes ---
// Kadence free ignores _kadence_post_layout title:hide meta.
// We read it ourselves and output the fix for any page that set it.
add_action('wp_head', function () {
    if (is_singular()) {
        $layout = get_post_meta(get_the_ID(), '_kadence_post_layout', true);
        $meta   = $layout ? json_decode($layout, true) : [];
        $hide_title = isset($meta['title'])  && $meta['title']  === 'hide';
        $full_width = isset($meta['layout']) && $meta['layout'] === 'fullwidth';
        if ($hide_title || $full_width) {
            $id    = get_the_ID();
            $rules = [];
            if ($hide_title) {
                $rules[] = '.page-id-' . $id . ' .entry-hero.page-hero-section{display:none!important}';
            }
            if ($full_width) {
                $rules[] = '.page-id-' . $id . ' .entry-content-wrap{padding:0!important;box-shadow:none!important;margin:0!important;background:none!important}';
                $rules[] = '.page-id-' . $id . ' .content-area{max-width:100%!important;padding:0!important}';
            }
            if ($rules) {
                echo '<style id="acrib-page-fixes-' . $id . '">' . implode("\n", $rules) . '</style>' . "\n";
            }
        }
    }
}, 5);

// --- Homepage + translations: inject critical CSS fixes ---
// Uses .home (Spanish front page) and .transparent-header (all front page variants)
// so the same rules apply to RO and EN translated homepages.
add_action('wp_head', function () {
    if (!is_front_page() && !is_singular()) return;
    // Only inject for actual front page or its translations
    $inject = is_front_page();
    if (!$inject && function_exists('pll_get_post_translations')) {
        $front_id = (int) get_option('page_on_front');
        if ($front_id) {
            $inject = in_array(get_the_ID(), pll_get_post_translations($front_id), true);
        }
    }
    if (!$inject) return;
    echo '<style id="acrib-homepage-fixes">
/* ── Transparent header overlay on homepage and translated versions ───── */
/* Position header absolutely so it overlays the hero without pushing      */
/* content down — Kadence Pro transparent header effect, replicated.       */
.home #masthead.site-header,
.transparent-header #masthead.site-header{
    position:absolute;
    top:0;left:0;right:0;
    z-index:1000;
    background:transparent!important;
    box-shadow:none!important;
}
/* Remove top margin Kadence adds to offset the header height */
.home .content-area,
.home .site-content,
.home #content,
.transparent-header .content-area,
.transparent-header .site-content,
.transparent-header #content{
    margin-top:0!important;
    padding-top:0!important;
}
/* Remove Kadence blank page-title section above hero on Spanish homepage */
.home .entry-hero.page-hero-section{display:none!important}
/* Remove bottom margin that creates gap after the last section */
.home .content-area,
.transparent-header .content-area{margin-bottom:0!important}
/* Remove boxed content styling */
.home .entry-content-wrap,
.transparent-header .entry-content-wrap{
    padding:0!important;
    box-shadow:none!important;
    margin:0!important;
    background:none!important;
}
/* ── Hero: fill exactly one viewport height ─────────────────────────── */
.acrib-hero.wp-block-cover{
    height:100svh!important;
    height:100vh!important;
    min-height:0!important;
}
/* Centre hero content; padding-top clears the overlaid header */
.acrib-hero .wp-block-cover__inner-container{
    height:100%!important;
    min-height:0!important;
    display:flex!important;
    flex-direction:column!important;
    align-items:center!important;
    justify-content:center!important;
    padding:80px 2rem 3rem!important;
    box-sizing:border-box!important;
}
</style>' . "\n";
}, 5);
