<?php
/**
 * MPC-MA Theme Functions
 */

if ( ! defined( 'ABSPATH' ) ) exit;

define( 'MPCMA_VERSION', '1.0.0' );

/* ── SETUP ── */
function mpcma_setup() {
    load_theme_textdomain( 'mpcma', get_template_directory() . '/languages' );
    add_theme_support( 'title-tag' );
    add_theme_support( 'post-thumbnails' );
    add_theme_support( 'html5', [ 'search-form', 'comment-form', 'comment-list', 'gallery', 'caption' ] );
    add_theme_support( 'custom-logo', [
        'height'      => 64,
        'width'       => 64,
        'flex-width'  => true,
        'flex-height' => true,
    ] );
    add_image_size( 'noticia-thumb', 600, 400, true );
    add_image_size( 'noticia-lista', 300, 200, true );

    register_nav_menus( [
        'primary' => __( 'Menu Principal', 'mpcma' ),
        'footer'  => __( 'Menu Rodapé', 'mpcma' ),
    ] );
}
add_action( 'after_setup_theme', 'mpcma_setup' );

/* ── ESTILOS & SCRIPTS ── */
function mpcma_enqueue() {
   wp_enqueue_style(
    'google-fonts',
    'https://fonts.googleapis.com/css2?family=Playfair+Display:ital,wght@0,400;0,600;0,700;1,400;1,700&family=Source+Sans+3:wght@300;400;600;700&display=swap',
    [],
    null
);
    wp_enqueue_style(
        'mpcma-main',
        get_template_directory_uri() . '/assets/css/main.css',
        [ 'google-fonts' ],
        MPCMA_VERSION
    );
    wp_enqueue_script(
        'mpcma-main',
        get_template_directory_uri() . '/assets/js/main.js',
        [],
        MPCMA_VERSION,
        true
    );
}
add_action( 'wp_enqueue_scripts', 'mpcma_enqueue' );

/* ── WIDGETS ── */
function mpcma_widgets_init() {
    register_sidebar( [
        'name'          => __( 'Sidebar', 'mpcma' ),
        'id'            => 'sidebar-1',
        'before_widget' => '<div class="widget">',
        'after_widget'  => '</div>',
        'before_title'  => '<h3 class="widget-title">',
        'after_title'   => '</h3>',
    ] );
    register_sidebar( [
        'name'          => __( 'Rodapé – Links Úteis', 'mpcma' ),
        'id'            => 'footer-links',
        'before_widget' => '',
        'after_widget'  => '',
        'before_title'  => '',
        'after_title'   => '',
    ] );
}
add_action( 'widgets_init', 'mpcma_widgets_init' );

/* ── OPÇÕES DO TEMA (Customizer) ── */
function mpcma_customize_register( $wp_customize ) {

    /* Seção: Informações do Rodapé */
    $wp_customize->add_section( 'mpcma_footer', [
        'title'    => __( 'Rodapé – Informações', 'mpcma' ),
        'priority' => 120,
    ] );

    $footer_fields = [
        'mpcma_endereco'  => [ 'label' => 'Endereço',   'default' => 'Av. Carlos Cunha S/Nº Jaracaty. São Luis-MA. CEP: 65076-820' ],
        'mpcma_telefone'  => [ 'label' => 'Telefone',   'default' => '(98) 2016-6000' ],
        'mpcma_email'     => [ 'label' => 'E-mail',     'default' => 'mpc@tcema.tc.br' ],
        'mpcma_instagram' => [ 'label' => 'Instagram URL', 'default' => '#' ],
        'mpcma_facebook'  => [ 'label' => 'Facebook URL',  'default' => '#' ],
        'mpcma_youtube'   => [ 'label' => 'YouTube URL',   'default' => '#' ],
    ];

    foreach ( $footer_fields as $key => $args ) {
        $wp_customize->add_setting( $key, [ 'default' => $args['default'], 'sanitize_callback' => 'sanitize_text_field' ] );
        $wp_customize->add_control( $key, [ 'label' => $args['label'], 'section' => 'mpcma_footer', 'type' => 'text' ] );
    }

    /* Seção: Links Úteis (sidebar) */
    $wp_customize->add_section( 'mpcma_links_uteis', [
        'title'    => __( 'Links Úteis', 'mpcma' ),
        'priority' => 130,
    ] );

    for ( $i = 1; $i <= 5; $i++ ) {
        $wp_customize->add_setting( "mpcma_link_label_{$i}", [ 'default' => '', 'sanitize_callback' => 'sanitize_text_field' ] );
        $wp_customize->add_control( "mpcma_link_label_{$i}", [ 'label' => "Link {$i} – Texto", 'section' => 'mpcma_links_uteis', 'type' => 'text' ] );
        $wp_customize->add_setting( "mpcma_link_url_{$i}", [ 'default' => '#', 'sanitize_callback' => 'esc_url_raw' ] );
        $wp_customize->add_control( "mpcma_link_url_{$i}", [ 'label' => "Link {$i} – URL", 'section' => 'mpcma_links_uteis', 'type' => 'url' ] );
    }

    /* Seção: Hero */
    $wp_customize->add_section( 'mpcma_hero', [
        'title'    => __( 'Hero (Página Inicial)', 'mpcma' ),
        'priority' => 110,
    ] );

    $wp_customize->add_setting( 'mpcma_hero_titulo', [ 'default' => 'Ministério Público de Contas do Estado do Maranhão', 'sanitize_callback' => 'sanitize_text_field' ] );
    $wp_customize->add_control( 'mpcma_hero_titulo', [ 'label' => 'Título do Hero', 'section' => 'mpcma_hero', 'type' => 'text' ] );

    $wp_customize->add_setting( 'mpcma_hero_subtitulo', [ 'default' => 'Atuação em defesa da legalidade, da transparência e da boa gestão pública.', 'sanitize_callback' => 'sanitize_text_field' ] );
    $wp_customize->add_control( 'mpcma_hero_subtitulo', [ 'label' => 'Subtítulo do Hero', 'section' => 'mpcma_hero', 'type' => 'textarea' ] );

    $wp_customize->add_setting( 'mpcma_hero_btn_texto', [ 'default' => 'CONHEÇA O MPC-MA', 'sanitize_callback' => 'sanitize_text_field' ] );
    $wp_customize->add_control( 'mpcma_hero_btn_texto', [ 'label' => 'Texto do Botão', 'section' => 'mpcma_hero', 'type' => 'text' ] );

    $wp_customize->add_setting( 'mpcma_hero_btn_url', [ 'default' => '/institucional', 'sanitize_callback' => 'esc_url_raw' ] );
    $wp_customize->add_control( 'mpcma_hero_btn_url', [ 'label' => 'URL do Botão', 'section' => 'mpcma_hero', 'type' => 'url' ] );

    $wp_customize->add_setting( 'mpcma_hero_bg', [ 'default' => '', 'sanitize_callback' => 'esc_url_raw' ] );
    $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'mpcma_hero_bg', [
        'label'   => 'Imagem de Fundo do Hero',
        'section' => 'mpcma_hero',
    ] ) );
}
add_action( 'customize_register', 'mpcma_customize_register' );

/* ── HELPER: get_theme_opt ── */
function mpcma_opt( $key, $default = '' ) {
    return get_theme_mod( $key, $default );
}

/* ── EXCERPT LENGTH ── */
function mpcma_excerpt_length( $length ) { return 30; }
add_filter( 'excerpt_length', 'mpcma_excerpt_length' );

function mpcma_excerpt_more( $more ) { return '...'; }
add_filter( 'excerpt_more', 'mpcma_excerpt_more' );

/* ── CUSTOM POST TYPE: PARECERES ── */
function mpcma_register_cpts() {
    register_post_type( 'parecer', [
        'labels' => [
            'name'          => 'Pareceres',
            'singular_name' => 'Parecer',
            'add_new_item'  => 'Adicionar Parecer',
            'edit_item'     => 'Editar Parecer',
        ],
        'public'       => true,
        'has_archive'  => true,
        'rewrite'      => [ 'slug' => 'pareceres' ],
        'menu_icon'    => 'dashicons-media-document',
        'supports'     => [ 'title', 'editor', 'thumbnail', 'custom-fields' ],
        'show_in_rest' => true,
    ] );

    register_post_type( 'ato_normativo', [
        'labels' => [
            'name'          => 'Atos Normativos',
            'singular_name' => 'Ato Normativo',
            'add_new_item'  => 'Adicionar Ato Normativo',
            'edit_item'     => 'Editar Ato Normativo',
        ],
        'public'       => true,
        'has_archive'  => true,
        'rewrite'      => [ 'slug' => 'atos-normativos' ],
        'menu_icon'    => 'dashicons-book-alt',
        'supports'     => [ 'title', 'editor', 'thumbnail', 'custom-fields' ],
        'show_in_rest' => true,
        'taxonomies'   => [ 'tipo_ato' ],
    ] );

    /* Taxonomia para Atos Normativos */
    register_taxonomy( 'tipo_ato', 'ato_normativo', [
        'labels' => [
            'name'          => 'Tipos de Ato',
            'singular_name' => 'Tipo de Ato',
        ],
        'hierarchical'  => true,
        'rewrite'       => [ 'slug' => 'tipo-ato' ],
        'show_in_rest'  => true,
    ] );

    /* Membro (CPT simples) */
    register_post_type( 'membro', [
        'labels' => [
            'name'          => 'Membros',
            'singular_name' => 'Membro',
        ],
        'public'      => false,
        'show_ui'     => true,
        'menu_icon'   => 'dashicons-id',
        'supports'    => [ 'title', 'thumbnail', 'custom-fields' ],
        'show_in_rest' => true,
    ] );
}
add_action( 'init', 'mpcma_register_cpts' );

/* ── FLUSH REWRITE RULES na ativação ── */
function mpcma_rewrite_flush() { flush_rewrite_rules(); }
register_activation_hook( __FILE__, 'mpcma_rewrite_flush' );

/* ── BUSCA EM CUSTOM FIELDS ── */
function mpcma_search_custom_fields( $query ) {
    if ( ! is_admin() && $query->is_search() && $query->is_main_query() ) {
        $post_type = isset( $_GET['post_type'] ) ? sanitize_text_field( $_GET['post_type'] ) : '';
        $search_term = $query->get('s');
        if ( in_array( $post_type, [ 'parecer', 'ato_normativo' ] ) && ! empty( $search_term ) ) {
            $query->set( 'post_type', $post_type );
            $query->set( 's', '' );
            $query->set( 'meta_query', [
                'relation' => 'OR',
                [
                    'key'     => 'numero_processo',
                    'value'   => $search_term,
                    'compare' => 'LIKE',
                ],
                [
                    'key'     => 'assunto',
                    'value'   => $search_term,
                    'compare' => 'LIKE',
                ],
                [
                    'key'     => 'arquivo_url',
                    'value'   => $search_term,
                    'compare' => 'LIKE',
                ],
            ] );
        }
    }
}
add_action( 'pre_get_posts', 'mpcma_search_custom_fields' );
