<?php
/**
 * Image Style Controls with Links
 * Adds admin controls to images without breaking layout
 */
   // Check if picture admin links are enabled in Customizer
        if (!get_theme_mod('my_plugin_show_picture_admin_links')) {
            return;
        }

// Process form submission
if (isset($_POST['ff_update_style']) && current_user_can('administrator')) {


     

    // Get and validate data
    $post_id = isset($_POST['post_id']) ? absint($_POST['post_id']) : 0;
    $img_num = isset($_POST['img_num']) ? absint($_POST['img_num']) : 0;
    $style = isset($_POST['style']) ? sanitize_text_field($_POST['style']) : '';
    $return_url = isset($_POST['return_url']) ? esc_url_raw($_POST['return_url']) : '';
    
    if ($post_id && $style) {
        // Get the post
        $post = get_post($post_id);
        if ($post) {
            $content = $post->post_content;
            
            // Find all image blocks
            preg_match_all('/<figure\s+class="[^"]*"[^>]*>.*?<img[^>]*>.*?<\/figure>/is', $content, $matches);
            
            // Check if we found the target image block
            if (isset($matches[0][$img_num])) {
                $figure_tag = $matches[0][$img_num];
                
                // Extract class attribute
                preg_match('/class="([^"]*)"/i', $figure_tag, $class_matches);
                
                if (!empty($class_matches)) {
                    // Remove any existing style classes
                    $current_classes = $class_matches[1];
                    $cleaned_classes = preg_replace('/\bis-style-[\w-]+\b\s*/', '', $current_classes);
                    $new_classes = trim($cleaned_classes . ' ' . $style);
                    
                    // Replace class in figure tag
                    $new_figure = str_replace(
                        'class="' . $current_classes . '"',
                        'class="' . $new_classes . '"',
                        $figure_tag
                    );
                    
                    // Update content
                    $new_content = str_replace($figure_tag, $new_figure, $content);
                    
                    // Save updated content
                    wp_update_post([
                        'ID' => $post_id,
                        'post_content' => $new_content
                    ]);
                }
            }
        }
    }
    
    // Redirect handling
    if (!empty($return_url)) {
        $redirect_to = $return_url;
    } else if (!empty($_SERVER['HTTP_REFERER'])) {
        $redirect_to = $_SERVER['HTTP_REFERER'];
    } else {
        $redirect_to = get_permalink($post_id);
    }
    
    // Add success indicator
    $redirect_to = add_query_arg('styled', '1', $redirect_to);
    
    // Ultra-reliable HTML redirect
    echo '<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0;url=' . esc_url($redirect_to) . '">
    <title>Redirecting...</title></head><body><p>Style updated! Redirecting you back...</p>
    <script>window.location.href = "' . esc_js($redirect_to) . '";</script></body></html>';
    exit;
}

// Add styling and initialize the JavaScript
add_action('wp_footer', function() {
    // Only for administrators
    if (!current_user_can('administrator')) {
        return;
    }
    
    // Add success message handling
    if (isset($_GET['styled']) && $_GET['styled'] === '1') {
        echo '<div id="ff-message" style="display:block;">Style updated!</div>';
        echo '<script>
            setTimeout(function() {
                document.getElementById("ff-message").style.display = "none";
                // Clean up URL
                const cleanUrl = window.location.href.replace(/[?&]styled=1/, "");
                if (cleanUrl !== window.location.href) {
                    history.replaceState({}, document.title, cleanUrl);
                }
            }, 3000);
        </script>';
    }
    
    // Add styles for the controls
    ?>
    <style>
    /* Success message */
    #ff-message {
        position: fixed;
        bottom: 20px;
        right: 20px;
        background: #00a32a;
        color: white;
        padding: 10px 20px;
        border-radius: 6px;
        font-size: 14px;
        display: none;
        z-index: 9999;
        box-shadow: 0 2px 5px rgba(0,0,0,0.2);
    }


    /* Fix alignment for centered images */
.wp-block-image.is-style-centered-image {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.wp-block-image.is-style-centered-image .firefly-admin-1-no-margin {
    align-self: center;
   
}


  </style>
    <?php
    global $post;
    if (!$post) return;
    
    // Parse blocks to get indices
    $blocks = parse_blocks($post->post_content);
    
    // Find image block indices
    $image_indices = [];
    foreach ($blocks as $index => $block) {
        if ($block['blockName'] === 'core/image') {
            $image_indices[] = $index;
        }
    }
    
    // Current page URL for form return
    $current_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
    ?>
    
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Get image block indices from PHP
        const imageIndices = <?php echo json_encode($image_indices); ?>;
        
        // Define styles
        const styles = [
            { label: '50% right', class: 'is-style-fifty-width' },
            { label: '33% right', class: 'is-style-33-width' },
            { label: 'full width', class: 'is-style-full-width-image' },
            { label: 'almost full', class: 'is-style-almost-full-width-image' },
            { label: 'centered', class: 'is-style-centered-image' }
        ];
        
        // Find all image blocks
        const imageBlocks = document.querySelectorAll('.wp-block-image');
        
        // Add admin controls to each image block
        imageBlocks.forEach(function(block, index) {


    // ❌ Skip if already processed
    if (block.querySelector('.firefly-admin-1-no-margin')) return;

    // ❌ Skip if inside a newsletter
    if (block.closest('.newsletter-container')) return;

            // Skip if already processed
            if (block.querySelector('.firefly-admin-1-no-margin')) return;
            
            // Get the corresponding block index
            const blockIndex = (index < imageIndices.length) ? imageIndices[index] : -1;
            
            // Create delete and move URLs
            const deleteUrl = '<?php echo add_query_arg(['delete_block' => '1', 'block_type' => 'image', 'block_index' => ''], $_SERVER['REQUEST_URI']); ?>' + blockIndex;
            const moveUpUrl = '<?php echo add_query_arg(['move_up' => '1', 'block_type' => 'image', 'block_index' => ''], $_SERVER['REQUEST_URI']); ?>' + blockIndex;
            const moveDownUrl = '<?php echo add_query_arg(['move_down' => '1', 'block_type' => 'image', 'block_index' => ''], $_SERVER['REQUEST_URI']); ?>' + blockIndex;
            
            // Create the admin container
            const adminContainer = document.createElement('div');
            adminContainer.className = 'firefly-admin-1-no-margin';
            
            // Create the header
            const header = document.createElement('div');
            header.className = 'firefly-admin-2';
            header.textContent = 'Image options';
            
            // Create the content div
            const content = document.createElement('div');
            content.className = 'firefly-admin-3';
            
            // Add operation links
            content.innerHTML = 
                '<a href="' + deleteUrl + '" onclick="return confirm(\'Are you sure you want to delete this picture?\');" class="firefly-admin-link">Delete this picture</a> | ';
            
            // Determine the active style
            let activeStyle = '';
            styles.forEach(function(style) {
                if (block.classList.contains(style.class)) {
                    activeStyle = style.class;
                }
            });
            
            // Add style options
            styles.forEach(function(style, i) {
                // Add separator except for first item
                if (i > 0) {
                    content.innerHTML += ' | ';
                }
                
                if (style.class === activeStyle) {
                    // Active style
                    content.innerHTML += '<span class="firefly-admin-link"><B>' + style.label + '</B></span>';
                } else {
                    // Create form for style change
                    content.innerHTML += 
                        '<form method="post" target="_self" style="display: inline;" class="firefly-admin-link">' +
                        '<input type="hidden" name="ff_update_style" value="1">' +
                        '<input type="hidden" name="post_id" value="<?php echo get_the_ID(); ?>">' +
                        '<input type="hidden" name="img_num" value="' + index + '">' +
                        '<input type="hidden" name="style" value="' + style.class + '">' +
                        '<input type="hidden" name="return_url" value="<?php echo esc_js($current_url); ?>">' +
                        '<a href="#" onclick="event.preventDefault(); this.parentNode.submit();">' + style.label + '</a>' +
                        '</form>';
                }
            });
            
            // Assemble the controls
            adminContainer.appendChild(header);
            adminContainer.appendChild(content);
            
            // Insert controls before the image block
            block.insertBefore(adminContainer, block.firstChild);
        });
    });
    </script>
    <?php
}, 30);
?>