<?php










//ini_set('display_errors', 1);
//ini_set('display_startup_errors', 1);
//error_reporting(E_ALL);


// 🔍 Debug Enqueued Styles (optional output)
function debug_enqueued_styles_in_php() {
    global $wp_styles;
    foreach ($wp_styles->queue as $handle) {
        $src = isset($wp_styles->registered[$handle]->src) ? $wp_styles->registered[$handle]->src : 'Unknown';
    }
}
add_action('wp_footer', 'debug_enqueued_styles_in_php');


// 🎨 Enqueue Parent + Child Styles with Cache Busting
function firefly_enqueue_styles() {
    $parent_style = 'parent-style';
    $child_style  = 'child-style';


    $parent_version = filemtime(get_template_directory() . '/style.css');
    $child_version  = filemtime(get_stylesheet_directory() . '/style.css');


   wp_enqueue_style($parent_style, get_template_directory_uri() . '/style.css', array(), $parent_version);
    wp_enqueue_style($child_style, get_stylesheet_directory_uri() . '/style.css', array($parent_style), $child_version);
}
add_action('wp_enqueue_scripts', 'firefly_enqueue_styles');


// ❌ Remove Unnecessary Styles
function firefly_remove_duplicate_styles() {
    wp_dequeue_style('blankslate-style');
    wp_deregister_style('blankslate-style');
}
add_action('wp_enqueue_scripts', 'firefly_remove_duplicate_styles', 20);


// 📥 Load Modular Customizer Sections     
function firefly_load_customizer_files() {
    $files = [
      
    
        'firefly-colours.php',    
        'firefly-layout.php', 
        'firefly-fonts.php',
        'firefly-blocks.php',
        'plugins.php',
        'firefly-gallery.php',
        'firefly-documents.php',
        'firefly-events.php',
        'firefly-admin.php',
        'firefly-header.php',
        'firefly-footer.php',
        'firefly-css.php',
        'firefly-schema.php',
        'firefly-seo.php'

    ];

         if (get_theme_mod('my_plugin_has_things', false)) {
        $files[] = 'firefly-things.php';
    }


    if (get_theme_mod('my_plugin_has_background_images', false)) {
        $files[] = 'firefly-background-images.php';
    }


     if (get_theme_mod('my_plugin_has_menu', true)) {
        $files[] = 'firefly-menu.php';
    }

    foreach ($files as $file) {
        $path = get_stylesheet_directory() . '/' . $file;
        if (file_exists($path)) {
            require_once $path;
        }
    }

   
}
add_action('after_setup_theme', 'firefly_load_customizer_files', 1);












// 🎨 Custom Block Styles
function my_custom_block_styles() {
    register_block_style('core/heading', array(
        'name'  => 'white-on-black',
        'label' => __('White on Black Box'),
        'inline_style' => '
            .wp-block-heading.is-style-white-on-black {
                color: white
                background-color: black;
                padding: 0.5em 1em;
                text-align: center;
                display: inline-block;
                width: 100%;
                max-width: 100%;
                font-size: 30px;
            }
        ',
    )); 


        $max_width    = get_theme_mod('my_plugin_max_width', '95%');
    $padding_lr   = get_theme_mod('my_plugin_padding_lr', '15px');


register_block_style('core/buttons', array(
    'name'  => 'align-center',
    'label' => __('Align Center!'),
    'inline_style' => '
        .wp-block-buttons.is-style-align-center {
            margin-left: auto !important;
            margin-right: auto !important;
            max-width:{$max-width} !important;
            margin-left:20px;
            text-align:center !important;
            /* border:10px red solid; debugging */
        }
    ',
));


// Buttons wrapper: Align Left
register_block_style( 'core/buttons', array(
    'name'  => 'align-left-row',
    'label' => __( 'Align Left' ),
    'inline_style' => '
        .wp-block-buttons.is-style-align-left-row {
            display:inline-block;
            text-align: left;
            width: 100%;
           max-width:{$max-width};
           /* margin:0 auto;*/
           padding-left:18px;
        }
    ',
) );



    register_block_style('core/heading', array(
        'name'  => 'gold-underline',
        'label' => __('Gold Underline'),
        'inline_style' => '
            .wp-block-heading.is-style-gold-underline {
                color: gold
                text-decoration: underline;
                text-decoration-thickness: 3px;
                text-underline-offset: 4px;
            }
        ',
    ));


    register_block_style('core/image', array(
        'name'  => 'full-width-image',
        'label' => __('Full Width Image (100%)'),
        'inline_style' => '
            .is-style-full-width-image {
                width: 100%
                max-width: 100%
            }
            .wp-block-image.is-style-full-width-image img {
                width: 100%
                max-width: 100%
                height: auto;
                display: block;
            }
        ',
    ));






    register_block_style('core/image', array(
        'name'  => 'almost-full-width-image',
        'label' => __('Almost Full Width (95%)'),
        'inline_style' => '
            .wp-block-image.is-style-almost-full-width-image img {
                width: 95%
                height: auto;
                display: block;
                margin-left: auto;
                margin-right: auto;
            }
        ',
    ));



    
 register_block_style(
    'core/group',
    array(
        'name'  => 'full-width',
        'label' => __('Full width', 'your-textdomain'),
        'inline_style' => '
            .wp-block-group.is-style-full-width {
                max-width: 100%
                width:100%
            }
        ',
    )
);



    

register_block_style(
    'core/group',
    array(
        'name'  => 'paragraph-width',
        'label' => __('Paragraph width', 'your-textdomain'),
        'inline_style' => "
            .wp-block-group.is-style-paragraph-width {
                max-width: {$max_width};
                padding-left: {$padding_lr};
                padding-right: {$padding_lr};
            }
        ",
    )
);



register_block_style(
    'core/group',
    array(
        'name'  => '80-percent-width',
        'label' => __('80% width', 'your-textdomain'),
        'inline_style' => "
            .wp-block-group.is-style-80-percent-width {
                max-width: 80%;
                padding-left: {$padding_lr};
                padding-right: {$padding_lr};
            }
        ",
    )
);


  register_block_style( 'core/image', array(
        'name'  => 'circle-mask',
        'label' => __( 'Circle Mask', 'text-domain' ),
    ) );

    register_block_style('core/columns', array(
        'name'  => 'columns-full-width',
        'label' => __('Full width'),
        'inline_style' => '
            .wp-block-columns.is-style-columns-full-width {
                max-width: 100%
                width:100%
                /* bbborder:5px red solid */
            }
        ',
    ));


        register_block_style('core/columns', array(
        'name'  => 'columns-paragraph-width',
        'label' => __('Paragraph width'),
          'inline_style' => "
            .wp-block-columns.is-style-columns-paragraph-width {
                max-width: {$max_width};
                padding-left: {$padding_lr};
                padding-right: {$padding_lr};
                /* bbborder:5px blue solid */
            } 
        ",
    ));



    if (1==2) {
    register_block_style('core/group', array(
        'name'  => 'Paragraph-width-coloured-background',
        'label' => __('Paragraph width coloured background'),
        'inline_style' => '
            .wp-block-columns.is-style-paragraph-width-coloured-background {
                padding: 2em;
                bbborder: 1px solid #ccc;
                bbborder-radius: 10px;
                background-color: #f9f9f9;
            }
        ',
    ));
   


    register_block_style('core/group', array(
        'name'  => 'Plain',
        'label' => __('Plain'),
        'inline_style' => '
            .wp-block-group.is-style-plain {
            }
        ',
    ));
   


    register_block_style('core/group', array(
        'name'  => 'highlight-section',
        'label' => __('Full width coloured background'),
        'inline_style' => '
            .wp-block-group.is-style-highlight-section {
                background-color: #ffffcc;
                padding: 1.5em;
            }
        ',
    ));
   


    register_block_style('core/group', array(
        'name'  => 'columns',
        'label' => __('Columns (products, staff)'),
        'inline_style' => '
            .wp-block-group.is-style-columns {
                background-color: #ffffcc;
                padding: 1.5em;
            }
        ',
    ));




    register_block_style('core/group', array(
        'name'  => 'container-for-columns',
        'label' => __('Container for columns'),
        'inline_style' => '
            .wp-block-group.is-style-container-for-columns {
                background-color: #ffffff;
                padding: 1.5em;
            }
        ',
    ));
   
}

    register_block_style(
        'core/image',
        array(
            'name'  => 'fifty-width',
            'label' => __('50% width align right', 'your-textdomain'),
            'inline_style' => '.wp-block-image.is-style-fifty-width img { width: 50% height: auto; }',
        )
    );
   
   
      register_block_style(
        'core/image',
        array(
            'name'  => '33-width',
            'label' => __('33% width align right', 'your-textdomain'),
            'inline_style' => '.wp-block-image.is-style-33-width img { width: 33% height: auto; }',
        )
    );
   


    register_block_style('core/image', array(
    'name'  => 'centered-image',
    'label' => __('Centered Image', 'your-textdomain'),
    'inline_style' => '
        .wp-block-image.is-style-centered-image {
            display: flex;
            justify-content: center;
        }
        .wp-block-image.is-style-centered-image img {
            float: none
            margin-left: auto;
            margin-right: auto;
            display: block;
        }
    ',
));






   
}
add_action('init', 'my_custom_block_styles');





add_action('admin_post_firefly_delete_gallery', 'firefly_handle_delete_gallery');
add_action('admin_post_firefly_delete_all_gallery_images', 'firefly_handle_delete_all_gallery_images');




function firefly_handle_delete_gallery() {
    if (!current_user_can('delete_posts')) {
        wp_die('Permission denied.');
    }


    $gallery_id = intval($_GET['gallery_id'] ?? 0);
    if (!$gallery_id) {
        wp_die('Missing gallery ID.');
    }


    // Step 1: Delete the FooGallery post
    wp_delete_post($gallery_id, true);


    // Step 2: Remove [fireflygallery gallery_id="208"] from all post content
    $query = new WP_Query([
        'post_type'      => 'any',
        'post_status'    => 'any',
        'posts_per_page' => -1,
        's'              => '[fireflygallery',
    ]);


    // Corrected pattern: looks for gallery_id="208" instead of id=
    $pattern = '/\[fireflygallery\s+gallery_id\s*=\s*["\']?' . preg_quote($gallery_id, '/') . '["\']?\s*\]/i';


    foreach ($query->posts as $post) {
        $original_content = $post->post_content;
        $updated_content = preg_replace($pattern, '', $original_content);


        if ($updated_content !== $original_content) {
            wp_update_post([
                'ID' => $post->ID,
                'post_content' => $updated_content,
            ]);
            error_log("Shortcode removed from post ID {$post->ID}");
        }
    }


    wp_redirect(wp_get_referer());
    exit;
}








function firefly_handle_delete_all_gallery_images() {
    if (!current_user_can('delete_posts')) {
        wp_die('Permission denied.');
    }


    $gallery_id = intval($_GET['gallery_id'] ?? 0);
    if (!$gallery_id) {
        wp_die('Missing gallery ID.');
    }


    // Get attachment IDs from meta
    $attachment_ids = get_post_meta($gallery_id, '_foogallery_data_attachments', true);
    if (is_array($attachment_ids)) {
        foreach ($attachment_ids as $id) {
            wp_delete_attachment($id, true); // permanently delete image
        }
    }


    // Clear meta
    update_post_meta($gallery_id, 'foogallery_attachments', []);
    update_post_meta($gallery_id, '_foogallery_data_attachments', []);


    wp_redirect(wp_get_referer());
    exit;
}


function firefly_move_gallery_up() {
    if (!current_user_can('edit_posts')) {
        wp_die('Permission denied.');
    }


    $gallery_id = intval($_GET['gallery_id'] ?? 0);
    firefly_move_gallery_in_post($gallery_id, 'up');


    wp_redirect(wp_get_referer());
    exit;
}


function firefly_move_gallery_down() {
    if (!current_user_can('edit_posts')) {
        wp_die('Permission denied.');
    }


    $gallery_id = intval($_GET['gallery_id'] ?? 0);
    firefly_move_gallery_in_post($gallery_id, 'down');


    wp_redirect(wp_get_referer());
    exit;
}


function firefly_move_gallery_in_post($gallery_id, $direction = 'up') {
    // Query posts containing the fireflygallery shortcode
    $query = new WP_Query([
        'post_type'      => 'any',
        'post_status'    => 'any',
        'posts_per_page' => -1,
        's'              => '[fireflygallery',
    ]);


    foreach ($query->posts as $post) {
        $content = $post->post_content;


        // Split content into blocks of text and shortcodes
        $pattern = '/(\[fireflygallery\b[^\]]*\])/i';
        $blocks = preg_split($pattern, $content, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);


        // Extract only fireflygallery shortcodes and their positions
        $gallery_blocks = [];
        foreach ($blocks as $index => $block) {
            if (preg_match('/^\[fireflygallery\b/i', $block)) {
                // Parse attributes to check gallery_id
                $attrs = shortcode_parse_atts(str_replace(['[fireflygallery', ']'], '', $block));
                if (isset($attrs['gallery_id']) && intval($attrs['gallery_id']) === $gallery_id) {
                    $gallery_blocks[] = $index;
                }
            }
        }


        if (empty($gallery_blocks)) {
            continue;
        }


        // Collect all indexes of fireflygallery shortcodes
        $all_shortcode_indexes = [];
        foreach ($blocks as $index => $block) {
            if (preg_match('/^\[fireflygallery\b/i', $block)) {
                $all_shortcode_indexes[] = $index;
            }
        }


        // Find current position in the list of shortcodes
        $current_pos = array_search($gallery_blocks[0], $all_shortcode_indexes);
        if ($current_pos === false) {
            continue;
        }


        // Determine target position based on direction
        if ($direction === 'up') {
            if ($current_pos === 0) {
                continue; // Already first, can't move up
            }
            $target_pos = $current_pos - 1;
        } else {
            if ($current_pos >= count($all_shortcode_indexes) - 1) {
                continue; // Already last, can't move down
            }
            $target_pos = $current_pos + 1;
        }


        // Get the actual block indexes to swap
        $current_index = $all_shortcode_indexes[$current_pos];
        $target_index = $all_shortcode_indexes[$target_pos];


        // Swap the blocks
        $temp = $blocks[$current_index];
        $blocks[$current_index] = $blocks[$target_index];
        $blocks[$target_index] = $temp;


        // Rebuild content
        $new_content = implode('', $blocks);


        // Update the post
        wp_update_post([
            'ID' => $post->ID,
            'post_content' => $new_content,
        ]);


        break; // Process only the first post found
    }
}


add_action('admin_post_firefly_move_gallery_up', 'firefly_move_gallery_up');
add_action('admin_post_firefly_move_gallery_down', 'firefly_move_gallery_down');



add_action('wp_ajax_test_simple_ajax', function () {
    header('Content-Type: application/json');
    wp_send_json_success('🔥 Test handler triggered successfully');
});





/**
 * Generic Block Deletion Functionality
 */


 







 /**
 * Block Manipulation Functions for WordPress
 * Handles deleting, moving up, and moving down any block type
 */

// Main function to handle all block operations via URL parameters
function firefly_block_operations() {
    // Check permissions first
    if (!current_user_can('manage_options')) {
        return;
    }
    
    // Get operation type and block index
    $operation = null;
    $block_index = -1;
    
    if (isset($_GET['delete_block'])) {
        $operation = 'delete';
        $block_index = isset($_GET['block_index']) ? intval($_GET['block_index']) : -1;
    } elseif (isset($_GET['move_up'])) {
        $operation = 'move_up';
        $block_index = isset($_GET['block_index']) ? intval($_GET['block_index']) : -1;
    } elseif (isset($_GET['move_down'])) {
        $operation = 'move_down';
        $block_index = isset($_GET['block_index']) ? intval($_GET['block_index']) : -1;
    }
    
    // If no operation specified, return early
    if (!$operation) {
        return;
    }
    
    // Get the current post ID
    $post_id = get_the_ID();
    if (!$post_id && isset($_GET['post_id'])) {
        $post_id = intval($_GET['post_id']);
    }
    
    if (!$post_id) {
        // No post ID found
        wp_die('Unable to determine the current page. <a href="/">Return to homepage</a>.');
        return;
    }
    
    // Get the post content
    $post = get_post($post_id);
    if (!$post) {
        wp_die('Post not found. <a href="/">Return to homepage</a>.');
        return;
    }
    
    // Parse blocks
    $blocks = parse_blocks($post->post_content);
    
    // Find block by index or by type/attributes if index not provided
    if ($block_index === -1) {
        // Try to find by block type
        if (isset($_GET['block_type'])) {
            $block_type = sanitize_text_field($_GET['block_type']);
            $block_index = firefly_find_block_by_type($blocks, $block_type);
        }
        
        // If still not found, try to find by shortcode content
        if ($block_index === -1 && isset($_GET['shortcode'])) {
            $shortcode = sanitize_text_field($_GET['shortcode']);
            $block_index = firefly_find_shortcode_block($blocks, $shortcode);
        }
    }
    
    // Check if block index is valid
    if ($block_index < 0 || $block_index >= count($blocks)) {
        // Block not found
        add_action('wp_footer', function() {
            echo '<div style="position: fixed; bottom: 20px; right: 20px; background: #f44336; color: white; padding: 15px; bbbborder-radius: 4px; box-shadow: 0 2px 4px rgba(0,0,0,0.2); z-index: 9999;">';
            echo 'Error: Block not found';
            echo '<button onclick="this.parentNode.style.display=\'none\'" style="background: transparent; bbbborder: none; color: white; float: right; font-weight: bold; cursor: pointer;">×</button>';
            echo '</div>';
        });
        return;
    }
    
    // Perform the requested operation
    $content_updated = false;
    
    if ($operation === 'delete') {
        // Remove the block at the specified index
        array_splice($blocks, $block_index, 1);
        $content_updated = true;
    } 
    elseif ($operation === 'move_up' && $block_index > 0) {
        // Swap with the block above
        $temp = $blocks[$block_index - 1];
        $blocks[$block_index - 1] = $blocks[$block_index];
        $blocks[$block_index] = $temp;
        $content_updated = true;
    } 
    elseif ($operation === 'move_down' && $block_index < count($blocks) - 1) {
        // Swap with the block below
        $temp = $blocks[$block_index + 1];
        $blocks[$block_index + 1] = $blocks[$block_index];
        $blocks[$block_index] = $temp;
        $content_updated = true;
    }
    
    if ($content_updated) {
        // Rebuild the content from the modified blocks array
        $new_content = '';
        foreach ($blocks as $block) {
            $new_content .= serialize_block($block);
        }
        
        // Update the post
        $update_result = wp_update_post([
            'ID' => $post_id,
            'post_content' => $new_content
        ]);
        
        if (!is_wp_error($update_result)) {
            // Clear cache
            clean_post_cache($post_id);
            
            // Show success message
            add_action('wp_footer', function() use ($operation) {
                $message = 'Block successfully ';
                switch ($operation) {
                    case 'delete': $message .= 'deleted'; break;
                    case 'move_up': $message .= 'moved up'; break;
                    case 'move_down': $message .= 'moved down'; break;
                }
                
                echo '<div style="position: fixed; bottom: 20px; right: 20px; background: #4CAF50; color: white; padding: 15px; bbbborder-radius: 4px; box-shadow: 0 2px 4px rgba(0,0,0,0.2); z-index: 9999;">';
                echo $message . '!';
                echo '<button onclick="this.parentNode.style.display=\'none\'" style="background: transparent; bbbborder: none; color: white; float: right; font-weight: bold; cursor: pointer;">×</button>';
                echo '</div>';
            });
            
            // Redirect to the same page without parameters
            $redirect_url = remove_query_arg(['delete_block', 'move_up', 'move_down', 'block_index', 'block_type', 'shortcode', 'post_id'], $_SERVER['REQUEST_URI']);
            wp_redirect($redirect_url);
            exit;
        } else {
            // Error updating post
            add_action('wp_footer', function() {
                echo '<div style="position: fixed; bottom: 20px; right: 20px; background: #f44336; color: white; padding: 15px; bbbborder-radius: 4px; box-shadow: 0 2px 4px rgba(0,0,0,0.2); z-index: 9999;">';
                echo 'Error updating the post content.';
                echo '<button onclick="this.parentNode.style.display=\'none\'" style="background: transparent; bbbborder: none; color: white; float: right; font-weight: bold; cursor: pointer;">×</button>';
                echo '</div>';
            });
        }
    }
}

// Helper function to find a block by type
function firefly_find_block_by_type($blocks, $block_type) {
    foreach ($blocks as $index => $block) {
        $name = $block['blockName'] ?? '';
        
        // Get the short name (part after the last slash)
        $name_parts = explode('/', $name);
        $short_name = end($name_parts);
        
        // Match against full name or short name
        if ($name === $block_type || $short_name === $block_type) {
            return $index;
        }
    }
    return -1; // Not found
}

// Helper function to find a shortcode block
function firefly_find_shortcode_block($blocks, $shortcode) {
    foreach ($blocks as $index => $block) {
        $name = $block['blockName'] ?? '';
        $html = $block['innerHTML'] ?? '';
        
        // First, check if it's a shortcode block
        if ($name === 'core/shortcode') {
            // Then check if it contains the specified shortcode
            if (strpos($html, '[' . $shortcode) !== false) {
                return $index;
            }
        }
    }
    return -1; // Not found
}















function firefly_add_block_operation_links($links_html, $block_type, $link_texts = []) {
    // Only show for admins
    if (!current_user_can('manage_options')) {
        return $links_html;
    }

    // ✅ Only show for core/group blocks
    if ($block_type !== 'core/group') {
        return $links_html;
    }

    // Default operations
    $operations = [
        'delete' => 'Delete this block',
        'move_up' => 'Move up',
        'move_down' => 'Move down'
    ];

    // Override with custom link texts if provided
    foreach ($link_texts as $op => $text) {
        if (isset($operations[$op])) {
            $operations[$op] = $text;
        }
    }

    // Get current post ID
    $post_id = get_the_ID();

    // Base parameters for all operation URLs
    $base_params = [
        'block_type' => $block_type,
        'post_id' => $post_id
    ];

    // For specific shortcodes
    if ($block_type === 'shortcode' && isset($_GET['shortcode'])) {
        $base_params['shortcode'] = $_GET['shortcode'];
    }

    // Add all operation links
    $new_links = [];

    foreach ($operations as $op => $text) {
        $params = array_merge([$op . '_block' => '1'], $base_params);
        $op_url = add_query_arg($params, $_SERVER['REQUEST_URI']);

        $confirm_msg = ($op === 'delete') ? 
            'Are you sure you want to delete this ' . strtolower(str_replace('Delete this ', '', $text)) . '?' : 
            'Are you sure?';

        $new_links[] = '<a href="' . esc_url($op_url) . '" onclick="return confirm(\'' . $confirm_msg . '\');">' . esc_html($text) . '</a>';
    }

    // Append new links to existing HTML
    if (strpos($links_html, '|') !== false) {
        $links_html .= ' | ' . implode(' | ', $new_links);
    } else {
        $links_html .= ' | ' . implode(' | ', $new_links);
    }

    return $links_html;
}

// Function to inject operation links into your specific admin UIs
function firefly_modify_admin_controls($html) {
    // For event modules (upcomingevents shortcode)
    if (strpos($html, 'Firefly event options') !== false) {
        $_GET['shortcode'] = 'upcomingevents';
        return firefly_add_block_operation_links($html, 'shortcode', [
            'delete' => 'Delete this events module',
            'move_up' => 'Move up',
            'move_down' => 'Move down'
        ]);
    }
    
    // For image options
    if (strpos($html, 'Image options') !== false) {
        return firefly_add_block_operation_links($html, 'image', [
            'delete' => 'Delete this image',
            'move_up' => 'Move up',
            'move_down' => 'Move down'
        ]);
    }
    
    // For gallery options (foogallery)
    if (strpos($html, 'Gallery options') !== false || strpos($html, 'foogallery') !== false) {
        $_GET['shortcode'] = 'foogallery';
        return firefly_add_block_operation_links($html, 'shortcode', [
            'delete' => 'Delete this gallery',
            'move_up' => 'Move up', 
            'move_down' => 'Move down'
        ]);
    }
    
    // For form options (fluentform)
    if (strpos($html, 'Form options') !== false || strpos($html, 'fluentform') !== false) {
        $_GET['shortcode'] = 'fluentform';
        return firefly_add_block_operation_links($html, 'shortcode', [
            'delete' => 'Delete this form',
            'move_up' => 'Move up',
            'move_down' => 'Move down'
        ]);
    }
    
    return $html;
}

// Add main operation handler
add_action('template_redirect', 'firefly_block_operations');

// Filter to modify your admin controls
// You can replace this with your actual filter or action hook
add_filter('the_content', function($content) {
    // Find and modify admin control sections
    $pattern = '/<div class="([^"]*(?:admin|firefly)-controls[^"]*)">(.*?)<\/div>/s';
    return preg_replace_callback($pattern, function($matches) {
        return '<div class="' . $matches[1] . '">' . firefly_modify_admin_controls($matches[2]) . '</div>';
    }, $content);
}, 999);


add_filter( 'block_type_metadata_settings', function( $settings, $metadata ) {

    // Only change core/heading
    if ( isset( $metadata['name'] ) && $metadata['name'] === 'core/heading' ) {

        if ( ! isset( $settings['supports'] ) ) {
            $settings['supports'] = [];
        }
        if ( ! isset( $settings['supports']['spacing'] ) ) {
            $settings['supports']['spacing'] = [];
        }

        // Turn on the UI for padding and margin
        $settings['supports']['spacing']['padding'] = true;
        $settings['supports']['spacing']['margin']  = true;
    }

    return $settings;

}, 10, 2 );




add_action('template_redirect', function () {
    if (isset($_GET['show_all_settings']) && current_user_can('manage_options')) {
        header('Content-Type: text/plain');

        $mods = get_theme_mods();

        foreach ($mods as $key => $value) {
            // ❌ Skip empty strings and arrays
            if ($value === '' || is_array($value)) continue;

            // ✅ Format booleans
            if (is_bool($value)) {
                $value = $value ? 'true' : 'false';
            } elseif (is_object($value)) {
                $value = json_encode($value);
            } else {
                $value = "'" . $value . "'";
            }

            printf("    '%s' => %s,\n", $key, $value);
        }

        exit;
    }
});



function custom_admin_title_styles($hook) {
    // Only load on post add/edit screens
    global $pagenow;
    if ($pagenow !== 'post.php' && $pagenow !== 'post-new.php') return;

    echo '<style>
        #titlewrap h1, .edit-post-visual-editor__post-title-wrapper h1 {
            color: white
            font-size: 18px
            font-weight: bold;
            background-color: grey;
            padding: 10px;
        }
    </style>';
}
add_action('admin_head', 'custom_admin_title_styles');




add_action('after_setup_theme', function () {
    $checker_file = get_stylesheet_directory() . '/update-checker.php';


    //echo "<h2>";
    //echo $checker_file;
    //echo "</h2>";

    if (file_exists($checker_file)) {
        require $checker_file;

    } else {
        error_log('update-checker.php not found at ' . $checker_file);
      
    }
});



//=======================================================




// ✅ 1. Assign a unique ID to each block (used in post_content)
//add_filter('render_block_data', 'firefly_assign_block_id', 10, 2);
function firefly_assign_block_id($parsed_block, $source_block) {
    if (current_user_can('edit_posts')) {
        if (empty($parsed_block['attrs']['firefly_block_id'])) {
            $parsed_block['attrs']['firefly_block_id'] = uniqid('block_');
        }
    }
    return $parsed_block;
}




add_action('save_post', 'firefly_assign_block_ids_on_save', 10, 3);
function firefly_assign_block_ids_on_save($post_id, $post, $update) {
    if ($post->post_type !== 'page' && $post->post_type !== 'post') return;
    if (!current_user_can('edit_post', $post_id)) return;

    $blocks = parse_blocks($post->post_content);
    $modified = false;

    firefly_recursive_assign_ids($blocks, $modified);

    if ($modified) {
        $new_content = implode("\n\n", array_map('serialize_block', $blocks));
        remove_action('save_post', 'firefly_assign_block_ids_on_save', 10);
        wp_update_post([
            'ID' => $post_id,
            'post_content' => $new_content,
        ]);
        add_action('save_post', 'firefly_assign_block_ids_on_save', 10, 3);
    }
}



function firefly_recursive_assign_ids(&$blocks, &$modified) {
  //  foreach ($blocks as &$block) {
   //     if (!is_array($block)) continue;

        // Only add ID to custom blocks
 //       if (
 //           strpos($block['blockName'], 'core/') !== 0 &&
  //          empty($block['attrs']['firefly_block_id'])
   //     ) {
    //        $block['attrs']['firefly_block_id'] = uniqid('block_');
    //        $modified = true;
   //     }

   //     if (!empty($block['innerBlocks'])) {
    //        firefly_recursive_assign_ids($block['innerBlocks'], $modified);
    //    }
   // }
}




// ✅ 3. Render block controls and visible block ID
//add_filter('render_block', 'firefly_add_block_controls', 10, 2);
function firefly_add_block_controls($block_content, $block) {
    if (!current_user_can('edit_posts')) return $block_content;

    $block_id   = esc_html($block['attrs']['firefly_block_id'] ?? '');
    $block_type = esc_html($block['blockName'] ?? 'unknown');



    if ($block_type == "unknown") return $block_content;

    if (!$block_id) return $block_content;

    // 🔍 Extract shortcode if this is a core/shortcode block
            if ($block_type === 'core/shortcode') {
                $shortcode_raw = $block['innerContent'][0] ?? '';

                if (preg_match('/\[([a-zA-Z0-9_]+)(.*?)\]/', $shortcode_raw, $matches)) {
                    $shortcode_tag = $matches[1];
                    $shortcode_attrs = trim($matches[2]);

                    // Inject block_id into specific shortcodes like [upcomingevents]
                    if ($shortcode_tag === 'upcomingevents' && strpos($shortcode_raw, 'block_id=') === false) {
                        $block_content = preg_replace_callback('/\[upcomingevents(.*?)\]/', function ($m) use ($block_id) {
                            return '[upcomingevents' . $m[1] . ' block_id="' . esc_attr($block_id) . '"]';
                        }, $block_content);
                    }
                }
            }


    if (!$block_id) return $block_content;

   

$admin_controls = '';
if ($block_type === 'core/group') {
    $admin_controls = sprintf(
        '<div class="delete-only" data-block-type="%s"><div class="firefly-admin-2">Block options - %s</div>
        <div class="firefly-admin-3">
            <a href="?edit_block_action=delete&block_id=%s" class="block-action" style="color:black;text-decoration:none;">Delete this block</a> 
        </div></div>',
        $block_type,
        $block_type,
        $block_id
    );
}


    if (!empty($block['attrs']['firefly_block_id'])) {
    $block_id = esc_attr($block['attrs']['firefly_block_id']);

    // Wrap the block content with a data attribute or comment
      //  $block_content = '<div class="firefly-block-wrapper" data-firefly-block-id="' . $block_id . '">'. $block_id . " " . $block_content . '</div>';


}

    return $visible . $admin_controls . $block_content;
}

// ✅ 4. Handle delete/move actions and show debug
add_action('template_redirect', 'firefly_handle_block_actions');
function firefly_handle_block_actions() {
    if (!is_user_logged_in() || !current_user_can('edit_posts')) return;

    $action   = $_GET['edit_block_action'] ?? '';
    $block_id = $_GET['block_id'] ?? '';
    $post_id  = get_the_ID();

    if (!$action || !$block_id || !$post_id || !is_singular()) return;

    $post = get_post($post_id);
    $blocks = parse_blocks($post->post_content);
   
    $found = false;
$new_blocks = firefly_traverse_blocks_and_delete($blocks, $block_id, $action, $found);


    if (!$found) {
        echo "<br>❌ <strong>Block not found!</strong>";
        echo '</div>';
        return;
    }

    $new_content = implode("\n\n", array_map('serialize_block', $new_blocks));
    echo "<br>✅ <strong>New post content length:</strong> " . strlen($new_content) . " characters<br>";
    echo "📃 Updating post...<br>";

    wp_update_post([
        'ID' => $post_id,
        'post_content' => $new_content,
    ]);

    echo "<br>🔄 Redirecting back to page...";
    echo '</div>';
    flush();
    sleep(2);
    wp_redirect(get_permalink($post_id));
    exit;

}






// ✅ 5. Add inline JS for confirmation
add_action('wp_footer', 'firefly_add_inline_block_actions_script');
function firefly_add_inline_block_actions_script() {
    if (!current_user_can('edit_posts')) return;
    ?>
    <script>
    document.addEventListener('DOMContentLoaded', function () {
        document.addEventListener('click', function (e) {
            const target = e.target.closest('.block-action');
            if (!target) return;

            const url = new URL(target.href);
            const action = url.searchParams.get("edit_block_action");
            const blockType = target.closest(".block-controls")?.dataset.blockType || "this block";

            if (action === 'delete') {
                if (!confirm(`Are you sure you want to delete ${blockType}?`)) {
                    e.preventDefault();
                }
            }
        });
    });




        document.addEventListener('DOMContentLoaded', () => {
        document.querySelectorAll('.firefly-block-wrapper').forEach(wrapper => {
            const blockId = wrapper.dataset.fireflyBlockId;
            const admin = wrapper.querySelector('.firefly-admin-3');

            if (blockId && admin && !admin.querySelector('.custom-delete-link')) {
            const deleteLink = document.createElement('a');
            deleteLink.href = `?edit_block_action=delete&block_id=${blockId}`;
            deleteLink.textContent = 'Delete this events listing';
            deleteLink.className = 'custom-delete-link';
            deleteLink.style.cssText = 'color:black;text-decoration:none;margin-left:8px;';
            deleteLink.onclick = () => confirm('Delete this block?') || event.preventDefault();
            admin.append(' | ', deleteLink);
            }
        });
        });


    </script>
    <?php
}



function firefly_traverse_blocks_and_delete($blocks, $target_id, $action, &$found) {
    $new_blocks = [];

    foreach ($blocks as $block) {
        $current_id = $block['attrs']['firefly_block_id'] ?? '';

        echo "Block — Type: <code>" . esc_html($block['blockName']) . "</code> — ID: <code>" . esc_html($current_id) . '</code><br>';

        if ($current_id === $target_id) {
            $found = true;
            echo "✅ <strong>Match found</strong> — performing <code>$action</code><br>";
            if ($action === 'delete') {
                echo "🧹 Skipping this block (deleted)<br>";
                continue;
            }
        }

        // Handle innerBlocks recursively
        if (!empty($block['innerBlocks'])) {
            $block['innerBlocks'] = firefly_traverse_blocks_and_delete($block['innerBlocks'], $target_id, $action, $found);
        }

        $new_blocks[] = $block;
    }

    return $new_blocks;
}

add_action('init', function () {
    if (isset($_GET['create_new_page']) && isset($_GET['pagename'])) {

        // 🔧 DEBUG
        ob_start();
        echo "<div style='position:fixed;top:0;left:0;width:100%;background:red;color:white;padding:10px;z-index:9999;'>";
        echo "🔧 DEBUG: create_new_page triggered<br>";

        $pagename = sanitize_title($_GET['pagename']);
        $title = sanitize_text_field($_GET['pagename']);
        echo "🔤 Page title: {$title}<br>";
        echo "🆔 Slug: {$pagename}<br>";

        // ✅ If page already exists
        $existing = get_page_by_path($pagename);
        if ($existing) {
            echo "⚠️ Page already exists. Redirecting...<br></div>";
            wp_redirect(get_permalink($existing->ID));
            exit;
        }

        // ✅ Gutenberg-safe block markup
        $block_html = '
            <!-- wp:group -->
                <!-- wp:heading -->
                <h1>' . esc_html($title) . '</h1>
                <!-- /wp:heading -->
                <!-- wp:paragraph -->
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur vel sem vel justo efficitur facilisis.</p>
                <!-- /wp:paragraph -->
            <!-- /wp:group -->
        ';

        $blocks = parse_blocks($block_html);
        $modified = false;
        firefly_recursive_assign_ids($blocks, $modified); // ✅ Make sure block IDs are applied

        $post_id = wp_insert_post([
            'post_title'   => $title,
            'post_name'    => $pagename,
            'post_status'  => 'publish',
            'post_type'    => 'page',
            'post_content' => serialize_blocks($blocks),
        ]);

        if (is_wp_error($post_id)) {
            echo "❌ Failed to create page: " . $post_id->get_error_message() . "</div>";
            exit;
        }

        echo "✅ Page created successfully (ID: $post_id)<br>";

        // ✅ Add to main menu if available
        $locations = get_nav_menu_locations();
        $menu_id = $locations['main-menu'] ?? null;

        if ($menu_id && is_nav_menu($menu_id)) {
            wp_update_nav_menu_item($menu_id, 0, [
                'menu-item-title'     => $title,
                'menu-item-object'    => 'page',
                'menu-item-object-id' => $post_id,
                'menu-item-type'      => 'post_type',
                'menu-item-status'    => 'publish',
            ]);
            echo "📌 Added to menu ID: $menu_id<br>";
        } else {
            echo "⚠️ No menu assigned to location 'main-menu'<br>";
        }

        echo "➡️ Redirecting to new page...</div>";
        ob_end_flush();
        wp_redirect(get_permalink($post_id));
        exit;
    }
});

add_action( 'template_redirect', function () {
    if ( isset( $_GET['ff_page_add_with_template'] ) ) {

        // Load WP header if you want the normal theme frame:
        get_header();

        require get_stylesheet_directory() . '/firefly-page-add-with-template.php';

        get_footer();

        exit; // Stop WP doing anything else
    }
} );


add_action( 'template_redirect', function () {
    if ( isset( $_GET['ff_section_add_with_template'] ) ) {

        // Use normal theme header + footer exactly like the page version
        get_header();

        require get_stylesheet_directory() . '/firefly-section-add-with-template.php';

        get_footer();

        exit; // Stop WP doing anything else
    }
} );



add_action( 'template_redirect', function () {

    if ( isset( $_GET['ff_show_raw'] ) && is_singular() ) {

        global $post;

        // Security: only allow logged-in editors/admins
        if ( ! is_user_logged_in() || ! current_user_can( 'edit_pages' ) ) {
            wp_die( 'You do not have permission to view raw page content.' );
        }

        // Get the raw DB content exactly as stored
        $raw = $post->post_content;

        header( 'Content-Type: text/plain; charset=utf-8' );


        echo $raw;

        exit;
    }
});


add_action('admin_menu', function () {
    add_submenu_page(
        null, // Hide from admin sidebar
        'Add Textblock', // Page title
        'Add Textblock', // Menu title (unused here)
        'manage_options', // Minimum capability (admin only)
        'firefly-add-textblock', // ?page=firefly-add-textblock
        'firefly_add_textblock_page_callback' // 👈 MUST MATCH your function name
    );
});


add_action('admin_init', function () {
    // Only fire for ?page=firefly-add-textblock
    if (!isset($_GET['page']) || $_GET['page'] !== 'firefly-add-textblock') return;

    // ✅ Ensure user is admin
    if (!current_user_can('manage_options')) {
        wp_die('You are not allowed to do this.');
    }

    $page_id = isset($_GET['page_id']) ? intval($_GET['page_id']) : 0;
    $style_class = isset($_GET['block_style']) ? sanitize_html_class($_GET['block_style']) : 'is-style-plain';

    if (!$page_id) {
        wp_die('No page ID provided.');
    }

    // Safely encode the block JSON
    $class_json = wp_json_encode(['className' => $style_class]);

    $block = <<<HTML
<!-- wp:group $class_json -->
<div class="wp-block-group $style_class">
<!-- wp:heading -->
<h2>New Section</h2>
<!-- /wp:heading -->
<!-- wp:paragraph -->
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<!-- /wp:paragraph -->
</div>
<!-- /wp:group -->
HTML;

    $post = get_post($page_id);
    if ($post && $post->post_type === 'page') {
        $updated_content = $post->post_content . "\n\n" . $block;

        wp_update_post([
            'ID' => $page_id,
            'post_content' => $updated_content,
        ]);
    }

    // 🔁 Clean, flicker-free redirect
    $target = esc_url(get_permalink($page_id));
    echo '<!DOCTYPE html>
<html><head>
<meta http-equiv="refresh" content="0;url=' . $target . '">
<script>location.href = "' . $target . '";</script>
</head><body style="background:#fff;"></body></html>';
    exit;
});






add_action('admin_post_firefly_add_scrolling_gallery', 'firefly_handle_add_scrolling_gallery');

function firefly_handle_add_scrolling_gallery() {
    if (!current_user_can('edit_posts')) {
        wp_die('Unauthorized');
    }

    $page_id     = isset($_POST['page_id']) ? intval($_POST['page_id']) : 0;
    $block_style = sanitize_text_field($_POST['block_style'] ?? '');

    // 🟩 Step 1: Create a new MetaSlider gallery
    $gallery_title = 'Scrolling Banner - Page ' . $page_id;
    $gallery_id = wp_insert_post([
        'post_title'  => $gallery_title,
        'post_type'   => 'ml-slider',
        'post_status' => 'publish',
    ]);

    if (!$gallery_id || is_wp_error($gallery_id)) {
        wp_die('Could not create gallery');
    }

    // 🟩 Step 2: Insert the MetaSlider shortcode as a Gutenberg block
    $shortcode = '[metaslider id="' . $gallery_id . '"]';
    $block = "<!-- wp:shortcode {\"className\":\"$block_style\"} -->$shortcode<!-- /wp:shortcode -->";

    $existing_blocks = parse_blocks(get_post_field('post_content', $page_id));
    $existing_blocks[] = parse_blocks($block)[0];
    $updated_content = serialize_blocks($existing_blocks);

    wp_update_post([
        'ID'           => $page_id,
        'post_content' => $updated_content,
    ]);

    // 🟩 Step 3: Redirect back to the page
    wp_redirect(get_permalink($page_id));
    exit;
}




function firefly_render_fonts_page() {
    $fonts = array_keys(firefly_get_all_font_choices());
    $source = $_GET['source'] ?? '';
    $target = $_GET['target'] ?? 'firefly_banner_font_family';

    // Detect page number from query or pretty URL
    $page = intval($_GET['paged'] ?? 0);
    if (!$page && preg_match('#/page/(\d+)/#', $_SERVER['REQUEST_URI'], $matches)) {
        $page = intval($matches[1]);
    }
    $page = max(1, $page);

    $per_page = 24;
    $offset = ($page - 1) * $per_page;
    $current_font = get_theme_mod($target);
    $text = get_theme_mod('firefly_banner_text', 'Your preview text here');
    $total_pages = ceil(count($fonts) / $per_page);

    echo '<!DOCTYPE html><html><head><title>View Fonts</title>';
    echo '<link rel="preconnect" href="https://fonts.googleapis.com">';
    echo '<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>';
    echo '<meta name="viewport" content="width=device-width, initial-scale=1">';
    echo '<style>
        body { font-family: sans-serif; margin: 40px; background: #f9f9f9; }
        .font-container { display: flex; flex-wrap: wrap; gap: 20px; }
        .font-box {
            display: inline-block;
            width: 300px;
            background: #fff;
            padding: 20px;
            bbbborder: 1px solid #ccc;
            vertical-align: top;
            box-sizing: bbbborder-box;
        }
        .font-box strong { display: block; margin-bottom: 10px; font-size: 16px; }
        .highlight { background-color: #dff0d8; }
        a.button {
            display:inline-block;
            padding:6px 12px;
            margin:10px 0;
            background:#0073aa;
            color:#fff;
            text-decoration:none;
            bbbborder-radius:4px;
        }
        a.button:hover { background:#005077; }
        .pagination { margin: 20px 0; }
    </style>';
    echo '</head><body>';
    echo '<h1>Preview Fonts</h1>';

    // Pagination (top)
    echo '<div class="pagination">';
    if ($page > 1) {
        echo '<a class="button" href="?paged=' . ($page - 1) . '&source=' . urlencode($source) . '&target=' . urlencode($target) . '">« Previous</a> ';
    }
    if ($page < $total_pages) {
        echo '<a class="button" href="?paged=' . ($page + 1) . '&source=' . urlencode($source) . '&target=' . urlencode($target) . '">Next »</a>';
    }
    echo '</div>';

    // Font panels
    echo '<div class="font-container">';
    $to_show = array_slice($fonts, $offset, $per_page);
    foreach ($to_show as $font) {
        $font_name = explode(',', $font)[0];
        $google_font = str_replace(' ', '+', $font_name);
        $highlight = ($current_font === $font) ? 'highlight' : '';

        echo "<div class='font-box $highlight'>";
        echo "<strong>$font</strong>";
        echo "<link href='https://fonts.googleapis.com/css2?family=" . esc_attr($google_font) . "&display=swap' rel='stylesheet'>";
        echo "<p style='font-family:$font;font-size:32px;'>$text</p>";

         echo "<p style='font-family:$font;font-size:16px;'>The quick brown fox jumps pver the lazy dog. Pack my box with five dozen liquor jugs. Sphinx of black quartz, judge my vow. The five boxing wizards jump quickly. Jackdaws love my big sphinx of quartz. How vexingly quick daft zebras jump! </p>";

        $url = add_query_arg([
            'action' => 'firefly_set_font',
            'font' => urlencode($font),
            'target' => $target,
            'source' => $source,
        ], admin_url('admin-post.php'));
       // echo "<a class='button' href='" . esc_url($url) . "'>Use this font</a>";
        echo "</div>";
    }
    echo '</div>';

    // Pagination (bottom)
    echo '<div class="pagination">';
    if ($page > 1) {
        echo '<a class="button" href="?paged=' . ($page - 1) . '&source=' . urlencode($source) . '&target=' . urlencode($target) . '">« Previous</a> ';
    }
    if ($page < $total_pages) {
        echo '<a class="button" href="?paged=' . ($page + 1) . '&source=' . urlencode($source) . '&target=' . urlencode($target) . '">Next »</a>';
    }
    echo '</div>';

    echo '</body></html>';
}




function firefly_get_all_font_choices() {
    return [ 
    'Abril Fatface, cursive' => 'Abril Fatface (dramatic, elegant)',
    'Aclonica, sans-serif' => 'Aclonica (negative space cuts)',
    'Alegreya, serif' => 'Alegreya (dynamic, readable)',
    'Aleo, serif' => 'Aleo (contemporary, slab-serif)',
    'Almendra Display, cursive' => 'Almendra Display (ancient coin)',
    'Amarante, cursive' => 'Amarante (Art Nouveau-inspired shapes)',
    'Anton, sans-serif' => 'Anton (strong, impactful)',
    'Archivo Narrow, sans-serif' => 'Archivo Narrow (condensed, versatile)',
    'Arial, sans-serif' => 'Arial (classic, neutral)',
    'Arvo, serif' => 'Arvo (geometric, slab-serif)',
    'Audiowide, cursive' => 'Audiowide (perfect circles)',
    'Bacasime Antique, serif' => 'Bacasime Antique (classic, antique style)',
    'Bangers, cursive' => 'Bangers (comic, bold, display)',
    'Barlow, sans-serif' => 'Barlow (contemporary, versatile)',
    'Bayon, sans-serif' => 'Bayon (angular Khmer style)',
    'Bebas Neue, sans-serif' => 'Bebas Neue (clean, display)',
    'Bitter, serif' => 'Bitter (contemporary, readable)',
    'Black Ops One, sans-serif' => 'Black Ops One (military stencil)',
    'Blaka Hollow, cursive' => 'Blaka Hollow (batik cutouts)',
    'Bodoni Moda, serif' => 'Bodoni Moda (fashion, high-contrast)',
    'Bowlby One, sans-serif' => 'Bowlby One (movie poster)',
    'Brush Script MT, cursive' => 'Brush Script MT (casual, artistic)',
    'Bungee, sans-serif' => 'Bungee (urban street-style)',
    'Bungee Shade, sans-serif' => 'Bungee Shade (3D shadow effect)',
    'Butterfly Kids, cursive' => 'Butterfly Kids (flower stems)',
    'Cabin, sans-serif' => 'Cabin (contemporary, friendly)',
    'Chango, cursive' => 'Chango (playful deco shapes)',
    'Cinzel, serif' => 'Cinzel (classic, Roman-style headings)',
    'Coda Caption, sans-serif' => 'Coda Caption (compact, bold)',
    'Codystar, cursive' => 'Codystar (constellation lines)',
    'Concert One, cursive' => 'Concert One (bold, fun)',
    'Condiment, cursive' => 'Condiment (condensed, playful)',
    'Cormorant Garamond, serif' => 'Cormorant Garamond (classic, refined)',
    'Courier New, monospace' => 'Courier New (technical, classic)',
    'Creepster, cursive' => 'Creepster (horror punk dripping style)',
    'Dancing Script, cursive' => 'Dancing Script (swirling elegance)',
    'DotGothic16, sans-serif' => 'DotGothic16 (pixel dots)',
    'Dosis, sans-serif' => 'Dosis (light, rounded)',
    'Eater, cursive' => 'Eater (vampire punk)',
    'Emilys Candy, cursive' => 'Emilys Candy (sweet wrappers)',
    'Exo 2, sans-serif' => 'Exo 2 (tech-inspired, readable)',
    'Fascinate, cursive' => 'Fascinate (comic book)',
    'Fasthand, serif' => 'Fasthand (Asian brush strokes)',
    'Faster One, cursive' => 'Faster One (speed lines)',
    'Fira Sans, sans-serif' => 'Fira Sans (technical, clean)',
    'Fjalla One, sans-serif' => 'Fjalla One (bold, compact headings)',
    'Francois One, sans-serif' => 'Francois One (rounded, headline)',
    'Freckle Face, cursive' => 'Freckle Face (spray-paint texture)',
    'Frijole, cursive' => 'Frijole (Day of the Dead)',
    'Georgia, serif' => 'Georgia (elegant, classic)',
    'Gothic A1, sans-serif' => 'Gothic A1 (modern gothic style)',
    'Gravitas One, serif' => 'Gravitas One (bold, slab-serif display)',
    'Great Vibes, cursive' => 'Great Vibes (calligraphic flair)',
    'Helvetica, sans-serif' => 'Helvetica (clean, versatile)',
    'Henny Penny, cursive' => 'Henny Penny (medieval manuscript)',
    'Hind, sans-serif' => 'Hind (simple, readable)',
    'IBM Plex Sans, sans-serif' => 'IBM Plex Sans (technical, professional)',
    'Inconsolata, monospace' => 'Inconsolata (monospace, technical)',
    'Inter, sans-serif' => 'Inter (neutral, readable)',
    'Irish Grover, cursive' => 'Irish Grover (Celtic knots)',
    'Josefin Sans, sans-serif' => 'Josefin Sans (geometric, elegant)',
    'Kanit, sans-serif' => 'Kanit (condensed, modern Thai-style)',
    'Karla, sans-serif' => 'Karla (minimalist, clean)',
    'Kranky, cursive' => 'Kranky (Halloween spooky)',
    'Lato, sans-serif' => 'Lato (warm, sophisticated)',
    'League Gothic, sans-serif' => 'League Gothic (tall, narrow, vintage)',
    'Libre Baskerville, serif' => 'Libre Baskerville (traditional, readable)',
    'Limelight, sans-serif' => 'Limelight (Broadway marquee)',
    'Lobster, cursive' => 'Lobster (50s diner)',
    'Luckiest Guy, cursive' => 'Luckiest Guy (comic, bold, fun)',
    'Major Mono Display, monospace' => 'Major Mono Display (hacking terminal)',
    'MedievalSharp, cursive' => 'MedievalSharp (castle inscriptions)',
    'Merriweather, serif' => 'Merriweather (traditional, readable)',
    'Metal Mania, cursive' => 'Metal Mania (engraved metal)',
    'Metrophobic, sans-serif' => 'Metrophobic (streamlined moderne)',
    'Michroma, sans-serif' => 'Michroma (retro-futuristic)',
    'Miltonian, cursive' => 'Miltonian (woodcut prints)',
    'Monoton, cursive' => 'Monoton (neon tube lights)',
    'Montserrat, sans-serif' => 'Montserrat (geometric, modern)',
    'Mountains of Christmas, cursive' => 'Mountains of Christmas (snowy peaks)',
    'Muli, sans-serif' => 'Muli (minimalist, versatile)',
    'Nabla, cursive' => 'Nabla (colorful layered)',
    'Nasalization, sans-serif' => 'Nasalization (space age)',
    'Neon Tubes, sans-serif' => 'Neon Tubes (retro, glowing lines)',
    'New Rocker, cursive' => 'New Rocker (70s metal band)',
    'Nosifer, cursive' => 'Nosifer (zombie apocalypse)',
    'Noto Sans Cherokee, sans-serif' => 'Noto Sans Cherokee (indigenous)',
    'Noto Sans Linear B, sans-serif' => 'Noto Sans Linear B (ancient Greek)',
    'Noto Sans Mayan, sans-serif' => 'Noto Sans Mayan (hieroglyphic)',
    'Noto Sans Osmanya, sans-serif' => 'Noto Sans Osmanya (ancient script)',
    'Nunito, sans-serif' => 'Nunito (rounded, friendly)',
    'Ojuju, sans-serif' => 'Ojuju (Afro-grotesque style)',
    'Old Standard TT, serif' => 'Old Standard TT (late 19th and early 20th-century style)',
    'Open Sans, sans-serif' => 'Open Sans (neutral, friendly)',
    'Orbitron, sans-serif' => 'Orbitron (sci-fi interface)',
    'Oswald, sans-serif' => 'Oswald (bold, impactful)',
    'Pacifico, cursive' => 'Pacifico (playful, casual)',
    'Palatino, serif' => 'Palatino (traditional, refined)',
    'Parisienne, cursive' => 'Parisienne (Parisian café)',
    'Passion One, cursive' => 'Passion One (extra-bold, expressive)',
    'Patua One, serif' => 'Patua One (slab-serif, display)',
    'Pirata One, cursive' => 'Pirata One (Jolly Roger skull)',
    'Play, sans-serif' => 'Play (compact, modern)',
    'Playfair Display, serif' => 'Playfair Display (classic, elegant)',
    'Poiret One, cursive' => 'Poiret One (geometric deco)',
    'Poppins, sans-serif' => 'Poppins (geometric, friendly)',
    'Press Start 2P, cursive' => 'Press Start 2P (8-bit arcade)',
    'Prompt, sans-serif' => 'Prompt (rounded, condensed)',
    'Quicksand, sans-serif' => 'Quicksand (light, modern)',
    'Racing Sans One, sans-serif' => 'Racing Sans One (fast, sporty)',
    'Rajdhani, sans-serif' => 'Rajdhani (angular tech)',
    'Raleway, sans-serif' => 'Raleway (elegant, stylish)',
    'Rampart One, cursive' => 'Rampart One (chiseled stone effect)',
    'Ribeye Marrow, cursive' => 'Ribeye Marrow (chalk outline)',
    'Righteous, cursive' => 'Righteous (geometric, unique headings)',
    'Roboto Condensed, sans-serif' => 'Roboto Condensed (modern, approachable)',
    'Roboto, sans-serif' => 'Roboto (modern, approachable)',
    'Rubik Beastly, cursive' => 'Rubik Beastly (monster claws)',
    'Rubik Broken Fax, cursive' => 'Rubik Broken Fax (glitch distortion)',
    'Rubik Glitch, cursive' => 'Rubik Glitch (digital distortion)',
    'Rubik Moonrocks, cursive' => 'Rubik Moonrocks (space texture)',
    'Rubik Vinyl, cursive' => 'Rubik Vinyl (70s funk)',
    'Rubik Wet Paint, cursive' => 'Rubik Wet Paint (dripping ink)',
    'Rubik, sans-serif' => 'Rubik (modern, slightly rounded)',
    'Russo One, sans-serif' => 'Russo One (bold geometry)',
    'Rye, serif' => 'Rye (saloon woodtype)',
    'Sacramento, cursive' => 'Sacramento (brush script)',
    'Saira Condensed, sans-serif' => 'Saira Condensed (modern, condensed)',
    'Saira Extra Condensed, sans-serif' => 'Saira Extra Condensed (extra tight)',
    'Share Tech, sans-serif' => 'Share Tech (clean circuitry)',
    'Slabo 27px, serif' => 'Slabo 27px (modern, slab-serif)',
    'Smokum, serif' => 'Smokum (wanted poster)',
    'Snowburst One, cursive' => 'Snowburst One (crystal shards)',
    'Smythe, serif' => 'Smythe (Arts and Crafts movement-inspired)',
    'Source Sans Pro, sans-serif' => 'Source Sans Pro (clean, reliable)',
    'Space Mono, monospace' => 'Space Mono (retro-futuristic style)',
    'Spectral, serif' => 'Spectral (elegant, modern)',
    'Staatliches, sans-serif' => 'Staatliches (Bauhaus blocks)',
    'Stardos Stencil, serif' => 'Stardos Stencil (circus deco)',
    'Stick, sans-serif' => 'Stick (basic lineart)',
    'Syncopate, sans-serif' => 'Syncopate (negative space)',
    'Tahoma, sans-serif' => 'Tahoma (modern, legible)',
    'Tajawal, sans-serif' => 'Tajawal (clean, modern)',
    'Tangerine, cursive' => 'Tangerine (delicate quill)',
    'Teko, sans-serif' => 'Teko (angular, strong headings)',
    'Times New Roman, serif' => 'Times New Roman (traditional, formal)',
    'Titillium Web, sans-serif' => 'Titillium Web (modern, stylish)',
    'Tourney, sans-serif' => 'Tourney (multiple weights)',
    'Train One, cursive' => 'Train One (railroad tracks)',
    'Trebuchet MS, sans-serif' => 'Trebuchet MS (friendly, modern)',
    'Ubuntu, sans-serif' => 'Ubuntu (humanist, approachable)',
    'Uncial Antiqua, cursive' => 'Uncial Antiqua (ancient manuscript)',
    'UnifrakturMaguntia, cursive' => 'UnifrakturMaguntia (medieval blackletter)',
    'Unica One, sans-serif' => 'Unica One (condensed, clean headings)',
    'Varela Round, sans-serif' => 'Varela Round (rounded, friendly)',
    'Vast Shadow, cursive' => 'Vast Shadow (long drop shadows)',
    'Verdana, sans-serif' => 'Verdana (modern, readable)',
    'VT323, monospace' => 'VT323 (pixel terminal)',
    'Wallpoet, sans-serif' => 'Wallpoet (digital stencil)',
    'Work Sans, sans-serif' => 'Work Sans (technical, clean)',
    'Yanone Kaffeesatz, sans-serif' => 'Yanone Kaffeesatz (clean, light condensed)',
    'Yeseva One, serif' => 'Yeseva One (1920s deco elegance)',
    'Zeyada, cursive' => 'Zeyada (handwritten, casual)',
    'Zilla Slab Highlight, cursive' => 'Zilla Slab Highlight (comic book emphasis)',
    'Zen Tokyo Zoo, cursive' => 'Zen Tokyo Zoo (animal shapes)'
    ];
}


function firefly_allow_font_uploads_for_admins($mimes) {
    if (current_user_can('administrator')) {
        define('ALLOW_UNFILTERED_UPLOADS', true);
        $mimes['ttf']   = 'font/ttf';
        $mimes['woff']  = 'font/woff';
        $mimes['woff2'] = 'font/woff2';
        $mimes['otf']   = 'font/otf';
    }
    return $mimes;
}
add_filter('upload_mimes', 'firefly_allow_font_uploads_for_admins');


function firefly_redirect_404_to_home() {
    if (is_404()) {
        wp_redirect(home_url());
        exit;
    }
}
add_action('template_redirect', 'firefly_redirect_404_to_home');



//=========================================
//for things page
//=========================================

// Add custom URL rewrite rule
// Step 1: Add rewrite rule like /12345/any-slug
add_action('init', function () {
    add_rewrite_rule(
        '^([0-9]+)/[^/]+/?$',
        'index.php?firefly_thing_id=$matches[1]&is_firefly_thing=1',
        'top'
    );
});

// Step 2: Declare custom query vars
add_filter('query_vars', function ($vars) {
    $vars[] = 'firefly_thing_id';
    $vars[] = 'is_firefly_thing';
    return $vars;
});

// Step 3: Intercept and route manually
add_action('template_redirect', function () {
    $thing_id = get_query_var('firefly_thing_id');
    $is_firefly = get_query_var('is_firefly_thing');

    if ($is_firefly && is_numeric($thing_id)) {
        remove_action('template_redirect', 'redirect_canonical');

        $path = get_stylesheet_directory() . '/firefly-thing-display.php';
        if (!file_exists($path)) {
            wp_die("🔥 Template file not found: $path");
        }

        include $path;
        exit;
    }
});


add_action('admin_post_delete_thing', function () {
    if (!current_user_can('manage_options')) {
        wp_die('❌ Unauthorized');
    }

    $post_id = isset($_GET['post_id']) ? intval($_GET['post_id']) : 0;
    if (!$post_id || !wp_verify_nonce($_GET['_wpnonce'], 'delete_thing_' . $post_id)) {
        wp_die('❌ Invalid post ID or nonce');
    }

    $result = wp_update_post([
        'ID' => $post_id,
        'post_status' => 'trash',
    ], true);

    if (is_wp_error($result)) {
        wp_die('❌ Error updating post: ' . $result->get_error_message());
    }

    wp_redirect(wp_get_referer() ?: home_url());
    exit;
});


/* ───────────────────────────────────────────────
 * Show  (publish)
 * ───────────────────────────────────────────── */
add_action( 'admin_post_show_thing', function () {

    if ( ! current_user_can( 'manage_options' ) ) wp_die( '❌ Unauthorized', 403 );

    $id    = absint( $_GET['post_id'] ?? 0 );
    $nonce = $_GET['_wpnonce'] ?? '';

    if ( ! $id || ! wp_verify_nonce( $nonce, 'show_thing_' . $id ) ) {
        wp_die( '❌ Invalid request', 400 );
    }

    wp_update_post( [
        'ID'          => $id,
        'post_status' => 'publish',   // ← must be “publish”
    ] );

    wp_safe_redirect( wp_get_referer() ?: home_url() );
    exit;
} );

/* ───────────────────────────────────────────────
 * Hide (draft)
 * ───────────────────────────────────────────── */
add_action( 'admin_post_hide_thing', function () {

    if ( ! current_user_can( 'manage_options' ) ) wp_die( '❌ Unauthorized', 403 );

    $id    = absint( $_GET['post_id'] ?? 0 );
    $nonce = $_GET['_wpnonce'] ?? '';

    if ( ! $id || ! wp_verify_nonce( $nonce, 'hide_thing_' . $id ) ) {
        wp_die( '❌ Invalid request', 400 );
    }

    wp_update_post( [
        'ID'          => $id,
        'post_status' => 'draft',
    ] );

    wp_safe_redirect( wp_get_referer() ?: home_url() );
    exit;
} );




add_action('admin_post_edit_thing', function () {
    if (!current_user_can('manage_options') || !wp_verify_nonce($_POST['_wpnonce'], 'firefly_edit_thing')) {
        wp_die('Unauthorized');
    }

    $post_id = isset($_POST['thing_id']) ? intval($_POST['thing_id']) : 0;
    $title   = sanitize_text_field($_POST['thing_title'] ?? '');
    $content = wp_kses_post($_POST['thing_content'] ?? '');
    $meta    = $_POST['thing_meta'] ?? [];

    if (!$post_id || !$title) {
        wp_die('Missing required fields');
    }

    // Update the post
    wp_update_post([
        'ID'           => $post_id,
        'post_title'   => $title,
        'post_content' => $content,
    ]);

    // Save meta fields
    foreach ($meta as $key => $value) {
        update_post_meta($post_id, sanitize_key($key), sanitize_text_field($value));
    }

    // Handle image if uploaded
    if (!empty($_FILES['thing_image']) && $_FILES['thing_image']['error'] === UPLOAD_ERR_OK) {
        require_once ABSPATH . 'wp-admin/includes/file.php';
        require_once ABSPATH . 'wp-admin/includes/media.php';
        require_once ABSPATH . 'wp-admin/includes/image.php';

        $attachment_id = media_handle_upload('thing_image', $post_id);
        if (!is_wp_error($attachment_id)) {
            set_post_thumbnail($post_id, $attachment_id);
        }
    }

    $referer = wp_get_referer();
$clean_url = remove_query_arg('edit_thing', $referer);
wp_redirect($clean_url);

    exit;
});





//=========================================
//for things page
//=========================================

// Add custom URL rewrite rule
// Step 1: Add rewrite rule like /12345/any-slug
// Add custom rewrite rule
add_action('init', function () {
    add_rewrite_rule(
        '^([0-9]+)/([^/]+)/([^/]+)/?$',
        'index.php?firefly_thing_id=$matches[1]&firefly_thing_slug=$matches[2]',
        'top'
    );
});

// Register the query vars
add_filter('query_vars', function ($vars) {
    $vars[] = 'firefly_thing_id';
    $vars[] = 'firefly_thing_slug';
    return $vars;
});

// Load template
add_action('template_redirect', function () {
    $thing_id = get_query_var('firefly_thing_id');
    if ($thing_id) {
        $template = get_stylesheet_directory() . '/firefly-thing-display.php';
        if (file_exists($template)) {
            include $template;
            exit;
        }
    }
});





add_action('wp_ajax_firefly_remove_gallery_image', 'firefly_ajax_remove_gallery_image');

function firefly_ajax_remove_gallery_image() {
    error_log('🔥 AJAX handler triggered');

    // Permission check
    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => 'Unauthorized']);
    }

    // Nonce check
    if (!check_ajax_referer('firefly_gallery_nonce', '_wpnonce', false)) {
        wp_send_json_error(['message' => 'Invalid nonce']);
    }

    // Post/image data
    $post_id = absint($_POST['post_id'] ?? 0);
    $img_id  = absint($_POST['img_id'] ?? 0);
    if (!$post_id || !$img_id) {
        wp_send_json_error(['message' => 'Missing data']);
    }

    $gallery = get_post_meta($post_id, 'thing_gallery', true);
    if (!is_array($gallery)) $gallery = [];

    $updated_gallery = array_values(array_diff($gallery, [$img_id]));
    $success = update_post_meta($post_id, 'thing_gallery', $updated_gallery);

    if (!$success) {
        wp_send_json_error(['message' => 'Meta update failed']);
    }

    // Optionally delete image
    if (get_post($img_id) && wp_attachment_is_image($img_id)) {
        wp_delete_attachment($img_id, true);
    }

    wp_send_json_success(['message' => 'Deleted']);
}



add_action('wp_ajax_firefly_add_gallery_images', function () {
    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => 'Unauthorized']);
    }

    if (!check_ajax_referer('firefly_gallery_nonce', '_wpnonce', false)) {
        wp_send_json_error(['message' => 'Invalid nonce']);
    }

    $post_id = absint($_POST['post_id'] ?? 0);
    $images = json_decode(stripslashes($_POST['images'] ?? '[]'), true);
    if (!$post_id || empty($images) || !is_array($images)) {
        wp_send_json_error(['message' => 'Invalid data']);
    }

    $gallery = get_post_meta($post_id, 'thing_gallery', true);
    if (!is_array($gallery)) $gallery = [];

    $upload_dir = wp_upload_dir();
    foreach ($images as $base64_image) {
        if (preg_match('/^data:image\/(\w+);base64,/', $base64_image, $match)) {
            $img_data = base64_decode(substr($base64_image, strpos($base64_image, ',') + 1));
            $ext = strtolower($match[1]);
            $filename = 'thing_' . uniqid() . '.' . $ext;
            $file_path = $upload_dir['path'] . '/' . $filename;
            file_put_contents($file_path, $img_data);

            $attachment_id = wp_insert_attachment([
                'post_mime_type' => 'image/' . $ext,
                'post_title' => sanitize_file_name($filename),
                'post_status' => 'inherit',
                'post_parent' => $post_id,
                'guid' => $upload_dir['url'] . '/' . $filename,
            ], $file_path);

            require_once ABSPATH . 'wp-admin/includes/image.php';
            $attach_data = wp_generate_attachment_metadata($attachment_id, $file_path);
            wp_update_attachment_metadata($attachment_id, $attach_data);

            $gallery[] = $attachment_id;
        }
    }

    update_post_meta($post_id, 'thing_gallery', $gallery);
    wp_send_json_success(['message' => 'Images added']);
});



/**
 * Show full post-meta + image data for a given post.
 * URL: /wp-admin/admin-post.php?action=show_thing_meta&post_id=123&_wpnonce=XXXX
 */
function firefly_show_thing_meta() {
    // ----- security -------------------------------------------------------
    $post_id = isset( $_GET['post_id'] ) ? (int) $_GET['post_id'] : 0;
    if ( ! $post_id || ! wp_verify_nonce( $_GET['_wpnonce'] ?? '', 'show_meta_' . $post_id ) ) {
        wp_die( 'Sorry, that link is no longer valid.' );
    }

    // ----- collect data ---------------------------------------------------
    $out  = [];
    $out['Post ID']          = $post_id;
    $out['Title']            = get_the_title( $post_id );
    $out['Permalink']        = get_permalink( $post_id );
    $out['Post Status']      = get_post_status( $post_id );
    $out['All Meta']         = get_post_meta( $post_id );
    $out['Featured Image']   = wp_get_attachment_url( get_post_thumbnail_id( $post_id ) );
    $out['Gallery Images']   = get_post_meta( $post_id, 'thing_gallery', true ); // adapt if your key is different

    // ----- output ---------------------------------------------------------
    header( 'Content-Type: text/plain; charset=utf-8' );
    print_r( $out );
    exit;
}
add_action( 'admin_post_nopriv_show_thing_meta', 'firefly_show_thing_meta' );
add_action( 'admin_post_show_thing_meta',       'firefly_show_thing_meta' );



add_filter( 'post_thumbnail_html', function( $html, $post_id, $post_thumbnail_id, $size, $attr ) {

    // Only apply when thumbnails are set to "no"
    if ( get_theme_mod( 'my_plugin_show_post_thumbnails', 'no' ) === 'no' ) {

        // Only on singular Pages
        if ( is_singular( 'page' ) ) {

            // If this is NOT one of our childpage-thumb images, strip it out
            if ( empty( $attr['class'] ) || false === strpos( $attr['class'], 'childpage-thumb' ) ) {
                return '';
            }
        }
    }

    return $html;

}, 10, 5 );




// add default colours to edit a page colour pallets

add_action( 'after_setup_theme', 'firefly_register_editor_colors' );
function firefly_register_editor_colors() {
    $colors = [];

    $custom_colors = [
        'firefly-colour-1' => get_theme_mod('firefly_colour_1', '#FF5733'),
        'firefly-colour-2' => get_theme_mod('firefly_colour_2', '#33C3FF'),
        'firefly-colour-3' => get_theme_mod('firefly_colour_3', '#33C3FF'),
        'firefly-colour-4' => get_theme_mod('firefly_colour_4', '#33C3FF'),
        'darkgrey' => '#545454ff',
        'mediumgrey' => '#8d8c8cff',
        'lightgrey' => '#c3c3c3ff',
        'black' => '#000000ff',
        'white' => '#ffffffff',
        // Add more from your Customizer
    ];

    foreach ( $custom_colors as $slug => $color ) {
        $colors[] = [
            'name'  => ucwords( str_replace( '-', ' ', $slug ) ),
            'slug'  => $slug,
            'color' => $color,
        ];
    }

    add_theme_support( 'editor-color-palette', $colors );
}


// including patters in the firefly/patterns folder
// ✅ Adds multiple custom "Firefly" pattern categories
add_action('init', function() {
    $categories = [
        'firefly' => __( 'Firefly', 'your-theme-textdomain' ),
        'firefly-heading-text-colored' => __( '1. Firefly heading and text over coloured background', 'your-theme-textdomain' ),
        'firefly-text-bg-image'        => __( '2. Firefly text over background image', 'your-theme-textdomain' ),
        'firefly-animated-text-bg'     => __( '3. Firefly animated text over background image', 'your-theme-textdomain' ),
        'blocksy'     => __( 'Blocksy', 'your-theme-textdomain' ),
    ];

    $registry = WP_Block_Pattern_Categories_Registry::get_instance();

    foreach ( $categories as $slug => $label ) {
        if ( ! $registry->is_registered( $slug ) ) {
            register_block_pattern_category( $slug, [ 'label' => $label ] );
        }
    }
});


// get custom patters in firefly/patterns folder

add_action('init', function () {
    if (!is_user_logged_in() || !current_user_can('edit_theme_options')) {
        return;
    }

    $pattern_dir = get_stylesheet_directory() . '/patterns';

    foreach (glob($pattern_dir . '/*.php') as $file) {
        register_block_pattern(
            'firefly/' . basename($file, '.php'),
            include $file
        );
    }
});



// go live checklist

// Handle "Mark done" (works in admin + front end)
add_action('admin_init',        'firefly_gl_handle_actions');
add_action('template_redirect', 'firefly_gl_handle_actions');

function firefly_gl_handle_actions() {
    if (!is_user_logged_in() || !current_user_can('manage_options')) return;

    // Mark single item done: ?gl_done={key}&_wpnonce=...
    if (isset($_GET['gl_done'], $_GET['_wpnonce'])) {
        $key = sanitize_key($_GET['gl_done']);
        if (wp_verify_nonce($_GET['_wpnonce'], 'gl_done_' . $key)) {
            set_theme_mod('go_live_done_' . $key, 1);
            wp_safe_redirect(remove_query_arg(['gl_done','_wpnonce']));
            exit;
        }
    }
}

// Helper to build "Mark done" link
function firefly_gl_mark_done_link($key) {
    return wp_nonce_url(add_query_arg('gl_done', $key), 'gl_done_' . $key);
}




/**
 * ff_debug_icon
 * Usage:
 *    ff_debug_icon(__FILE__, __LINE__, 'optional message');
 */
function ff_debug_icon($caller_file, $caller_line, $message = '') {
    // Respect optional global toggle (if you use it elsewhere)
    if (isset($GLOBALS['showadminmenus']) && empty($GLOBALS['showadminmenus'])) {
        return;
    }

    // Only show to the specified user/email
    if (!is_user_logged_in()) return;
    $u = wp_get_current_user();
    if (!$u || ($u->user_login !== 'rainbowdev' && $u->user_email !== 'drjeffsimmonds@gmail.com')) {
        return;
    }

    // One-time CSS (avoid duplicating styles for multiple instances)
    static $ffdbg_css_done = false;
    if (!$ffdbg_css_done) {
        $ffdbg_css_done = true;
        ?>
        <style>
            .ff-debug-icon { display:inline-block; vertical-align:middle; margin-left:6px; cursor:pointer;margin-right:10px;margin-top:10px; }
            .ff-debug-details {
                display:none; position:absolute; z-index:99999; right:0; top:28px;
                padding:10px 12px; background:#111; color:#fff; bbbborder-radius:8px;
                box-shadow:0 6px 24px rgba(0,0,0,.3); max-width:90vw;
                font:12px/1.5 system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif;
            }
            .ff-debug-details code { background:#222; padding:2px 4px; bbbborder-radius:4px; }
            .ff-debug-wrap { position:relative; float:right; margin-left:8px; }
            .ff-debug-close { float:right; font-size:12px; color:#ccc; text-decoration:none; margin-left:8px; }
            .ff-debug-close:hover { color:#fff; }
            .ff-debug-summary { margin:0 0 8px; font-weight:600; }
        </style>
        <?php
    }

    // Build nice labels/paths
    $full_path = $caller_file;
    $file_name = basename($caller_file);

    $where    = 'Unknown';
    $relative = $full_path;
    $root     = '';

    if (defined('WPMU_PLUGIN_DIR') && strpos($full_path, WPMU_PLUGIN_DIR) === 0) {
        $where    = 'Must-Use Plugin';
        $root     = rtrim(WPMU_PLUGIN_DIR, '/');
        $relative = ltrim(str_replace($root, '', $full_path), '/');
    } elseif (strpos($full_path, WP_PLUGIN_DIR) === 0) {
        $where    = 'Plugin';
        $root     = rtrim(WP_PLUGIN_DIR, '/');
        $relative = ltrim(str_replace($root, '', $full_path), '/');
    } elseif (strpos($full_path, get_theme_root()) === 0) {
        $where    = 'Theme';
        $root     = rtrim(get_theme_root(), '/');
        $relative = ltrim(str_replace($root, '', $full_path), '/');
    } elseif (strpos($full_path, WP_CONTENT_DIR) === 0) {
        $where    = 'wp-content';
        $root     = rtrim(WP_CONTENT_DIR, '/');
        $relative = ltrim(str_replace($root, '', $full_path), '/');
    }

    $bits = explode('/', $relative);
    $top_folder = !empty($bits[0]) ? $bits[0] : '';

    // Unique IDs for this instance
    $uid = 'ffdbg_' . substr(md5($caller_file . '|' . $caller_line . '|' . microtime(true)), 0, 10);
    $icon_id  = $uid . '_icon';
    $panel_id = $uid . '_panel';
    $close_id = $uid . '_close';
    ?>

    <span class="ff-debug-wrap ff-debug-wrap-instance" id="<?php echo esc_attr($uid); ?>">
        <span id="<?php echo esc_attr($icon_id); ?>" class="ff-debug-icon dashicons dashicons-admin-tools" aria-label="Debug info" title="Show debug info"></span>
        <div id="<?php echo esc_attr($panel_id); ?>" class="ff-debug-details" role="dialog" aria-label="Debug info">
            <a href="#" id="<?php echo esc_attr($close_id); ?>" class="ff-debug-close" aria-label="Close">✕</a>
            <div class="ff-debug-summary">Debug info</div>
            <?php if ($message) : ?>
                <div><strong>Note:</strong> <?php echo esc_html($message); ?></div>
            <?php endif; ?>
            <div>This is <strong>line <?php echo intval($caller_line); ?></strong> on <strong><?php echo esc_html($file_name); ?></strong>.</div>
            <div>Scope: <strong><?php echo esc_html($where); ?></strong><?php echo $top_folder ? ' — <em>'.esc_html($top_folder).'</em>' : ''; ?></div>
            <div>Relative: <code><?php echo esc_html($relative); ?></code></div>
            <div>Full path: <code><?php echo esc_html($full_path); ?></code></div>
        </div>
    </span>

    <script>
    (function(){
        var icon  = document.getElementById('<?php echo esc_js($icon_id); ?>');
        var panel = document.getElementById('<?php echo esc_js($panel_id); ?>');
        var close = document.getElementById('<?php echo esc_js($close_id); ?>');
        if (!icon || !panel) return;

        icon.addEventListener('click', function(e){
            e.preventDefault();
            e.stopPropagation();
            panel.style.display = (panel.style.display === 'block') ? 'none' : 'block';
        });

        if (close) {
            close.addEventListener('click', function(e){
                e.preventDefault();
                e.stopPropagation();
                panel.style.display = 'none';
            });
        }

        // Click outside to close (instance-scoped)
        document.addEventListener('click', function(e){
            if (!panel.contains(e.target) && e.target !== icon) {
                panel.style.display = 'none';
            }
        });
    })();
    </script>
    <?php
}





//========================================================================
 // ff_debug_icon(__FILE__, __LINE__, 'Top of course categories page');
//========================================================================


// delete a page

add_action( 'template_redirect', function () {

    if ( empty( $_GET['ff_trash_page'] ) || ! is_singular() ) {
        return;
    }

    $post_id = (int) $_GET['ff_trash_page'];

    // Security checks
    if ( ! is_user_logged_in() || ! current_user_can( 'delete_page', $post_id ) ) {
        wp_die( 'You do not have permission to delete this page.' );
    }

    $nonce = isset( $_GET['_wpnonce'] ) ? sanitize_text_field( wp_unslash( $_GET['_wpnonce'] ) ) : '';
    if ( ! wp_verify_nonce( $nonce, 'ff_trash_page_' . $post_id ) ) {
        wp_die( 'Security check failed.' );
    }

    // Move to Trash (kept in DB, restorable from Pages → Trash)
    wp_trash_post( $post_id );

    // Redirect somewhere sensible – home, or an admin page, etc.
    wp_redirect( home_url( '/' ) );
    exit;
} );




/**
 * Handle ?ff_show_raw=1 and ?ff_show_css=1
 */
function firefly_export_page_template_redirect() {
    if ( ! is_singular() ) {
        return;
    }

    // Nothing to do if neither flag is present
    if ( ! isset( $_GET['ff_show_raw'] ) && ! isset( $_GET['ff_show_css'] ) ) {
        return;
    }

    // Security: only logged-in users with edit capability
    if ( ! is_user_logged_in() || ! current_user_can( 'edit_pages' ) ) {
        wp_die( 'You do not have permission to view this.' );
    }

    global $post;

    if ( ! $post instanceof WP_Post ) {
        wp_die( 'No post found.' );
    }

    // --- RAW CONTENT --------------------------------------------------------
    if ( isset( $_GET['ff_show_raw'] ) ) {
        nocache_headers();
        header( 'Content-Type: text/plain; charset=utf-8' );

      //  echo "RAW CONTENT FOR POST ID {$post->ID}\n";
      //  echo "-----------------------------------------\n\n";
        echo $post->post_content;

        exit;
    }

    // --- RAW CSS ------------------------------------------------------------
    if ( isset( $_GET['ff_show_css'] ) ) {

        // Capture what wp_head() outputs just for this request
        ob_start();
        /**
         * Calling wp_head() here is safe because:
         * - It normally runs later in the template.
         * - We will exit before rendering the template, so it's not called twice.
         */
        wp_head();
        $head_output = ob_get_clean();

        // Prepare plain text response
        nocache_headers();
        header( 'Content-Type: text/plain; charset=utf-8' );

     //   echo "CSS FOR PAGE ID {$post->ID}\n";
      //  echo "-----------------------------------------\n\n";

        // 1) Inline <style> blocks
        if ( preg_match_all( '/<style[^>]*>(.*?)<\/style>/is', $head_output, $style_matches ) ) {
            foreach ( $style_matches[1] as $css_block ) {
                $css_block = trim( $css_block );
                if ( $css_block !== '' ) {
                    echo $css_block . "\n\n";
                }
            }
        }

        // 2) Linked stylesheets (URLs)
    if ( preg_match_all( '/<link[^>]+rel=["\']stylesheet["\'][^>]*>/i', $head_output, $link_matches ) ) {

    echo "\n\n==============================\n";
    echo " LINKED STYLESHEETS (INLINE)\n";
    echo "==============================\n\n";

    foreach ( $link_matches[0] as $tag ) {

        if ( preg_match( '/href=["\']([^"\']+)["\']/', $tag, $href_match ) ) {

            $href = $href_match[1];

            // Convert relative links to absolute
            if ( strpos( $href, '//' ) === 0 ) {
                $href = ( is_ssl() ? 'https:' : 'http:' ) . $href;
            } elseif ( strpos( $href, '/' ) === 0 ) {
                $href = site_url( $href );
            } elseif ( ! preg_match( '#^https?://#', $href ) ) {
                $href = site_url( '/' . ltrim( $href, '/' ) );
            }

            echo "\n--- $href ---\n";

            // Fetch CSS
            $response = wp_remote_get( $href, [ 'timeout' => 8 ] );

            if ( is_wp_error( $response ) ) {
                echo "Error loading CSS: " . $response->get_error_message() . "\n";
                continue;
            }

            $css = wp_remote_retrieve_body( $response );

            if ( empty( $css ) ) {
                echo "No content returned.\n";
            } else {
                echo $css . "\n";
            }
        }
    }
}


        exit;
    }
} 
add_action( 'template_redirect', 'firefly_export_page_template_redirect' ); 


