/*
 Theme Name:   Bricks Child Theme
 Theme URI:    https://bricksbuilder.io/
 Description:  Use this child theme to extend Bricks.
 Author:       Bricks
 Author URI:   https://bricksbuilder.io/
 Template:     bricks
 Version:      1.1
 Text Domain:  bricks
*/

/**
 * Rellena cualquier <h1> vacío del contenido con el título del post/página.
 * Aplica a TODO WordPress en vistas singulares (posts, pages, CPTs).
 */
function autofill_empty_h1_with_post_title($content) {
    // Evita afectar admin, feeds, AJAX/REST, o listados (solo en singular)
    if ( is_admin() || is_feed() || wp_doing_ajax() || (function_exists('wp_is_json_request') && wp_is_json_request()) ) {
        return $content;
    }
    if ( ! is_singular() ) {
        return $content;
    }

    $post = get_queried_object();
    if ( ! $post || empty($post->ID) ) {
        return $content;
    }

    $title = get_the_title($post->ID);
    if ( $title === '' ) {
        return $content;
    }

    // Patrón: <h1 ...>   </h1> (permite atributos y espacios/saltos dentro)
    $pattern = '/<h1\b[^>]*>\s*<\/h1>/i';

    // Reemplazo: <h1 ...>Título</h1> (sin copiar atributos; si prefieres conservarlos, ver variante abajo)
    $replacement = '<h1>' . esc_html($title) . '</h1>';

    // Reemplaza TODOS los H1 vacíos del contenido (cambia el  -1  a  1  si quieres solo el primero)
    $content = preg_replace($pattern, $replacement, $content, -1);

    return $content;
}
add_filter('the_content', 'autofill_empty_h1_with_post_title', 20);

/* ==============================
   CPT: Agenda + taxonomía
============================== */
add_action('init', function () {
  $labels = [
    'name'               => 'Agenda',
    'singular_name'      => 'Evento',
    'menu_name'          => 'Agenda',
    'name_admin_bar'     => 'Agenda',
    'add_new'            => 'Añadir evento',
    'add_new_item'       => 'Añadir nuevo evento',
    'edit_item'          => 'Editar evento',
    'new_item'           => 'Nuevo evento',
    'view_item'          => 'Ver evento',
    'view_items'         => 'Ver eventos',
    'search_items'       => 'Buscar eventos',
    'not_found'          => 'No se han encontrado eventos',
    'not_found_in_trash' => 'No hay eventos en la papelera',
    'all_items'          => 'Todos los eventos',
  ];

  register_post_type('agenda', [
    'labels'        => $labels,
    'public'        => true,
    'has_archive'   => true,
    'show_in_rest'  => true,
    'menu_icon'     => 'dashicons-calendar-alt',
    'rewrite'       => ['slug' => 'agenda'],
    'supports'      => ['title','editor','thumbnail','excerpt','custom-fields'],
  ]);

  register_taxonomy('tipo_evento', ['agenda'], [
    'label'        => 'Tipo de evento',
    'hierarchical' => true,
    'show_in_rest' => true,
    'rewrite'      => ['slug' => 'tipo-evento'],
  ]);
});

/* Columna "Fecha" en la lista de Agenda */
add_filter('manage_agenda_posts_columns', function($cols){
  $new = [];
  foreach ($cols as $k=>$v){
    if ($k==='date'){ $new['fecha_evento'] = 'Fecha'; }
    $new[$k] = $v;
  }
  return $new;
});
add_action('manage_agenda_posts_custom_column', function($col,$post_id){
  if ($col==='fecha_evento'){
    $d = get_post_meta($post_id,'fecha_evento',true);   // ACF (Ymd)
    $t = get_post_meta($post_id,'hora_inicio',true);
    if ($d){
      $dt = DateTime::createFromFormat('Ymd',$d);
      echo $dt ? $dt->format('d/m/Y') : $d;
      if ($t) echo ' · ' . esc_html($t);
    } else {
      echo '—';
    }
  }
},10,2);

/* Orden por fecha del evento en el admin (ASC) */
add_action('pre_get_posts', function($q){
  if (!is_admin() || !$q->is_main_query()) return;
  if ($q->get('post_type')==='agenda'){
    $q->set('meta_key','fecha_evento');
    $q->set('orderby','meta_value');
    $q->set('order','ASC');
  }
});

/* Archivo Agenda: próximos por defecto; ?ver=pasados para históricos */
add_action('pre_get_posts', function($q){
  if (is_admin() || !$q->is_main_query()) return;

  if (is_post_type_archive('agenda') || is_tax('tipo_evento')) {
    $hoy = current_time('Ymd');
    $ver = isset($_GET['ver']) ? sanitize_text_field($_GET['ver']) : 'proximos';

    $meta_query = [];

    if ($ver === 'pasados') {
      $meta_query[] = [
        'key'     => 'fecha_evento',
        'value'   => $hoy,
        'compare' => '<',
        'type'    => 'NUMERIC',
      ];
      $q->set('order','DESC');
    } else { // próximos
      $meta_query[] = [
        'key'     => 'fecha_evento',
        'value'   => $hoy,
        'compare' => '>=',
        'type'    => 'NUMERIC',
      ];
      $q->set('order','ASC');
    }

    $q->set('meta_key','fecha_evento');
    $q->set('orderby','meta_value');
    $q->set('meta_query',$meta_query);
    $q->set('posts_per_page', 12);
  }
});

// [fecha_evento id="" formato="d/m/Y"]
add_shortcode('fecha_evento', function($atts){
  $atts = shortcode_atts(['id'=>null,'formato'=>'d/m/Y'], $atts, 'fecha_evento');
  $post_id = $atts['id'] ? intval($atts['id']) : get_the_ID();
  $raw = get_post_meta($post_id,'fecha_evento',true);
  if (!$raw) return '';
  $dt = DateTime::createFromFormat('Ymd', $raw);
  return $dt ? esc_html($dt->format($atts['formato'])) : esc_html($raw);
});
