<?php
/**
 * BASE-THEME: BANNER MANAGER
 * Inclua no functions.php: require_once get_template_directory() . '/inc/banner-manager.php';
 */
if ( ! defined( 'ABSPATH' ) ) { exit; }

/**
 * Configurações de posições de banner.
 * Adicione/edite posições aqui. O resto do sistema se atualiza automaticamente.
 */
define( 'CULT_BANNER_POSITIONS', [
	'home-top'      => [
		'label'  => __( 'Header da home', 'base-theme' ),
		'width'  => 728,
		'height' => 90,
	],
	'sidebar'       => [
		'label'  => __( 'Barra lateral', 'base-theme' ),
		'width'  => 300,
		'height' => 250,
	],
	'footer'        => [
		'label'  => __( 'Rodapé do site', 'base-theme' ),
		'width'  => 300,
		'height' => 50,
	],
	'content-mid'   => [
		'label'  => __( 'Meio do conteúdo', 'base-theme' ),
		'width'  => 300,
		'height' => 250,
	],
	'featured-week' => [
		'label'  => __( 'Destaque da semana', 'base-theme' ),
		'width'  => 1200,
		'height' => 400,
	],
] );

/**
 * Retorna configurações de uma posição de banner.
 * @param string $position_id Ex: 'home-top'
 * @return array|null ['label'=>..., 'width'=>..., 'height'=>...] ou null
 */
function culturando_get_banner_position( $position_id ) {
	$positions = defined( 'CULT_BANNER_POSITIONS' ) ? CULT_BANNER_POSITIONS : [];
	return $positions[ $position_id ] ?? null;
}

// ==========================================
// 1. CUSTOM POST TYPE
// ==========================================
function culturando_banner_cpt() {
	register_post_type( 'banner', array(
		'labels'             => array(
			'name'          => __( 'Banners', 'culturando' ),
			'singular_name' => __( 'Banner', 'culturando' ),
			'add_new'       => __( 'Adicionar novo', 'culturando' ),
			'add_new_item'  => __( 'Adicionar banner', 'culturando' ),
			'edit_item'     => __( 'Editar banner', 'culturando' ),
			'view_item'     => __( 'Ver banner', 'culturando' ),
		),
		'public'             => true,
		'show_ui'            => true,
		'show_in_menu'       => true,
		'menu_position'      => 25,
		'menu_icon'          => 'dashicons-format-image',
		'supports'           => array( 'title', 'editor', 'thumbnail' ),
		'has_archive'        => false,
		'show_in_rest'       => false,
		'rewrite'            => array( 'slug' => 'banner', 'with_front' => false ),
	) );
}
add_action( 'init', 'culturando_banner_cpt' );

// ==========================================
// 2. META BOXES & SALVAMENTO
// ==========================================
function culturando_banner_add_meta_boxes() {
	add_meta_box( 'banner_data', __( 'Configurações do Banner', 'culturando' ), 'culturando_banner_meta_box_html', 'banner', 'advanced', 'high' );
}
add_action( 'add_meta_boxes', 'culturando_banner_add_meta_boxes' );

function culturando_banner_meta_box_html( $post ) {
	wp_nonce_field( 'culturando_banner_nonce', 'culturando_banner_nonce' );
	$url      = get_post_meta( $post->ID, 'banner_url', true );
	$position = get_post_meta( $post->ID, 'banner_position', true );
	$start    = get_post_meta( $post->ID, 'banner_start_date', true );
	$end      = get_post_meta( $post->ID, 'banner_end_date', true );
	$target   = get_post_meta( $post->ID, 'banner_target', true ) ?: '_blank';
	$clicks   = (int) get_post_meta( $post->ID, 'banner_clicks', true );
	?>
	<p>
        <label for="banner_url"><?php esc_html_e( 'URL de destino:', 'culturando' ); ?></label>
	    <input type="url" id="banner_url" name="banner_url" value="<?php echo esc_url( $url ); ?>" class="widefat" required>
    </p>
	
	<p>
        <label><?php esc_html_e( 'Abrir link:', 'culturando' ); ?></label>
        <select name="banner_target" class="widefat">
            <option value="_self" <?php selected( $target, '_self' ); ?>>Na mesma aba</option>
            <option value="_blank" <?php selected( $target, '_blank' ); ?>>Nova aba</option>
        </select>
    </p>

    <p>
        <label for="banner_position"><?php esc_html_e( 'Posição no site:', 'base-theme' ); ?></label>
        <select id="banner_position" name="banner_position" class="widefat" required>
            <option value=""><?php esc_html_e( '— Selecione —', 'base-theme' ); ?></option>
            <?php 
            $positions = defined( 'CULT_BANNER_POSITIONS' ) ? CULT_BANNER_POSITIONS : [];
            foreach ( $positions as $pos_id => $pos_data ) : 
                $size_label = sprintf( '%d × %d px', $pos_data['width'], $pos_data['height'] );
                ?>
                <option value="<?php echo esc_attr( $pos_id ); ?>" <?php selected( $position, $pos_id ); ?>>
                    <?php echo esc_html( $pos_data['label'] . ' (' . $size_label . ')' ); ?>
                </option>
            <?php endforeach; ?>
        </select>
    </p>
	
	<p>
        <label><?php esc_html_e( 'Vigência:', 'culturando' ); ?></label><br>
        <input type="date" name="banner_start_date" value="<?php echo esc_attr( $start ); ?>"> <?php esc_html_e( 'até', 'culturando' ); ?>
        <input type="date" name="banner_end_date" value="<?php echo esc_attr( $end ); ?>">
    </p>
	
	<hr>
	<p>
        <strong><?php esc_html_e( 'Cliques:', 'culturando' ); ?></strong> <span id="banner_clicks_display"><?php echo esc_html( $clicks ); ?></span>
    </p>
	<p class="description">
        <?php esc_html_e( 'Atualizado automaticamente.', 'culturando' ); ?>
    </p>
	<?php
}

function culturando_banner_save_meta( $post_id ) {
	if ( ! isset( $_POST['culturando_banner_nonce'] ) || ! wp_verify_nonce( $_POST['culturando_banner_nonce'], 'culturando_banner_nonce' ) ) return;
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return;
	if ( ! current_user_can( 'edit_post', $post_id ) ) return;

	// 1. Campos comuns (URL, posição, target)
	$common_fields = array( 'banner_url', 'banner_position', 'banner_target' );
	foreach ( $common_fields as $field ) {
		if ( isset( $_POST[ $field ] ) ) {
			$val = sanitize_text_field( $_POST[ $field ] );
			if ( ! empty( $val ) ) {
				update_post_meta( $post_id, $field, $val );
			} else {
				delete_post_meta( $post_id, $field ); // Limpa se vazio
			}
		}
	}

	// 2. Campos de data (lógica especial para vigência flexível)
	$start = isset( $_POST['banner_start_date'] ) ? sanitize_text_field( $_POST['banner_start_date'] ) : '';
	$end   = isset( $_POST['banner_end_date'] )   ? sanitize_text_field( $_POST['banner_end_date'] )   : '';

	// Se preenchido → salva. Se vazio → DELETA do banco para o NOT EXISTS funcionar
	if ( ! empty( $start ) ) {
		update_post_meta( $post_id, 'banner_start_date', $start );
	} else {
		delete_post_meta( $post_id, 'banner_start_date' );
	}

	if ( ! empty( $end ) ) {
		update_post_meta( $post_id, 'banner_end_date', $end );
	} else {
		delete_post_meta( $post_id, 'banner_end_date' );
	}
}
add_action( 'save_post_banner', 'culturando_banner_save_meta' );

// ==========================================
// 3. COLUNAS NO ADMIN
// ==========================================
function culturando_banner_manage_columns( $columns ) {
	unset( $columns['date'] );
	return array_merge( $columns, array(
		'banner_position' => __( 'Posição', 'culturando' ),
		'banner_dates'    => __( 'Vigência', 'culturando' ),
		'banner_clicks'   => __( 'Cliques', 'culturando' ),
		'date'            => __( 'Publicado em', 'culturando' ),
	) );
}
add_filter( 'manage_banner_posts_columns', 'culturando_banner_manage_columns' );

function culturando_banner_custom_column( $column, $post_id ) {
	$pos   = get_post_meta( $post_id, 'banner_position', true );
	$start = get_post_meta( $post_id, 'banner_start_date', true );
	$end   = get_post_meta( $post_id, 'banner_end_date', true );
	$click = (int) get_post_meta( $post_id, 'banner_clicks', true );

	switch ( $column ) {
		case 'banner_position':
			echo esc_html( $pos ?: '-' );
			break;
		case 'banner_dates':
			echo $start ? esc_html( $start ) : '∞';
			echo ' / ';
			echo $end ? esc_html( $end ) : '∞';
			break;
		case 'banner_clicks':
			echo '<strong>' . esc_html( $click ) . '</strong>';
			break;
	}
}
add_action( 'manage_banner_posts_custom_column', 'culturando_banner_custom_column', 10, 2 );

add_filter( 'manage_edit-banner_sortable_columns', function( $cols ) {
	$cols['banner_clicks'] = 'banner_clicks';
	$cols['banner_dates']  = 'banner_end_date';
	return $cols;
} );

add_action( 'pre_get_posts', function( $query ) {
	if ( ! is_admin() || ! $query->is_main_query() || 'banner' !== $query->get( 'post_type' ) ) return;
	$orderby = $query->get( 'orderby' );
	if ( 'banner_clicks' === $orderby ) {
		$query->set( 'meta_key', 'banner_clicks' );
		$query->set( 'orderby', 'meta_value_num' );
	}
	if ( 'banner_end_date' === $orderby ) {
		$query->set( 'meta_key', 'banner_end_date' );
		$query->set( 'orderby', 'meta_value' );
	}
} );

// ==========================================
// 4. QUERY HELPER (FILTRO POR VIGÊNCIA)
// ==========================================
function culturando_get_active_banners( $position = '', $count = -1 ) {
    $now = current_time( 'mysql' );

    $args = array(
        'post_type'      => 'banner',
        'posts_per_page' => $count,
        'post_status'    => 'publish',
        'meta_key'       => 'banner_position',
        'meta_value'     => $position,
        'orderby'        => 'rand', // ou menu_order, date, etc.
        'meta_query'     => array(
            'relation' => 'AND',

            // Data inicial: se vazio → ignora. Se preenchido → deve ser <= agora
            array(
                'relation' => 'OR',
                array(
                    'key'     => '_banner_start',
                    'value'   => $now,
                    'compare' => '<=',
                    'type'    => 'DATETIME',
                ),
                array(
                    'key'     => '_banner_start',
                    'compare' => 'NOT EXISTS',
                ),
            ),

            // Data final: se vazio → ignora. Se preenchido → deve ser >= agora
            array(
                'relation' => 'OR',
                array(
                    'key'     => '_banner_end',
                    'value'   => $now,
                    'compare' => '>=',
                    'type'    => 'DATETIME',
                ),
                array(
                    'key'     => '_banner_end',
                    'compare' => 'NOT EXISTS',
                ),
            ),
        ),
    );
    return new WP_Query( $args );
}

// ==========================================
// 5. SHORTCODE & RENDERIZAÇÃO POR POSIÇÃO
// ==========================================
function culturando_banners_shortcode( $atts ) {
	$atts = shortcode_atts( array(
		'position' => 'home-top',
		'count'    => 3,
	), $atts, 'banners' );

	// Valida a posição
	$positions = defined( 'CULT_BANNER_POSITIONS' ) ? CULT_BANNER_POSITIONS : [];
	if ( ! isset( $positions[ $atts['position'] ] ) ) {
		return ''; // Posição inválida
	}

	$size = $positions[ $atts['position'] ];

	$query = culturando_get_active_banners( $atts['position'], $atts['count'] );
	if ( ! $query->have_posts() ) return '';

	$output = '';
	while ( $query->have_posts() ) {
		$query->the_post();
		$id      = get_the_ID();
		$url     = esc_url( get_post_meta( $id, 'banner_url', true ) );
		$target  = esc_attr( get_post_meta( $id, 'banner_target', true ) ) ?: '_blank';
		$title   = get_the_title();
		$thumb   = has_post_thumbnail( $id ) ? get_the_post_thumbnail_url( $id, 'full' ) : '';
        $track = esc_url( home_url( '?cct=' . $id . '&r=' . base64_encode( $url ) ) );

		// Inline style baseado no array
		$inline_style = sprintf( 
			'max-width:%dpx; max-height:%dpx;', 
			$size['width'], 
			$size['height'] 
		);

		$html = '';
		switch ( $atts['position'] ) {
			case 'featured-week':
				$html  = '<div class="banner-featured" style="' . $inline_style . '">';
				$html .= '<a href="' . $track . '" target="' . $target . '" rel="noopener">';
                $content = wp_kses_post( get_the_content() );
                if ( $content ) {
                    $html .= '<div class="banner-featured-content">' . $content . '</div>';
                } else if ( $thumb ) {
					$html .= '<img src="' . esc_url( $thumb ) . '" alt="' . esc_attr( $title ) . '" loading="lazy" style="width:100%; height:100%; object-fit:cover;">';
				}
				$html .= '</a></div>';
				break;

			default:
				$pos_class = 'banner-' . esc_attr( $atts['position'] );
				$html  = '<div class="' . $pos_class . '" style="' . $inline_style . '">';
				$html .= '<a href="' . $track . '" target="' . $target . '" rel="noopener sponsored">';
				if ( $thumb ) {
					$html .= '<img src="' . esc_url( $thumb ) . '" alt="' . esc_attr( $title ) . '" loading="lazy" style="width:100%; height:100%; object-fit:cover;">';
				} else {
					$html .= '<span class="banner-fallback" style="width:100%; height:100%; display:flex; align-items:center; justify-content:center; background:#f1f5f9; color:#334155; border-radius:4px; font-size:14px;">' . esc_html( $title ) . '</span>';
				}
				$html .= '</a></div>';
		}
		$output .= apply_filters( 'base_theme_banner_html', $html, $id, $atts['position'] );
	}
	wp_reset_postdata();
	return $output;
}
add_shortcode( 'banners', 'culturando_banners_shortcode' );

// ==========================================
// 6. RASTREAMENTO DE CLIQUES
// ==========================================
// function culturando_track_banner_click() {
// 	if ( ! isset( $_GET['base_track_banner'], $_GET['dest'] ) ) return;

// 	$banner_id = absint( $_GET['base_track_banner'] );
// 	$dest      = esc_url_raw( $_GET['dest'] );

// 	if ( $banner_id && $dest && get_post_status( $banner_id ) === 'publish' ) {
// 		$clicks = (int) get_post_meta( $banner_id, 'banner_clicks', true );
// 		update_post_meta( $banner_id, 'banner_clicks', $clicks + 1 );
// 		wp_redirect( $dest, 302 );
// 		exit;
// 	}
// }
function culturando_track_banner_click() {
    // Usa os novos nomes de parâmetro
    if ( ! isset( $_GET['cct'], $_GET['r'] ) ) return;

    $banner_id = absint( $_GET['cct'] );
    
    // Decodifica base64 e valida
    $dest_raw = base64_decode( $_GET['r'], true );
    $dest     = $dest_raw ? esc_url_raw( $dest_raw ) : '';

    if ( $banner_id && $dest && get_post_status( $banner_id ) === 'publish' ) {
        // Registra clique
        $clicks = (int) get_post_meta( $banner_id, 'banner_clicks', true );
        update_post_meta( $banner_id, 'banner_clicks', $clicks + 1 );
        
        // Redireciona
        wp_redirect( $dest, 302 );
        exit;
    }
    
    // Fallback seguro
    wp_redirect( home_url(), 302 );
    exit;
}
add_action( 'template_redirect', 'culturando_track_banner_click', 1 );

// ==========================================
// 7. FLUSH REGRAS AO ATIVAR O TEMA
// ==========================================
function culturando_banner_flush_rules() {
	culturando_banner_cpt();
	flush_rewrite_rules();
}
add_action( 'after_switch_theme', 'culturando_banner_flush_rules' );

/**
 * Injeta CSS e JS inline apenas na tela de criação/edição de Banners
 */
add_action( 'admin_head', 'culturando_banner_inline_assets_css' );
add_action( 'admin_footer', 'culturando_banner_inline_assets_js' );

function culturando_banner_inline_assets_css() {
    $screen = get_current_screen();
    // Garante que estamos na tela certa (CPT banner + post.php ou post-new.php)
    if ( ! $screen || 'banner' !== $screen->post_type || ! in_array( $screen->base, [ 'post', 'post-new' ], true ) ) {
        return;
    }
    ?>
    <style>
        .post-type-banner #postdivrich { display: none; }
        .post-type-banner.show-editor #postdivrich { display: block; }
    </style>
    <?php
}

function culturando_banner_inline_assets_js() {
    $screen = get_current_screen();
    if ( ! $screen || 'banner' !== $screen->post_type || ! in_array( $screen->base, [ 'post', 'post-new' ], true ) ) {
        return;
    }
    ?>
    <script>
    jQuery(document).ready(function($) {
        var $select = $('#banner_position');
        var $body   = $('body');

        function toggleEditor() {
            var isFeatured = ($select.val() === 'featured-week');

            if (isFeatured) {
                $body.addClass('show-editor');

                // Delay para o CSS aplicar o display:block antes de redimensionar
                setTimeout(function() {
                    if (typeof tinymce !== 'undefined') {
                        $(window).trigger('resize');
                    }
                }, 100);

            } else {
                $body.removeClass('show-editor');
            }
        }

        toggleEditor();
        $select.on('change', toggleEditor);
    });
    </script>
    <?php
}