<?php
/**
 * Plugin Name: Fe Adulta — Homepage
 * Description: Portada con selección editorial via ACF.
 * Version: 1.3
 */

// ── Foto de perfil de autor via ACF (campo en perfil de usuario) ──────────
add_action('acf/init', function() {
    if (!function_exists('acf_add_local_field_group')) return;
    acf_add_local_field_group([
        'key'    => 'group_user_foto_perfil',
        'title'  => 'Foto de perfil',
        'fields' => [[
            'key'           => 'field_user_foto_perfil',
            'label'         => 'Foto',
            'name'          => 'foto_perfil',
            'type'          => 'image',
            'instructions'  => 'Sube una foto cuadrada del autor (mínimo 100×100px).',
            'return_format' => 'url',
            'preview_size'  => 'thumbnail',
            'upload_folder' => 'autores',
        ]],
        'location' => [[
            ['param' => 'user_form', 'operator' => '==', 'value' => 'all'],
        ]],
    ]);
});

// Usar la foto del autor en lugar del Gravatar cuando existe
// Lee el attachment ID guardado en el meta 'foto_perfil' (campo ACF)
add_filter('get_avatar_url', function($url, $id_or_email, $args) {
    $user_id = null;
    if (is_numeric($id_or_email))            $user_id = (int) $id_or_email;
    elseif ($id_or_email instanceof WP_User) $user_id = $id_or_email->ID;
    elseif (is_string($id_or_email)) {
        $user = get_user_by('email', $id_or_email);
        if ($user) $user_id = $user->ID;
    }
    if (!$user_id) return $url;
    $attach_id = get_user_meta($user_id, 'foto_perfil', true);
    if ($attach_id) {
        $foto = wp_get_attachment_image_url((int) $attach_id, 'full');
        if ($foto) return $foto;
    }
    return $url;
}, 10, 3);

// ── Ordenar por fecha los resultados del buscador ACF en campos de portada ─
add_filter('acf/fields/relationship/query/key=field_portada_articulos', function($args) {
    $args['orderby'] = 'date';
    $args['order']   = 'DESC';
    return $args;
});
add_filter('acf/fields/relationship/query/key=field_portada_multimedia', function($args) {
    $args['orderby'] = 'date';
    $args['order']   = 'DESC';
    return $args;
});

// ── Campos ACF para la portada ────────────────────────────────────────────
add_action('acf/init', function() {
    if (!function_exists('acf_add_local_field_group')) return;

    $front_page_id = (int) get_option('page_on_front');

    acf_add_local_field_group([
        'key'    => 'group_portada_fea',
        'title'  => 'Contenido de la portada',
        'fields' => [
            [
                'key'           => 'field_portada_articulos',
                'label'         => 'Artículos seleccionados',
                'name'          => 'portada_articulos',
                'type'          => 'relationship',
                'instructions'  => 'Elige los artículos que aparecerán en la portada esta semana (máx. 9). Puedes buscar por título.',
                'post_type'     => ['post'],
                'post_status'   => ['publish', 'draft'],
                'filters'       => ['search', 'taxonomy'],
                'elements'      => ['featured_image'],
                'min'           => 0,
                'max'           => 9,
                'return_format' => 'object',
                'query_args'    => ['orderby' => 'date', 'order' => 'DESC'],
            ],
            [
                'key'           => 'field_portada_multimedia',
                'label'         => 'Multimedia seleccionado',
                'name'          => 'portada_multimedia',
                'type'          => 'relationship',
                'instructions'  => 'Elige los vídeos o audios para la portada (máx. 4).',
                'post_type'     => ['post'],
                'post_status'   => ['publish', 'draft'],
                'filters'       => ['search'],
                'elements'      => ['featured_image'],
                'min'           => 0,
                'max'           => 4,
                'return_format' => 'object',
                'query_args'    => ['orderby' => 'date', 'order' => 'DESC'],
            ],
        ],
        'location' => [[
            ['param' => 'page', 'operator' => '==', 'value' => (string) $front_page_id],
        ]],
        'position'      => 'normal',
        'style'         => 'default',
        'label_placement' => 'top',
    ]);
});

// ── Centrar bloque slider+librería (header template, todas las páginas) ───
add_action('wp_head', function() {
    ?>
    <style>
    /* El bloque de columnas con el slider usa márgenes negativos del FSE
       que lo desplazan. Lo forzamos a centrar con max-width explícito. */
    .wp-block-columns:has(.wp-block-nextend-smartslider3) {
        max-width: min(var(--wp--style--global--wide-size, 1340px), 100%);
        margin-left: auto !important;
        margin-right: auto !important;
        box-sizing: border-box;
        padding-left: var(--wp--preset--spacing--30);
        padding-right: var(--wp--preset--spacing--30);
    }

    /* Ocultar columna librería en tablet */
    @media (max-width: 900px) {
        .fea-slider-block .wp-block-column:last-child {
            display: none !important;
        }
    }

    /* Ocultar slider en móvil (banner superior sigue visible) */
    @media (max-width: 600px) {
        .fea-slider-block {
            display: none !important;
        }
    }

    /* Buscador del header: reducir altura */
    .wp-block-search__input {
        padding-top: 0.25rem !important;
        padding-bottom: 0.25rem !important;
        line-height: 1.3 !important;
    }
    .wp-block-search__button {
        padding-top: 0.25rem !important;
        padding-bottom: 0.25rem !important;
    }
    </style>
    <?php
});

// ── Estilos ───────────────────────────────────────────────────────────────
add_action('wp_head', function() {
    if (!is_front_page()) return;
    ?>
    <style>
    .fea-hero { border-bottom: 2px solid #111; padding-bottom: 2rem; margin-bottom: 2.5rem; }
    .fea-hero-link { display: block; text-decoration: none; color: inherit; }
    .fea-hero-link:hover .fea-hero-title { text-decoration: underline; text-underline-offset: 4px; }
    .fea-section-label { display: inline-block; font-size: 0.72rem; font-weight: 700; letter-spacing: 0.1em; text-transform: uppercase; color: #888; margin-bottom: 0.6rem; }
    .fea-hero-title { font-size: clamp(1.5rem, 4vw, 2.2rem); font-weight: 700; line-height: 1.2; margin: 0 0 0.75rem; color: #111; }
    .fea-hero-meta { display: flex; align-items: center; gap: 0.5rem; font-size: 0.875rem; color: #666; }

    .fea-section { margin-bottom: 3rem; }
    .fea-section-title { font-size: 0.72rem; font-weight: 700; letter-spacing: 0.1em; text-transform: uppercase; color: #888; margin: 0 0 1.25rem; padding-bottom: 0.5rem; border-bottom: 1px solid #e0e0e0; }

    .fea-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 1.5rem; }
    @media (max-width: 720px) { .fea-grid { grid-template-columns: 1fr 1fr; } }
    @media (max-width: 480px) { .fea-grid { grid-template-columns: 1fr; } }

    .fea-card { border-bottom: 1px solid #e5e5e5; padding-bottom: 1.1rem; }
    .fea-card-meta { display: flex; align-items: center; gap: 0.4rem; margin-bottom: 0.4rem; }
    .fea-avatar { border-radius: 50%; width: 28px !important; height: 28px !important; flex-shrink: 0; display: inline-block !important; }
    .fea-card-author { font-size: 0.78rem; font-weight: 600; color: #555; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .fea-card-title { font-size: 0.93rem; font-weight: 600; line-height: 1.35; margin: 0; }
    .fea-card-title a { text-decoration: none; color: #111; }
    .fea-card-title a:hover { text-decoration: underline; text-underline-offset: 3px; }
    </style>
    <?php
});


// ── Byline personalizado en artículos individuales ────────────────────────

// ── Byline personalizado: se gestiona desde el template FSE (ID 42359) ────
// El template wp_template 'single' ya contiene wp:avatar + wp:post-author-name
// + wp:post-terms. Este hook solo añade los estilos necesarios.
add_action('astra_single_header_bottom', function() {
    if (!is_single()) return;

    $author_id   = (int) get_the_author_meta('ID');
    $author_name = get_the_author_meta('display_name');
    $avatar_url  = get_avatar_url($author_id, ['size' => 48]);
    $author_url  = get_author_posts_url($author_id);

    $cat_str = '';
    $cats = get_the_category();
    if ($cats) {
        $cat_url = get_category_link($cats[0]->term_id);
        $cat_str = '<a href="' . esc_url($cat_url) . '" class="fea-byline-cat">'
                 . esc_html($cats[0]->name) . '</a>';
    }

    echo '<div class="fea-byline">'
       . '<a href="' . esc_url($author_url) . '" class="fea-byline-avatar-link">'
       . '<img src="' . esc_url($avatar_url) . '" alt="" width="48" height="48" class="fea-byline-avatar">'
       . '</a>'
       . '<div class="fea-byline-info">'
       . '<a href="' . esc_url($author_url) . '" class="fea-byline-name">' . esc_html($author_name) . '</a>'
       . $cat_str
       . '</div>'
       . '</div>';
});

add_action('wp_head', function() {
    if (!is_single()) return;
    ?>
    <style>
    .fea-byline { display: flex; align-items: center; gap: 0.75rem; margin-top: 0.75rem; }
    .fea-byline-avatar-link { flex-shrink: 0; }
    .fea-byline-avatar { border-radius: 50%; display: block; }
    .fea-byline-info { display: flex; flex-direction: column; gap: 0.2rem; }
    .fea-byline-name { font-size: 0.9rem; font-weight: 600; color: #222; text-decoration: none; }
    .fea-byline-name:hover { text-decoration: underline; }
    .fea-byline-cat { font-size: 0.78rem; color: #888; text-decoration: none; }
    .fea-byline-cat:hover { text-decoration: underline; color: #555; }
    </style>
    <?php
});

// ── Helpers ───────────────────────────────────────────────────────────────
function fea_title(string $title): string {
    $lower = mb_strtolower($title, 'UTF-8');
    return mb_strtoupper(mb_substr($lower, 0, 1, 'UTF-8'), 'UTF-8') . mb_substr($lower, 1, null, 'UTF-8');
}

function fea_card(object $post): string {
    $author_id   = $post->post_author;
    $author_name = get_the_author_meta('display_name', $author_id);
    $avatar_url  = get_avatar_url($author_id, ['size' => 28, 'default' => 'identicon']);
    $url         = get_permalink($post->ID);
    $title       = fea_title($post->post_title);
    return '<article class="fea-card">'
        . '<div class="fea-card-meta">'
        . '<img src="' . esc_url($avatar_url) . '" alt="" width="28" height="28" class="fea-avatar" loading="lazy">'
        . '<span class="fea-card-author">' . esc_html($author_name) . '</span>'
        . '</div>'
        . '<h3 class="fea-card-title"><a href="' . esc_url($url) . '">' . esc_html($title) . '</a></h3>'
        . '</article>';
}

// ── Shortcode: [fea_carta_semana_hero] ────────────────────────────────────
add_shortcode('fea_carta_semana_hero', function() {
    $cartas = get_posts([
        'posts_per_page' => 1,
        'category__in'   => [6],
        'post_status'    => 'publish',
        'orderby'        => 'date',
        'order'          => 'DESC',
    ]);
    if (!$cartas) return '';

    $c           = $cartas[0];
    $url         = get_permalink($c->ID);
    $fecha       = date_i18n('j \d\e F \d\e Y', strtotime($c->post_date));
    $author_name = get_the_author_meta('display_name', $c->post_author);
    $avatar_url  = get_avatar_url($c->post_author, ['size' => 32, 'default' => 'identicon']);

    return '<section class="fea-hero">'
        . '<a href="' . esc_url($url) . '" class="fea-hero-link">'
        . '<span class="fea-section-label">Carta de la semana</span>'
        . '<h2 class="fea-hero-title">' . esc_html(fea_title($c->post_title)) . '</h2>'
        . '<div class="fea-hero-meta">'
        . '<img src="' . esc_url($avatar_url) . '" alt="" width="32" height="32" class="fea-avatar">'
        . '<span>' . esc_html($author_name) . ' · ' . $fecha . '</span>'
        . '</div>'
        . '</a></section>';
});

// ── Shortcode: [fea_articulos_semana] ─────────────────────────────────────
add_shortcode('fea_articulos_semana', function($atts) {
    $atts  = shortcode_atts(['titulo' => 'Artículos de esta semana'], $atts);
    $page  = (int) get_option('page_on_front');

    // Selección editorial (ACF) — solo posts publicados, ordenados por fecha desc
    $posts = [];
    if (function_exists('get_field')) {
        $seleccion = get_field('portada_articulos', $page) ?: [];
        foreach ($seleccion as $p) {
            if ($p->post_status === 'publish') $posts[] = $p;
        }
    }

    // Fallback: últimos artículos si no hay selección
    if (empty($posts)) {
        $posts = get_posts([
            'posts_per_page'   => 9,
            'category__in'     => [1650],
            'category__not_in' => [6, 21, 22, 23, 26, 58, 40, 1645, 1646, 1647, 1648, 1649, 1651, 1652],
            'post_status'      => 'publish',
            'orderby'          => 'date',
            'order'            => 'DESC',
        ]);
    }
    if (!$posts) return '';

    $html = '<section class="fea-section">'
          . '<h2 class="fea-section-title">' . esc_html($atts['titulo']) . '</h2>'
          . '<div class="fea-grid">';
    foreach ($posts as $post) $html .= fea_card($post);
    return $html . '</div></section>';
});

// ── Shortcode: [fea_evangelio] ────────────────────────────────────────────
// Editorial (cat 1646) primero, luego comentarios (cat 1647). Máx 7 en total.
add_shortcode('fea_evangelio', function($atts) {
    $atts = shortcode_atts(['titulo' => 'Comentarios al evangelio'], $atts);

    $editorial = get_posts([
        'posts_per_page' => 1,
        'category__in'   => [1646],
        'post_status'    => 'publish',
        'orderby'        => 'date',
        'order'          => 'DESC',
    ]);

    $comentarios = get_posts([
        'posts_per_page'   => 6,
        'category__in'     => [1647],
        'category__not_in' => [1646],
        'post_status'      => 'publish',
        'orderby'          => 'date',
        'order'            => 'DESC',
    ]);

    $posts = array_merge($editorial, $comentarios);
    if (!$posts) return '';

    $html = '<section class="fea-section">'
          . '<h2 class="fea-section-title">' . esc_html($atts['titulo']) . '</h2>'
          . '<div class="fea-grid">';
    foreach ($posts as $post) $html .= fea_card($post);
    return $html . '</div></section>';
});

// ── Shortcode: [fea_eucaristia] ───────────────────────────────────────────
add_shortcode('fea_eucaristia', function($atts) {
    $atts  = shortcode_atts(['titulo' => 'Para una eucaristía más participativa'], $atts);

    $posts = get_posts([
        'posts_per_page' => 6,
        'category__in'   => [1648],
        'post_status'    => 'publish',
        'orderby'        => 'date',
        'order'          => 'DESC',
    ]);
    if (!$posts) return '';

    $html = '<section class="fea-section">'
          . '<h2 class="fea-section-title">' . esc_html($atts['titulo']) . '</h2>'
          . '<div class="fea-grid">';
    foreach ($posts as $post) $html .= fea_card($post);
    return $html . '</div></section>';
});

// ── Shortcode: [fea_multimedia] ───────────────────────────────────────────
add_shortcode('fea_multimedia', function($atts) {
    $atts  = shortcode_atts(['titulo' => 'Multimedia'], $atts);
    $page  = (int) get_option('page_on_front');

    $posts = [];
    if (function_exists('get_field')) {
        $seleccion = get_field('portada_multimedia', $page) ?: [];
        foreach ($seleccion as $p) {
            if ($p->post_status === 'publish') $posts[] = $p;
        }
    }

    if (empty($posts)) {
        $posts = get_posts([
            'posts_per_page' => 4,
            'category__in'   => [1649, 26, 58],
            'post_status'    => 'publish',
            'orderby'        => 'date',
            'order'          => 'DESC',
        ]);
    }
    if (!$posts) return '';

    $html = '<section class="fea-section">'
          . '<h2 class="fea-section-title">' . esc_html($atts['titulo']) . '</h2>'
          . '<div class="fea-grid">';
    foreach ($posts as $post) $html .= fea_card($post);
    return $html . '</div></section>';
});

// ── Reescribir links internos al idioma activo (Polylang) ─────────────────
add_filter('the_content', function($content) {
    if (!function_exists('pll_current_language') || !function_exists('pll_get_post')) return $content;
    $lang = pll_current_language();
    if (!$lang || $lang === 'es') return $content;

    return preg_replace_callback(
        '/<a\s([^>]*\s)?href=["\']([^"\']+)["\']([^>]*)>/i',
        function($m) use ($lang) {
            $href = $m[2];
            $home = home_url();
            if (strpos($href, $home) === false) return $m[0];

            $post_id = url_to_postid($href);
            if (!$post_id) return $m[0];

            $translated_id = pll_get_post($post_id, $lang);
            if (!$translated_id || $translated_id === $post_id) return $m[0];

            $new_url = get_permalink($translated_id);
            if (!$new_url) return $m[0];

            return str_replace($href, $new_url, $m[0]);
        },
        $content
    );
}, 20);
