<?php
/**
 * Enqueue child styles and scripts.
 */
function child_enqueue_styles() {
    wp_enqueue_style('child-theme', get_stylesheet_directory_uri() . '/style.css', array(), '1.0.1');
    
    // Enqueue the scroll caret script
    wp_enqueue_script(
        'scroll-caret-js',
        get_stylesheet_directory_uri() . '/assets/js/scroll-caret.js',
        array('jquery'),
        '1.0.0',
        true
    );
}
add_action('wp_enqueue_scripts', 'child_enqueue_styles');

/**
 * Sync ACF thumbnail to featured image ONLY for media-clip type
 * For local-event, we'll handle differently
 */
function sync_acf_thumbnail_to_featured_image($post_id) {
    // Only process media-clip post type
    if (get_post_type($post_id) === 'media-clip') {
        // Get the image ID from your ACF field 'thumbnail_image'
        $image_id = get_field('thumbnail_image', $post_id, false);
        
        if (!empty($image_id)) {
            // Set the featured image to match your ACF field
            set_post_thumbnail($post_id, $image_id);
        } else {
            // If ACF image field is empty, remove the featured image
            delete_post_thumbnail($post_id);
        }
    }
}

function redirect_media_clip_to_view_more_link() {
    if (is_singular('media-clip')) {
        $view_more_link = get_post_meta(get_the_ID(), 'view_more_link', true);
        
        if (!empty($view_more_link)) {
            // Prevent infinite redirect loops
            if (home_url($_SERVER['REQUEST_URI']) !== $view_more_link) {
                wp_redirect(esc_url_raw($view_more_link), 301);
                exit;
            }
        }
    }
}
add_action('template_redirect', 'redirect_media_clip_to_view_more_link');


// Hook into ACF save post action for media-clip
add_action('acf/save_post', 'sync_acf_thumbnail_to_featured_image', 20);

/**
 * For Local Events, simply ensure the event_poster field is being used
 * We're NOT syncing to featured image since that causes confusion
 */
function bw_fix_local_event_display() {
    // This function doesn't need to do anything to "fix" existing events
    // We're now using the event_poster field directly in the shortcode renderer
    return 0;
}

// We don't need the fix function anymore
// add_action('init', 'bw_fix_local_event_display');

/**
 * Show admin notice about the local events
 */
function bw_local_events_admin_notice() {
    // Only show to admins
    if (!current_user_can('manage_options')) {
        return;
    }
    
    // Show a notice on the local events page
    global $pagenow;
    if ($pagenow === 'edit.php' && isset($_GET['post_type']) && $_GET['post_type'] === 'local-event') {
        ?>
        <div class="notice notice-info is-dismissible">
            <p><strong>Local Events:</strong> Each event requires a title, date text, description, and both image fields:</p>
            <ul style="margin-left: 20px; list-style-type: disc;">
                <li><strong>Featured Image</strong> - Appears in the event listing (main display image)</li>
                <li><strong>Event Poster Image</strong> - Shown when a visitor clicks the VIEW button</li>
            </ul>
            <p>Events will appear on the website based on their publish/unpublish dates.</p>
        </div>
        <?php
    }
}
add_action('admin_notices', 'bw_local_events_admin_notice');

/**
 * Include BW Gallery Slider Block
 */
require_once get_stylesheet_directory() . '/blocks/bw-gallery-slider/index.php';

/**
 * Include BW Local Events Block
 */
require_once get_stylesheet_directory() . '/blocks/bw-local-events/index.php';

/**
 * Include BW Default Title Block
 */
require_once get_stylesheet_directory() . '/blocks/bw-default-title/index.php';

/**
 * Include BW Advanced Tabordion Block
 */
require_once get_stylesheet_directory() . '/blocks/bw-advanced-tabordion/index.php';

// Block code removed to prevent duplicate function errors and conflicts

/**
 * Register Local Events Custom Post Type
 */
function bw_register_local_events_post_type() {
    $labels = array(
        'name'                  => _x('Local Events', 'Post type general name', 'kadence-child'),
        'singular_name'         => _x('Local Event', 'Post type singular name', 'kadence-child'),
        'menu_name'             => _x('Local Events', 'Admin Menu text', 'kadence-child'),
        'name_admin_bar'        => _x('Local Event', 'Add New on Toolbar', 'kadence-child'),
        'add_new'               => __('Add New', 'kadence-child'),
        'add_new_item'          => __('Add New Local Event', 'kadence-child'),
        'new_item'              => __('New Local Event', 'kadence-child'),
        'edit_item'             => __('Edit Local Event', 'kadence-child'),
        'view_item'             => __('View Local Event', 'kadence-child'),
        'all_items'             => __('All Local Events', 'kadence-child'),
        'search_items'          => __('Search Local Events', 'kadence-child'),
        'not_found'             => __('No local events found.', 'kadence-child'),
        'not_found_in_trash'    => __('No local events found in Trash.', 'kadence-child'),
        'featured_image'        => _x('Event Featured Image', 'Featured Image', 'kadence-child'),
        'set_featured_image'    => _x('Set featured image', 'Featured Image', 'kadence-child'),
        'remove_featured_image' => _x('Remove featured image', 'Featured Image', 'kadence-child'),
        'use_featured_image'    => _x('Use as featured image', 'Featured Image', 'kadence-child'),
    );

    $args = array(
        'labels'             => $labels,
        'public'             => true,
        'publicly_queryable' => true,
        'show_ui'            => true,
        'show_in_menu'       => true,
        'query_var'          => true,
        'rewrite'            => array('slug' => 'local-event'),
        'capability_type'    => 'post',
        'has_archive'        => true,
        'hierarchical'       => false,
        'menu_position'      => null,
        'menu_icon'          => 'dashicons-calendar-alt',
        'supports'           => array('title'), // Only support title, no editor or featured image
        'show_in_rest'       => false, // Disable Gutenberg editor
    );

    register_post_type('local-event', $args);
}
add_action('init', 'bw_register_local_events_post_type');

/**
 * Disable Gutenberg for Local Events and remove the editor completely
 */
function bw_disable_gutenberg_for_local_events($use_block_editor, $post_type) {
    if ($post_type === 'local-event') {
        return false; // Disable Gutenberg only for local-event post type
    }
    return $use_block_editor;
}
add_filter('use_block_editor_for_post_type', 'bw_disable_gutenberg_for_local_events', 10, 2);

/**
 * Hide Classic Editor from Local Events post type and enhance the UI
 */
function bw_hide_classic_editor_for_local_events() {
    global $typenow;
    
    // If we're on a local-event edit page
    if ($typenow === 'local-event') {
        // Add CSS to hide the editor and improve the admin layout
        echo '<style>
            /* Hide all editor-related elements */
            #postdivrich, /* Classic editor */
            .wp-editor-tabs, /* Editor tabs */
            .wp-editor-container, /* Entire editor container */
            .wp-editor-wrap, /* Editor wrapper */
            #editor, /* Gutenberg container */
            #edit-slug-box, /* Permalink box */
            .edit-post-header, /* Gutenberg header */
            .edit-post-layout__content, /* Gutenberg content */
            .editor-post-publish-panel, /* Publish panel */ 
            .components-panel__body.edit-post-post-status, /* Post status panel */
            .editor-post-featured-image__container + .components-button, /* Featured image replacement button */
            .editor-post-text-editor { /* Text editor */
                display: none !important;
            }
            
            /* Make the ACF fields more prominent */
            .acf-fields {
                padding-top: 20px !important;
            }
            
            /* Make the featured image uploader more prominent */
            #postimagediv {
                margin-top: 20px;
                padding: 15px;
                background: #f9f9f9;
                border: 1px solid #e2e4e7;
                border-radius: 4px;
            }
            
            #postimagediv h2 {
                margin-top: 0;
                font-size: 16px;
                font-weight: bold;
            }
            
            /* Hide featured image section completely */
            #postimagediv {
                display: none !important;
            }
            
            /* Add note about Event Poster field */
            .acf-field-event-poster::after {
                content: "This image will be displayed for the event in the Local Events listing.";
                display: block;
                margin-top: 5px;
                font-size: 12px;
                color: #646970;
                font-style: italic;
            }
        </style>';
        
        // Add JavaScript to enhance the UI for clarity
        echo '<script type="text/javascript">
            jQuery(document).ready(function($) {
                // Style the Featured Image field
                $(".acf-field-event-featured-image .acf-label label").css({
                    "font-size": "16px",
                    "font-weight": "bold",
                    "color": "#23282d",
                    "margin-bottom": "10px",
                    "display": "block"
                });
                
                // Add a special highlight to make it clear this is the main display image
                $(".acf-field-event-featured-image").css({
                    "padding": "20px",
                    "background": "#f0f7ff", // Light blue background
                    "border": "1px solid #c8d7e1",
                    "border-radius": "4px",
                    "margin-bottom": "20px"
                }).append("<div class=\'field-description\' style=\'margin-top:10px;font-style:italic;color:#646970;font-size:12px;\'>This image will appear in the event listing and is the main event image.</div>");
                
                // Style the Event Poster field
                $(".acf-field-event-poster .acf-label label").css({
                    "font-size": "16px",
                    "font-weight": "bold",
                    "color": "#23282d",
                    "margin-bottom": "10px",
                    "display": "block"
                });
                
                // Style the poster field differently
                $(".acf-field-event-poster").css({
                    "padding": "20px",
                    "background": "#fff8f0", // Light orange background
                    "border": "1px solid #e2d7c8",
                    "border-radius": "4px",
                    "margin-bottom": "20px"
                }).append("<div class=\'field-description\' style=\'margin-top:10px;font-style:italic;color:#646970;font-size:12px;\'>This image will be shown when a visitor clicks the VIEW button.</div>");
            });
        </script>';
    }
}
add_action('admin_head', 'bw_hide_classic_editor_for_local_events');

/**
 * Register ACF Fields for Local Events
 * Note: This is using ACF's local JSON feature. 
 * The fields will be saved to acf-json folder in the theme.
 */
function bw_register_local_events_acf_fields() {
    if(function_exists('acf_add_local_field_group')):

        acf_add_local_field_group(array(
            'key' => 'group_local_events',
            'title' => 'Local Event Details',
            'fields' => array(
                array(
                    'key' => 'field_event_featured_image',
                    'label' => 'Featured Image',
                    'name' => 'event_featured_image',
                    'type' => 'image',
                    'instructions' => 'Upload or select a featured image (used as the main image for the event in listings)',
                    'required' => 1, // Make it required
                    'return_format' => 'array',
                    'preview_size' => 'medium',
                    'library' => 'all',
                    'wrapper' => array(
                        'width' => '',
                        'class' => 'event-featured-image-field-wrapper',
                        'id' => ''
                    ),
                    'min_width' => 0,
                    'min_height' => 0,
                    'min_size' => 0,
                    'max_width' => 0,
                    'max_height' => 0,
                    'max_size' => 0,
                    'mime_types' => 'jpg,jpeg,png',
                ),
                array(
                    'key' => 'field_event_date_text',
                    'label' => 'Event Date Text',
                    'name' => 'event_date_text',
                    'type' => 'text',
                    'instructions' => 'Enter the event date as you want it displayed (e.g., "June 15-17, 2025")',
                    'required' => 1,
                ),
                array(
                    'key' => 'field_event_description',
                    'label' => 'Event Description',
                    'name' => 'event_description',
                    'type' => 'textarea',
                    'instructions' => 'Enter a short description of the event',
                    'required' => 1,
                ),
                array(
                    'key' => 'field_event_poster',
                    'label' => 'Event Poster Image',
                    'name' => 'event_poster',
                    'type' => 'image',
                    'instructions' => 'Upload or select an event poster image (shown when clicking "VIEW")',
                    'required' => 1, // Make it required
                    'return_format' => 'array',
                    'preview_size' => 'medium',
                    'library' => 'all',
                    'wrapper' => array(
                        'width' => '',
                        'class' => 'event-poster-field-wrapper',
                        'id' => ''
                    ),
                    'min_width' => 0,
                    'min_height' => 0,
                    'min_size' => 0,
                    'max_width' => 0,
                    'max_height' => 0,
                    'max_size' => 0,
                    'mime_types' => 'jpg,jpeg,png',
                ),
                array(
                    'key' => 'field_publish_date',
                    'label' => 'Publish Date',
                    'name' => 'publish_date',
                    'type' => 'date_picker',
                    'instructions' => 'When should this event start showing on the website? Leave blank to show immediately.',
                    'required' => 0,
                    'display_format' => 'd/m/Y',
                    'return_format' => 'Ymd',
                    'first_day' => 1,
                ),
                array(
                    'key' => 'field_unpublish_date',
                    'label' => 'Unpublish Date',
                    'name' => 'unpublish_date',
                    'type' => 'date_picker',
                    'instructions' => 'When should this event stop showing on the website? Leave blank to never automatically unpublish.',
                    'required' => 0,
                    'display_format' => 'd/m/Y',
                    'return_format' => 'Ymd',
                    'first_day' => 1,
                ),
            ),
            'location' => array(
                array(
                    array(
                        'param' => 'post_type',
                        'operator' => '==',
                        'value' => 'local-event',
                    ),
                ),
            ),
            'menu_order' => 0,
            'position' => 'normal',
            'style' => 'default',
            'label_placement' => 'top',
            'instruction_placement' => 'label',
            'hide_on_screen' => array(
                'the_content',
                'excerpt',
                'discussion',
                'comments',
                'revisions',
                'slug',
                'author',
                'format',
                'page_attributes',
                'featured_image',
                'categories',
                'tags',
                'send-trackbacks'
            ), // Hide everything except title and custom fields
            'active' => true,
            'description' => '',
            'show_in_rest' => true,
        ));
    endif;
}
add_action('acf/init', 'bw_register_local_events_acf_fields');

// Custom admin messages for Local Events post type
function bw_local_events_admin_messages($messages) {
    global $post;
    
    if (get_post_type($post) === 'local-event') {
        $messages['post'][1] = 'Local Event updated.';
        $messages['post'][4] = 'Local Event updated.';
        $messages['post'][6] = 'Local Event published.';
        $messages['post'][7] = 'Local Event saved.';
        $messages['post'][10] = 'Local Event draft updated.';
        
        // Add a special note about how these events are displayed
        $note = ' <span style="display:block;margin-top:5px;color:#646970;">Remember to include both a Featured Image (main display) and Event Poster Image (for VIEW button). Events appear on the website based on their Publish/Unpublish dates.</span>';
        $messages['post'][1] .= $note;
        $messages['post'][6] .= $note;
    }
    
    return $messages;
}
add_filter('post_updated_messages', 'bw_local_events_admin_messages');

/**
 * Local Events Block/Shortcode Renderer
 * Usage: [local_events count="3" orderby="date" order="ASC"]
 */
function bw_local_events_shortcode($atts) {
    // Parse attributes
    $atts = shortcode_atts(array(
        'count' => 3,     // Number of events to display
        'orderby' => 'meta_value', // Can be 'date', 'title', 'meta_value'
        'order' => 'ASC',  // ASC or DESC
    ), $atts);
    
    // Get today's date in the same format as ACF saves it
    $today = date('Ymd');
    
    // Build query args
    $args = array(
        'post_type' => 'local-event',
        'posts_per_page' => intval($atts['count']),
        'order' => $atts['order'],
        'meta_query' => array(
            'relation' => 'AND',
            // Either no publish date is set, or publish date is in the past
            array(
                'relation' => 'OR',
                array(
                    'key' => 'publish_date',
                    'compare' => 'NOT EXISTS',
                ),
                array(
                    'key' => 'publish_date',
                    'value' => '',
                    'compare' => '=',
                ),
                array(
                    'key' => 'publish_date',
                    'value' => $today,
                    'compare' => '<=',
                    'type' => 'NUMERIC',
                ),
            ),
            // Either no unpublish date is set, or unpublish date is in the future
            array(
                'relation' => 'OR',
                array(
                    'key' => 'unpublish_date',
                    'compare' => 'NOT EXISTS',
                ),
                array(
                    'key' => 'unpublish_date',
                    'value' => '',
                    'compare' => '=',
                ),
                array(
                    'key' => 'unpublish_date',
                    'value' => $today,
                    'compare' => '>=',
                    'type' => 'NUMERIC',
                ),
            ),
        )
    );
    
    // Add meta_key if ordering by meta_value
    if ($atts['orderby'] === 'meta_value') {
        $args['meta_key'] = 'event_date_text';
        $args['orderby'] = 'meta_value';
    } else {
        $args['orderby'] = $atts['orderby'];
    }
    
    // Get events
    $events_query = new WP_Query($args);
    
    // Start output buffering
    ob_start();
    
    if ($events_query->have_posts()) {
        echo '<div class="local-events-container">';
        
        while ($events_query->have_posts()) {
            $events_query->the_post();
            
            // Get both images: featured image for display and poster for lightbox
            $display_image = '';
            $poster_full_url = '';
            $poster_alt = get_the_title();
            
            // Get the featured image ACF field (primary display)
            $featured_image = get_field('event_featured_image');
            
            // Get the event poster ACF field (for lightbox/view)
            $poster = get_field('event_poster');
            
            // Set the display image (what appears in the list)
            if (!empty($featured_image) && isset($featured_image['url'])) {
                $display_image = $featured_image['url'];
                $poster_alt = !empty($featured_image['alt']) ? $featured_image['alt'] : $poster_alt;
            }
            
            // Set the poster image URL (what appears in the lightbox)
            if (!empty($poster) && isset($poster['url'])) {
                $poster_full_url = $poster['url'];
            } elseif (!empty($featured_image) && isset($featured_image['url'])) {
                // Fallback to featured image if no poster image
                $poster_full_url = $featured_image['url'];
            }
            
            // Start event item
            echo '<div class="local-event-row">';
            
            // Left column - Event Image (390px width, 280px height)
            echo '<div class="local-event-image-col">';
            
            if (!empty($display_image)) {
                echo '<a href="' . esc_url($poster_full_url) . '" title="' . esc_attr($poster_alt) . '" class="local-event-image-link">';
                echo '<div class="local-event-image" style="background-image: url(\'' . esc_url($display_image) . '\')"></div>';
                echo '</a>';
            } else {
                // Default placeholder
                echo '<div class="local-event-image placeholder-image"></div>';
                // Add an error message visible only to admins
                if (current_user_can('manage_options')) {
                    echo '<div style="position:absolute;top:0;left:0;background:rgba(255,0,0,0.7);color:white;padding:5px;font-size:10px;">No featured image set!</div>';
                }
            }
            echo '</div>';
            
            // Right column - Event Details
            echo '<div class="local-event-info-col">';
            
            // 1. Event Date - uppercase, 12px, color #838485, letter spacing
            if (get_field('event_date_text')) {
                echo '<div class="local-event-date">' . esc_html(get_field('event_date_text')) . '</div>';
            }
            
            // 2. Event Title - uppercase, 32px, weight 400, color #ff7760
            echo '<h2 class="local-event-title">' . strtoupper(get_the_title()) . '</h2>';
            
            // 3. Event Description
            if (get_field('event_description')) {
                echo '<div class="local-event-description">' . wp_kses_post(get_field('event_description')) . '</div>';
            }
            
            // 4. "VIEW >>" button - 13px, color #ff7760, no background
            // Simpler approach - just use a plain class without javascript in the href
            echo '<a href="#" class="local-event-view-link" data-image="' . esc_url($poster_full_url) . '" data-alt="' . esc_attr($poster_alt) . '">VIEW <span class="view-arrow">&raquo;</span></a>';
            
            echo '</div>'; // End right column
            echo '</div>'; // End event row
        }
        
        echo '</div>'; // End container
        
    } else {
        echo '<p class="no-events-message">' . esc_html__('No events found.', 'kadence-child') . '</p>';
    }
    
    // Reset post data
    wp_reset_postdata();
    
    // Return the buffered output
    return ob_get_clean();
}
add_shortcode('local_events', 'bw_local_events_shortcode');

/**
 * Include Interactive Map Shortcode
 */
require_once get_stylesheet_directory() . '/inc/interactive-map-shortcode.php';

/**
 * Include helper for Interactive Map in editor
 */
require_once get_stylesheet_directory() . '/blocks/bw-interactive-map-helper.php';

/**
 * Prevent output during AJAX/REST that could break JSON responses
 */
function bw_prevent_rest_output() {
    if ((defined('REST_REQUEST') && REST_REQUEST) || wp_doing_ajax()) {
        // Turn off any PHP notices or warnings during REST/AJAX requests
        error_reporting(0);
        // Disable debug logging
        @ini_set('display_errors', 0);
    }
}
add_action('init', 'bw_prevent_rest_output', 1); // Run very early


add_filter('wp_lazy_loading_enabled', '__return_false');

