<?php
/**
 * Enqueue child styles.
 */
function child_enqueue_styles() {
    wp_enqueue_style( 'child-theme', get_stylesheet_directory_uri() . '/style.css', array(), 100 );
}

add_action( 'wp_enqueue_scripts', 'child_enqueue_styles' );

/**
 * Enqueue hero animation assets.
 */
function kadence_child_hero_animation_assets() {
    // Enqueue hero animation CSS
    wp_enqueue_style( 
        'hero-animation-style', 
        get_stylesheet_directory_uri() . '/assets/css/hero-animation.css', 
        array(), 
        '1.1.0' 
    );
    
    // Enqueue hero animation JS
    wp_enqueue_script( 
        'hero-animation-script', 
        get_stylesheet_directory_uri() . '/assets/js/hero-animation.js', 
        array(), 
        '1.1.0', 
        true 
    );
}

add_action( 'wp_enqueue_scripts', 'kadence_child_hero_animation_assets' );



// Custom inline search bar
function kadence_child_inline_search() {
    ob_start();
    ?>
    <div class="kc-inline-search-wrap">
        <button class="kc-search-toggle" aria-label="Toggle Search" type="button">
            <svg class="kc-search-icon" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <circle cx="11" cy="11" r="8"></circle>
                <path d="m21 21-4.35-4.35"></path>
            </svg>
        </button>
        <div class="kc-search-form-wrap">
            <form role="search" method="get" class="kc-search-form" action="<?php echo esc_url( home_url( '/' ) ); ?>">
                <input type="search" class="kc-search-field" placeholder="<?php echo esc_attr__( 'Search...', 'kadence' ); ?>" value="<?php echo get_search_query(); ?>" name="s" />
                <button type="submit" class="kc-search-submit">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <circle cx="11" cy="11" r="8"></circle>
                        <path d="m21 21-4.35-4.35"></path>
                    </svg>
                </button>
            </form>
        </div>
    </div>
    <?php
    return ob_get_clean();
}

// Register shortcode
add_shortcode( 'kc_inline_search', 'kadence_child_inline_search' );

// Enqueue custom scripts and styles
function kadence_child_search_scripts() {
    wp_enqueue_script( 'kadence-child-search', get_stylesheet_directory_uri() . '/inline-search.js', array('jquery'), '1.0.1', true );
}
add_action( 'wp_enqueue_scripts', 'kadence_child_search_scripts' );

// Resource Filter Shortcode
function bw_resource_filter_shortcode($atts) {
    // Shortcode attributes
    $atts = shortcode_atts(array(
        'hide_selector' => '.bw_manual_block', // Hide elements with this class
        'posts_per_page' => 10,
    ), $atts);
    
    ob_start();
    ?>
    <style>
    .bw-resource-filter-container .bw-filter-row {
        display: flex !important;
        flex-direction: row !important;
        align-items: center !important;
        gap: 20px !important;
        flex-wrap: wrap !important;
    }
    .bw-resource-filter-container .bw-filter-row > * {
        display: inline-block !important;
        vertical-align: middle !important;
    }
    </style>
    <div class="bw-resource-filter-container" data-hide-selector="<?php echo esc_attr($atts['hide_selector']); ?>" data-posts-per-page="<?php echo esc_attr($atts['posts_per_page']); ?>">
        <div class="bw-filter-row">
            <div class="bw-filter-label">Filter by</div>
            
            <div class="bw-filter-item">
                <label for="bw-topic-filter">Topic</label>
                <select id="bw-topic-filter" class="bw-filter-select" data-filter-type="category">
                    <option value="">Select</option>
                    <?php
                    $categories = get_categories(array('hide_empty' => true));
                    foreach($categories as $category) {
                        echo '<option value="' . esc_attr($category->slug) . '" data-cat-id="' . esc_attr($category->term_id) . '">' . esc_html($category->name) . '</option>';
                    }
                    ?>
                </select>
            </div>
            
            <div class="bw-filter-item">
                <label for="bw-service-filter">Service</label>
                <select id="bw-service-filter" class="bw-filter-select" data-filter-type="service">
                    <option value="">Select</option>
                    <?php
                    $services = get_terms(array(
                        'taxonomy' => 'service',
                        'hide_empty' => true
                    ));
                    if (!is_wp_error($services)) {
                        foreach($services as $service) {
                            echo '<option value="' . esc_attr($service->slug) . '">' . esc_html($service->name) . '</option>';
                        }
                    }
                    ?>
                </select>
            </div>
            
            <div class="bw-filter-item">
                <label for="bw-resource-type-filter">Resource Type</label>
                <select id="bw-resource-type-filter" class="bw-filter-select" data-filter-type="resource_type">
                    <option value="">Select</option>
                    <?php
                    $resource_types = get_terms(array(
                        'taxonomy' => 'resource_type',
                        'hide_empty' => true
                    ));
                    if (!is_wp_error($resource_types)) {
                        foreach($resource_types as $resource_type) {
                            echo '<option value="' . esc_attr($resource_type->slug) . '">' . esc_html($resource_type->name) . '</option>';
                        }
                    }
                    ?>
                </select>
            </div>
            
            <div class="bw-filter-item">
                <label for="bw-search-filter">Search</label>
                <div class="bw-search-wrapper">
                    <input type="text" id="bw-search-filter" class="bw-filter-search" placeholder="Search">
                    <button type="button" class="bw-search-button">
                        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <circle cx="11" cy="11" r="8"></circle>
                            <path d="m21 21-4.35-4.35"></path>
                        </svg>
                    </button>
                </div>
            </div>
            
            <div class="bw-filter-item">
                <button type="button" id="bw-reset-filters" class="bw-reset-button">Reset Filters</button>
            </div>
        </div>
        
        <div id="bw-filtered-results" class="bw-filtered-results" style="display: none;">
            <!-- Filtered results will be displayed here via AJAX -->
        </div>
    </div>
    <?php
    return ob_get_clean();
}
add_shortcode('bw_resource_filter', 'bw_resource_filter_shortcode');

// Enqueue resource filter scripts and styles
function bw_resource_filter_assets() {
    wp_enqueue_style('bw-resource-filter', get_stylesheet_directory_uri() . '/assets/css/resource-filter.css', array(), '1.1.0');
    wp_enqueue_script('bw-resource-filter', get_stylesheet_directory_uri() . '/assets/js/resource-filter.js', array('jquery'), '1.1.0', true);
    
    // Localize script for AJAX
    wp_localize_script('bw-resource-filter', 'bw_ajax', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('bw_resource_filter_nonce')
    ));
}
add_action('wp_enqueue_scripts', 'bw_resource_filter_assets');

// AJAX handler for filtering resources
function bw_filter_resources() {
    if (is_user_logged_in()) {
    check_ajax_referer('bw_resource_filter_nonce', 'nonce');
}
    
    $topic = isset($_POST['topic']) ? sanitize_text_field($_POST['topic']) : '';
    $service = isset($_POST['service']) ? sanitize_text_field($_POST['service']) : '';
    $resource_type = isset($_POST['resource_type']) ? sanitize_text_field($_POST['resource_type']) : '';
    $search = isset($_POST['search']) ? sanitize_text_field($_POST['search']) : '';
    $posts_per_page = isset($_POST['posts_per_page']) ? intval($_POST['posts_per_page']) : 10;
    
    // Debug logging
    error_log('BW Filter - Topic: ' . $topic);
    error_log('BW Filter - Service: ' . $service);
    error_log('BW Filter - Resource Type: ' . $resource_type);
    
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => $posts_per_page,
        'post_status' => 'publish',
    );
    
    // Add taxonomy queries
    $tax_query = array();
    
    if (!empty($topic)) {
        // Try to get category by slug first, then by name
        $category = get_category_by_slug($topic);
        if (!$category) {
            // Try to find by name
            $categories = get_categories(array('name' => $topic));
            if (!empty($categories)) {
                $category = $categories[0];
            }
        }
        
        $tax_query[] = array(
            'taxonomy' => 'category',
            'field' => 'slug',
            'terms' => $topic,
            'operator' => 'IN'
        );
    }
    
    if (!empty($service)) {
        $tax_query[] = array(
            'taxonomy' => 'service',
            'field' => 'slug',
            'terms' => $service
        );
    }
    
    if (!empty($resource_type)) {
        $tax_query[] = array(
            'taxonomy' => 'resource_type',
            'field' => 'slug',
            'terms' => $resource_type
        );
    }
    
    if (!empty($tax_query)) {
        $tax_query['relation'] = 'AND'; // Ensure AND relation for multiple taxonomies
        $args['tax_query'] = $tax_query;
    }
    
    // Add search query
    if (!empty($search)) {
        $args['s'] = $search;
    }
    
    // Debug the final query args
    error_log('BW Filter - Query Args: ' . print_r($args, true));
    
    $query = new WP_Query($args);
    
    // Debug query results
    error_log('BW Filter - Found posts: ' . $query->found_posts);
    error_log('BW Filter - SQL: ' . $query->request);
    
    ob_start();
    
    // Always show debug info in response
    echo '<!-- Debug: Topic=' . $topic . ', Service=' . $service . ', ResourceType=' . $resource_type . ', Search=' . $search . ' -->';
    
    if ($query->have_posts()) {
        echo '<div class="bw-resource-info">Found ' . $query->found_posts . ' resource(s)</div>';
        echo '<div class="bw-resource-list">';
        while ($query->have_posts()) {
            $query->the_post();
            $post_thumbnail_url = get_the_post_thumbnail_url(get_the_ID(), 'medium');
            ?>
            <article class="bw-resource-item">
                <div class="bw-resource-row">
                    <?php if ($post_thumbnail_url) : ?>
                        <div class="bw-resource-image">
                            <a href="<?php the_permalink(); ?>">
                                <img src="<?php echo esc_url($post_thumbnail_url); ?>" alt="<?php the_title_attribute(); ?>">
                            </a>
                        </div>
                    <?php endif; ?>
                    
                    <div class="bw-resource-content <?php echo $post_thumbnail_url ? '' : 'no-image'; ?>">
                        <h3 class="bw-resource-title">
                            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                        </h3>
                        
                        <div class="bw-resource-meta">
                            <span class="bw-meta-date"><?php echo get_the_date(); ?></span>
                            <span class="bw-meta-separator">•</span>
                            <span class="bw-meta-author">by <?php the_author(); ?></span>
                        </div>
                        
                        <div class="bw-resource-excerpt">
                            <?php echo wp_trim_words(get_the_excerpt(), 20); ?>
                        </div>
                        
                        <a href="<?php the_permalink(); ?>" class="bw-read-more">Read More</a>
                    </div>
                </div>
            </article>
            <?php
        }
        echo '</div>';
    } else {
        echo '<p class="bw-no-results">No resources found matching your filters.</p>';
    }
    
    wp_reset_postdata();
    
    $output = ob_get_clean();
    wp_send_json_success($output);
}
add_action('wp_ajax_bw_filter_resources', 'bw_filter_resources');
add_action('wp_ajax_nopriv_bw_filter_resources', 'bw_filter_resources');



/**
 * Add Resource Type and Service taxonomy columns to Posts list table.
 */
add_filter( 'manage_post_posts_columns', 'aisv_add_custom_taxonomy_columns' );
add_action( 'manage_post_posts_custom_column', 'aisv_render_custom_taxonomy_columns', 10, 2 );

/**
 * Register new columns for Resource Type and Service on the Posts admin list.
 *
 * @param array $columns Existing columns.
 * @return array
 */
function aisv_add_custom_taxonomy_columns( $columns ) {

	// Choose where to insert the new columns (after Categories, before Tags).
	$new_columns = array();

	foreach ( $columns as $key => $label ) {
		$new_columns[ $key ] = $label;

		if ( 'categories' === $key ) {
			if ( taxonomy_exists( 'resource_type' ) ) {
				$new_columns['resource_type'] = __( 'Resource Type', 'kadence-child' );
			}
			if ( taxonomy_exists( 'service' ) ) {
				$new_columns['service'] = __( 'Service', 'kadence-child' );
			}
		}
	}

	return $new_columns;
}

/**
 * Render the content for the custom taxonomy columns.
 *
 * @param string $column  Column key.
 * @param int    $post_id Post ID.
 */
function aisv_render_custom_taxonomy_columns( $column, $post_id ) {

	if ( 'resource_type' === $column ) {
		if ( taxonomy_exists( 'resource_type' ) ) {
			$terms = get_the_term_list( $post_id, 'resource_type', '', ', ', '' );
			echo $terms ? $terms : '—';
		} else {
			echo '—';
		}
	}

	if ( 'service' === $column ) {
		if ( taxonomy_exists( 'service' ) ) {
			$terms = get_the_term_list( $post_id, 'service', '', ', ', '' );
			echo $terms ? $terms : '—';
		} else {
			echo '—';
		}
	}
}

/* Enable auto-updates of plugins/themes on Flywheel */
add_action(
    'wp_update_plugins',
    function() {
        if (wp_doing_cron() && ! doing_action('wp_maybe_auto_update')) {
            do_action('wp_maybe_auto_update');
        }
    },
    20
);