<?php
//define('WP_DEBUG', true);
//define('WP_DEBUG_LOG', true);
//define('WP_DEBUG_DISPLAY', true);
//@ini_set('display_errors', 1);

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


if (!function_exists('firefly_customizer_gallery')) {
    function firefly_customizer_gallery($wp_customize) {
        // Add section
        $wp_customize->add_section('firefly_gallery_section', array(
            'title'       => __('Firefly Gallery', 'firefly'),
            'priority'    => 35,
            'description' => __('Customize gallery spacing and background.', 'firefly'),
        ));

        // Margin and padding choices
        $spacing_choices = [];
        foreach ([0, 1, 2, 3, 4, 5, 10, 15, 20, 25, 30, 35, 40] as $val) {
            $spacing_choices["{$val}px"] = "{$val}px";
        }

        // Margin Top
        $wp_customize->add_setting('firefly_gallery_margin_top', array(
            'default'           => '40px',
            'sanitize_callback' => 'sanitize_text_field',
        ));
        $wp_customize->add_control('firefly_gallery_margin_top', array(
            'label'    => __('Space Above (margin-top)', 'firefly'),
            'section'  => 'firefly_gallery_section',
            'type'     => 'select',
            'choices'  => $spacing_choices,
        ));

        // Margin Bottom
        $wp_customize->add_setting('firefly_gallery_margin_bottom', array(
            'default'           => '40px',
            'sanitize_callback' => 'sanitize_text_field',
        ));
        $wp_customize->add_control('firefly_gallery_margin_bottom', array(
            'label'    => __('Space Below (margin-bottom)', 'firefly'),
            'section'  => 'firefly_gallery_section',
            'type'     => 'select',
            'choices'  => $spacing_choices,
        ));

        // Padding Top
     


        // 1) Build your max-width choices
$gallery_width_choices = [
    '100%'  => __( 'Full width', 'firefly' ),
];
// from 1800px down to 900px in 100px steps
for ( $w = 1800; $w >= 900; $w -= 100 ) {
    $gallery_width_choices["{$w}px"] = "{$w}px";
}

// 2) Register the setting
$wp_customize->add_setting( 'firefly_gallery_max_width', [
    'default'           => '100%',
    'sanitize_callback' => 'sanitize_text_field',
    'transport'         => 'refresh',
] );

// 3) Register the control
$wp_customize->add_control( 'firefly_gallery_max_width', [
    'label'    => __( 'Max Width of Gallery', 'firefly' ),
    'section'  => 'firefly_gallery_section',
    'type'     => 'select',
    'choices'  => $gallery_width_choices,
] );

        // Colour choices
        $colour_choices = array(
            'colour1' => array('color' => get_theme_mod('firefly_colour_1', '#dd3333'), 'label' => 'Colour 1'),
            'colour2' => array('color' => get_theme_mod('firefly_colour_2', '#1e73be'), 'label' => 'Colour 2'),
            'colour3' => array('color' => get_theme_mod('firefly_colour_3', '#8224e3'), 'label' => 'Colour 3'),
            'colour4' => array('color' => get_theme_mod('firefly_colour_4', '#ededc4'), 'label' => 'Colour 4'),
            'white'   => array('color' => '#ffffff', 'label' => 'White'),
            'black'   => array('color' => '#000000', 'label' => 'Black'),
        );


        if (1==2) {
        // Background colour
        $wp_customize->add_setting('firefly_gallery_background', array(
            'default'           => 'white',
            'sanitize_callback' => 'sanitize_text_field',
        ));

        $wp_customize->add_control(new Firefly_Radio_Colour_Control_Text(
            $wp_customize,
            'firefly_gallery_background_control',
            array(
                'label'       => __('Background Colour', 'firefly'),
                'section'     => 'firefly_gallery_section',
                'settings'    => 'firefly_gallery_background',
                'choices'     => $colour_choices,
                'description' => __('Choose a background colour for your gallery.', 'firefly'),
            )
        ));
    }
    }
    add_action('customize_register', 'firefly_customizer_gallery');
}


add_action('wp_head', function () {
    $margin_top    = get_theme_mod('firefly_gallery_margin_top', '40px');
    $margin_bottom = get_theme_mod('firefly_gallery_margin_bottom', '40px');

    $max_gallery_width = get_theme_mod( 'firefly_gallery_max_width', '100%' );
    $bg_key = get_theme_mod('firefly_gallery_background', 'white');

     $padding_lr   = get_theme_mod('my_plugin_padding_lr', '15px');
    $content_choice = get_theme_mod('layout_content_color_choice', 'white');

    $bg_colour = match ($bg_key) {
        'colour1' => get_theme_mod('firefly_colour_1', '#dd3333'),
        'colour2' => get_theme_mod('firefly_colour_2', '#1e73be'),
        'colour3' => get_theme_mod('firefly_colour_3', '#8224e3'),
        'colour4' => get_theme_mod('firefly_colour_4', '#ededc4'),
        'black'   => '#000000',
        default   => '#ffffff',
    };

    $content_color = isset($colours[$content_choice]) ? $colours[$content_choice] : '#ffffff';

    echo "<style>
        .foogallery {
            margin:0 auto !important;
            margin-top: {$margin_top} !important;
            margin-bottom: {$margin_bottom} !important;
          border-left:solid {$content_color} {$padding_lr};
           border-right:solid {$content_color} {$padding_lr};
              padding:0px !important;
alex:alex;
            max-width:{$max_gallery_width} !important;
        }
		
		 .foogallery img { 
			max-width:100% !important;
		}
		
		.fg-item {
			max-width:92% !important;
		}
		

  
    </style>";
});








function firefly_handle_gallery_upload_late() {
    // Start output buffering to capture any errors
    ob_start();
    
    try {
        // Check permissions and nonce
        if (!current_user_can('manage_options')) {
            throw new Exception('Error: Insufficient permissions');
        }
        
        if (!isset($_POST['_wpnonce']) || !wp_verify_nonce($_POST['_wpnonce'], 'firefly_add_gallery_image')) {
            throw new Exception('Error: Invalid nonce check');
        }
        
        $page_id = isset($_POST['page_id']) ? intval($_POST['page_id']) : 0;
        if ($page_id <= 0) {
            throw new Exception('Error: Invalid page ID: ' . (isset($_POST['page_id']) ? $_POST['page_id'] : 'not set'));
        }
        
        // Use the direct gallery ID if provided
        $gallery_id = isset($_POST['direct_gallery_id']) && !empty($_POST['direct_gallery_id']) ? 
            intval($_POST['direct_gallery_id']) : 293; // Hardcoded to 293 for now
        
        $gallery_post = get_post($gallery_id);
        if (!$gallery_post || $gallery_post->post_type !== 'foogallery') {
            throw new Exception('Error: Invalid gallery ID: ' . $gallery_id);
        }
        
        // Check file upload
        if (!isset($_FILES['gallery_image'])) {
            throw new Exception('Error: No file uploaded');
        }
        
        if ($_FILES['gallery_image']['error'] !== UPLOAD_ERR_OK) {
            $error_codes = [
                UPLOAD_ERR_INI_SIZE => 'File exceeds upload_max_filesize directive',
                UPLOAD_ERR_FORM_SIZE => 'File exceeds MAX_FILE_SIZE directive',
                UPLOAD_ERR_PARTIAL => 'File was only partially uploaded',
                UPLOAD_ERR_NO_FILE => 'No file was uploaded',
                UPLOAD_ERR_NO_TMP_DIR => 'Missing temporary folder',
                UPLOAD_ERR_CANT_WRITE => 'Failed to write file to disk',
                UPLOAD_ERR_EXTENSION => 'A PHP extension stopped the upload'
            ];
            $error_message = isset($error_codes[$_FILES['gallery_image']['error']]) ? 
                $error_codes[$_FILES['gallery_image']['error']] : 'Unknown upload error';
            throw new Exception('Error: ' . $error_message);
        }
        
        // Make sure we have the required WordPress files
        require_once(ABSPATH . 'wp-admin/includes/image.php');
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once(ABSPATH . 'wp-admin/includes/media.php');
        
        // Handle the upload - set the proper parent to the gallery
        $attachment_id = media_handle_upload('gallery_image', $gallery_id);
        
        if (is_wp_error($attachment_id)) {
            throw new Exception('Error: Image upload error: ' . $attachment_id->get_error_message());
        }
        
        // Save caption if provided
        if (!empty($_POST['gallery_caption'])) {
            wp_update_post([
                'ID' => $attachment_id,
                'post_excerpt' => sanitize_text_field($_POST['gallery_caption']),
            ]);
        }
        
        // Set the proper post parent - this is important for FooGallery
        wp_update_post([
            'ID' => $attachment_id,
            'post_parent' => $gallery_id
        ]);
        
        // Generate all image sizes
        $attached_file = get_attached_file($attachment_id);
        if ($attached_file) {
            $metadata = wp_generate_attachment_metadata($attachment_id, $attached_file);
            wp_update_attachment_metadata($attachment_id, $metadata);
        }
        
        // Get existing attachments in FooGallery format
        $attachments = get_post_meta($gallery_id, FOOGALLERY_META_ATTACHMENTS, true);
        if (!is_array($attachments)) {
            $attachments = array();
        }
        
        // Add the new attachment to the list (if not already there)
        if (!in_array($attachment_id, $attachments)) {
            $attachments[] = $attachment_id;
            
            // Update both required meta fields
            update_post_meta($gallery_id, FOOGALLERY_META_ATTACHMENTS, $attachments);
            // Force update data_attachments too (sometimes this is used)
            update_post_meta($gallery_id, '_foogallery_data_attachments', $attachments);
        }
        
        // Clear all caches
        delete_post_meta($gallery_id, '_foogallery_gallery_hash');
        delete_post_meta($gallery_id, '_foogallery_rendered');
        delete_transient('foogallery_cache_' . $gallery_id);
        
        // Set last updated timestamp
        update_post_meta($gallery_id, '_foogallery_last_refresh', time());
        
        // Fire FooGallery actions (which might be used for cache clearing or thumbnails)
        if (has_action('foogallery_attachment_added_to_gallery')) {
            do_action('foogallery_attachment_added_to_gallery', $attachment_id, $gallery_id);
        }
        
        if (has_action('foogallery_gallery_updated')) {
            do_action('foogallery_gallery_updated', $gallery_id);
        }
        
        // Clear any output buffer content
        ob_end_clean();
        
        // Redirect back to the gallery page
        wp_redirect(get_permalink($page_id));
        exit;
        
    } catch (Exception $e) {
        $debug_output = ob_get_clean();
        echo "<h1>Error Occurred</h1>";
        echo "<p><strong>" . $e->getMessage() . "</strong></p>";
        echo "<p><a href='javascript:history.back()'>Go back</a></p>";
        exit;
    }
}
// Register the admin-post action handler
add_action('admin_post_firefly_add_gallery_image', 'firefly_handle_gallery_upload_late');




//----------------------------------------------
// DELETE LINK
//----------------------------------------------

// Add this function to your theme's functions.php or your plugin file
function add_foogallery_admin_controls() {
    

    if (!get_theme_mod('my_plugin_show_gallery_admin_links')) {
        return;
    }


    // Only proceed if user is an admin
    if (!current_user_can('manage_options')) {
        return;
    }
    
    ?>
    <style>
        .foogallery-admin-controls {
            position: absolute;
            top: 5px;
            right: 5px;
            z-index: 100;
            display: flex;
            gap: 4px;
            opacity: 0;
            transition: opacity 0.2s;
        }
        
        .fg-item:hover .foogallery-admin-controls {
            opacity: 1;
        }
        
        .foogallery-admin-delete-link {
            background: rgba(255, 0, 0, 0.7);
            color: white;
            padding: 10px;
            font-size: 12px;
            text-decoration: none;
        }
        
        .foogallery-admin-delete-link:hover {
            background: rgba(255, 0, 0, 0.9);
            color: white;
        }
        
        .foogallery-admin-edit-caption {
            background: rgba(0, 100, 255, 0.7);
            color: white;
            padding: 10px;
            border-radius: 3px;
            font-size: 12px;
            text-decoration: none;
        }
        
        .foogallery-admin-edit-caption:hover {
            background: rgba(0, 100, 255, 0.9);
            color: white;
        }
        
        /* Caption editor modal */
        .caption-editor-modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.7);
        }
        
        .caption-editor-content {
            background-color: #fefefe;
            margin: 10% auto;
            padding: 20px;
            border-radius: 5px;
            width: 50%;
            max-width: 500px;
        }
        
        .caption-editor-content h3 {
            margin-top: 0;
        }
        
        .caption-editor-content textarea {
            width: 100%;
            min-height: 100px;
            margin-bottom: 15px;
        }
        
        .caption-editor-buttons {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }
        
        .caption-editor-buttons button {
            padding: 5px 15px;
            border: none;
            border-radius: 3px;
            cursor: pointer;
        }
        
        .caption-save-btn {
            background-color: #4CAF50;
            color: white;
        }
        
        .caption-cancel-btn {
            background-color: #f44336;
            color: white;
        }
    </style>
    
    <!-- Modal for editing captions -->
    <div id="captionEditorModal" class="caption-editor-modal">
        <div class="caption-editor-content">
            <h3>Edit Image Caption</h3>
            <textarea id="captionText" placeholder="Enter caption for this image..."></textarea>
            <div class="caption-editor-buttons">
                <button class="caption-cancel-btn" onclick="closeCaptionEditor()">Cancel</button>
                <button class="caption-save-btn" onclick="saveCaption()">Save Caption</button>
            </div>
            <input type="hidden" id="currentAttachmentId">
            <input type="hidden" id="currentGalleryId">
        </div>
    </div>
    
    <script>
    // Variables for the caption editor
    let captionModal, captionTextarea, currentAttachmentId, currentGalleryId;
    
    document.addEventListener('DOMContentLoaded', function() {
        // Initialize modal elements
        captionModal = document.getElementById('captionEditorModal');
        captionTextarea = document.getElementById('captionText');
        currentAttachmentId = document.getElementById('currentAttachmentId');
        currentGalleryId = document.getElementById('currentGalleryId');
        
        // Find all foogallery items
        const galleryItems = document.querySelectorAll('.foogallery .fg-item');
        
        galleryItems.forEach(function(item) {
            // Find the attachment ID from the link
            const link = item.querySelector('a.fg-thumb');
            if (link) {
                const attachmentId = link.getAttribute('data-attachment-id');
                if (attachmentId) {
                    // Create controls container
                    const controlsDiv = document.createElement('div');
                    controlsDiv.className = 'foogallery-admin-controls';
                    
                    // Create the edit caption link
                    const editLink = document.createElement('a');
                    editLink.href = '#';
                    editLink.className = 'foogallery-admin-edit-caption';
                    editLink.textContent = 'Edit Caption';
                    editLink.setAttribute('data-attachment-id', attachmentId);
                    
                    // Add click handler for edit
                    editLink.addEventListener('click', function(e) {
                        e.preventDefault();
                        
                        // Get the gallery ID from the parent container
                        const gallery = item.closest('.foogallery');
                        const galleryId = gallery ? gallery.id.replace('foogallery-gallery-', '') : '';
                        
                        // Open caption editor
                        openCaptionEditor(attachmentId, galleryId);
                    });
                    
                    // Create the delete link
                    const deleteLink = document.createElement('a');
                    deleteLink.href = '#';
                    deleteLink.className = 'foogallery-admin-delete-link';
                    deleteLink.textContent = 'Delete';
                    deleteLink.setAttribute('data-attachment-id', attachmentId);
                    deleteLink.setAttribute('data-nonce', '<?php echo wp_create_nonce("delete_gallery_image"); ?>');
                    
                    // Add click handler for delete
                    deleteLink.addEventListener('click', function(e) {
                        e.preventDefault();
                        if (confirm('Are you sure you want to remove this image from the gallery?')) {
                            // Get the gallery ID from the parent container
                            const gallery = item.closest('.foogallery');
                            const galleryId = gallery ? gallery.id.replace('foogallery-gallery-', '') : '';
                            
                            // Send AJAX request to remove the image
                            const xhr = new XMLHttpRequest();
                            xhr.open('POST', '<?php echo admin_url('admin-ajax.php'); ?>');
                            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                            xhr.onload = function() {
                                if (xhr.status === 200) {
                                    const response = JSON.parse(xhr.responseText);
                                    if (response.success) {
                                        // Remove the item from the DOM
                                        item.remove();
                                        alert('Image removed from gallery');
                                    } else {
                                        alert('Error: ' + response.data);
                                    }
                                } else {
                                    alert('Request failed. Please try again.');
                                }
                            };
                            xhr.send('action=remove_gallery_image&attachment_id=' + attachmentId + 
                                    '&gallery_id=' + galleryId + 
                                    '&nonce=' + this.getAttribute('data-nonce'));
                        }
                    });
                    
                    // Add both links to the controls
                    controlsDiv.appendChild(editLink);
                    controlsDiv.appendChild(deleteLink);
                    
                    // Add the controls to the item
                    item.querySelector('.fg-item-inner').appendChild(controlsDiv);
                }
            }
        });
    });
    
    // Function to open the caption editor
    function openCaptionEditor(attachmentId, galleryId) {
        // Fetch the current caption first
        const xhr = new XMLHttpRequest();
        xhr.open('POST', '<?php echo admin_url('admin-ajax.php'); ?>');
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onload = function() {
            if (xhr.status === 200) {
                const response = JSON.parse(xhr.responseText);
                if (response.success) {
                    // Set the caption text
                    captionTextarea.value = response.data;
                    
                    // Store IDs
                    currentAttachmentId.value = attachmentId;
                    currentGalleryId.value = galleryId;
                    
                    // Show the modal
                    captionModal.style.display = 'block';
                } else {
                    alert('Error: ' + response.data);
                }
            } else {
                alert('Request failed. Please try again.');
            }
        };
        xhr.send('action=get_attachment_caption&attachment_id=' + attachmentId + 
                '&nonce=' + '<?php echo wp_create_nonce("get_attachment_caption"); ?>');
    }
    
    // Function to close the caption editor
    function closeCaptionEditor() {
        captionModal.style.display = 'none';
    }
    
    // Function to save the caption
    function saveCaption() {
        const attachmentId = currentAttachmentId.value;
        const galleryId = currentGalleryId.value;
        const caption = captionTextarea.value;
        
        const xhr = new XMLHttpRequest();
        xhr.open('POST', '<?php echo admin_url('admin-ajax.php'); ?>');
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onload = function() {
            if (xhr.status === 200) {
                const response = JSON.parse(xhr.responseText);
                if (response.success) {
                    alert('Caption saved successfully!');
                    closeCaptionEditor();
                    
                    // Refresh the page to show the updated caption
                    window.location.reload();
                } else {
                    alert('Error: ' + response.data);
                }
            } else {
                alert('Request failed. Please try again.');
            }
        };
        xhr.send('action=update_attachment_caption&attachment_id=' + attachmentId + 
                '&gallery_id=' + galleryId + 
                '&caption=' + encodeURIComponent(caption) + 
                '&nonce=' + '<?php echo wp_create_nonce("update_attachment_caption"); ?>');
    }
    
    // Close the modal if user clicks outside of it
    window.onclick = function(event) {
        if (event.target == captionModal) {
            closeCaptionEditor();
        }
    }
    </script>
    <?php
}

// Add the code to wp_footer to ensure it runs after the gallery is loaded


add_action('wp_footer', 'add_foogallery_admin_controls');

// Add the AJAX handler for deleting images
function handle_remove_gallery_image() {
    // Verify the nonce
    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'delete_gallery_image')) {
        wp_send_json_error('Invalid security token');
        return;
    }
    
    // Check if user is allowed to do this
    if (!current_user_can('manage_options')) {
        wp_send_json_error('You do not have permission to do this');
        return;
    }
    
    // Get the attachment ID and gallery ID
    $attachment_id = isset($_POST['attachment_id']) ? intval($_POST['attachment_id']) : 0;
    $gallery_id = isset($_POST['gallery_id']) ? intval($_POST['gallery_id']) : 0;
    
    if ($attachment_id <= 0 || $gallery_id <= 0) {
        wp_send_json_error('Invalid attachment or gallery ID');
        return;
    }
    
    // Get the current attachments
    $attachments = get_post_meta($gallery_id, FOOGALLERY_META_ATTACHMENTS, true);
    
    if (!is_array($attachments)) {
        wp_send_json_error('Gallery has no attachments');
        return;
    }
    
    // Remove the attachment ID from the array
    $attachments = array_diff($attachments, [$attachment_id]);
    
    // Update the gallery
    update_post_meta($gallery_id, FOOGALLERY_META_ATTACHMENTS, $attachments);
    update_post_meta($gallery_id, '_foogallery_data_attachments', $attachments);
    
    // Clear gallery caches
    delete_post_meta($gallery_id, '_foogallery_gallery_hash');
    delete_post_meta($gallery_id, '_foogallery_rendered');
    delete_transient('foogallery_cache_' . $gallery_id);
    update_post_meta($gallery_id, '_foogallery_last_refresh', time());
    
    // Fire FooGallery actions for when a gallery is updated
    if (has_action('foogallery_gallery_updated')) {
        do_action('foogallery_gallery_updated', $gallery_id);
    }
    
    wp_send_json_success('Image removed from gallery');
}
add_action('wp_ajax_remove_gallery_image', 'handle_remove_gallery_image');

// Add the AJAX handler for getting attachment caption
function handle_get_attachment_caption() {
    // Verify the nonce
    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'get_attachment_caption')) {
        wp_send_json_error('Invalid security token');
        return;
    }
    
    // Check if user is allowed to do this
    if (!current_user_can('manage_options')) {
        wp_send_json_error('You do not have permission to do this');
        return;
    }
    
    // Get the attachment ID
    $attachment_id = isset($_POST['attachment_id']) ? intval($_POST['attachment_id']) : 0;
    
    if ($attachment_id <= 0) {
        wp_send_json_error('Invalid attachment ID');
        return;
    }
    
    // Get the attachment
    $attachment = get_post($attachment_id);
    
    if (!$attachment) {
        wp_send_json_error('Attachment not found');
        return;
    }
    
    // Return the caption (post_excerpt)
    wp_send_json_success($attachment->post_excerpt);
}
add_action('wp_ajax_get_attachment_caption', 'handle_get_attachment_caption');

// Add the AJAX handler for updating attachment caption
function handle_update_attachment_caption() {
    // Verify the nonce
    if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'update_attachment_caption')) {
        wp_send_json_error('Invalid security token');
        return;
    }
    
    // Check if user is allowed to do this
    if (!current_user_can('manage_options')) {
        wp_send_json_error('You do not have permission to do this');
        return;
    }
    
    // Get the attachment ID, gallery ID and caption
    $attachment_id = isset($_POST['attachment_id']) ? intval($_POST['attachment_id']) : 0;
    $gallery_id = isset($_POST['gallery_id']) ? intval($_POST['gallery_id']) : 0;
    $caption = isset($_POST['caption']) ? sanitize_textarea_field($_POST['caption']) : '';
    
    if ($attachment_id <= 0) {
        wp_send_json_error('Invalid attachment ID');
        return;
    }
    
    // Update the attachment
    $updated = wp_update_post([
        'ID' => $attachment_id,
        'post_excerpt' => $caption,
    ]);
    
    if (!$updated || is_wp_error($updated)) {
        wp_send_json_error('Failed to update caption');
        return;
    }
    
    // Clear gallery caches if gallery ID was provided
    if ($gallery_id > 0) {
        delete_post_meta($gallery_id, '_foogallery_gallery_hash');
        delete_post_meta($gallery_id, '_foogallery_rendered');
        delete_transient('foogallery_cache_' . $gallery_id);
        update_post_meta($gallery_id, '_foogallery_last_refresh', time());
        
        // Fire FooGallery actions for when a gallery is updated
        if (has_action('foogallery_gallery_updated')) {
            do_action('foogallery_gallery_updated', $gallery_id);
        }
    }
    
    wp_send_json_success('Caption updated successfully');
}
add_action('wp_ajax_update_attachment_caption', 'handle_update_attachment_caption');







function fireflygallery_shortcode_callback($atts) {
    //echo "hello";

    $atts = shortcode_atts([
        'id' => '', // ← Accept the correct attribute name
    ], $atts);

    $gallery_id = intval($atts['id']); // ← Match the attribute name

    //echo '<b>Gallery ID is ' . $gallery_id . '</b><br>';


    if (!$gallery_id) return '<!-- Invalid gallery ID -->';



    

    ob_start();


    if (current_user_can('manage_options')) {





        ?>
  <style>
  

    .firefly-gallery-container h2 {
        margin: 0;
        font-size: 36px;
        font-weight: bold;
    }

  

   

    .firefly-gallery-form {
        display: none;
        margin-top: 20px;
        text-align: left;
    }
</style> 

<?php 

        ?>
<div class="firefly-admin-1">
    <div class="firefly-admin-2">Firefly Gallery</div>
    <div class="firefly-admin-3">

    <div class="firefly-gallery-actions">
        <a onclick="toggleGalleryForm()">Add an image</a> 
       <?php // <a href="javascript:void(0);" onclick="toggleGalleryOptions()">Gallery options</a> ?>
      
        <div class="firefly-gallery-options" id="fireflyGalleryOptions" style="display:none; margin-top:20px;">
    <form method="post" action="<?= esc_url(admin_url('admin-post.php')); ?>">
        <input type="hidden" name="action" value="firefly_update_gallery_settings">
        <input type="hidden" name="gallery_id" value="<?= esc_attr($gallery_id); ?>">
        <?php wp_nonce_field('firefly_update_gallery_settings'); ?>

      
<?php

echo "<pre><h2>Post Meta for Gallery ID: {$gallery_id}</h2>";

$meta = get_post_meta($gallery_id);
foreach ($meta as $key => $value) {
    echo "<strong>{$key}</strong>:\n";
    print_r($value);
    echo "\n\n";
}

echo "</pre>";
        $current_template = get_post_meta($gallery_id, '_foogallery_template', true);
$current_settings = get_post_meta($gallery_id, '_foogallery_settings', true);
$current_thumb = $current_settings['thumb_width'] ?? '350';



?>
         
        <p><strong>Gallery Style:</strong><br>
    <select name="gallery_template">
        <option value="masonry-image-gallery" <?= selected($current_template, 'masonry-image-gallery') ?>>Masonry Gallery</option>
        <option value="justified-gallery" <?= selected($current_template, 'justified-gallery') ?>>Justified Gallery</option>
        <option value="responsive-image-gallery" <?= selected($current_template, 'responsive-image-gallery') ?>>Responsive Gallery</option>
        <option value="carousel" <?= selected($current_template, 'carousel') ?>>Carousel</option>
    </select>
</p>

<p><strong>Thumbnail Width:</strong><br>
    <select name="thumb_width">
        <option value="250" <?= selected($current_thumb, '250') ?>>250px</option>
        <option value="300" <?= selected($current_thumb, '300') ?>>300px</option>
        <option value="350" <?= selected($current_thumb, '350') ?>>350px</option>
        <option value="400" <?= selected($current_thumb, '400') ?>>400px</option>
    </select>
</p>
        <input type="hidden" name="gallery_id" value="<?= esc_attr($gallery_id); ?>">
        <p><button type="submit">Save Settings</button></p>
        <a href="#" onclick="toggleGalleryOptions(); return false;">Cancel</a>
    </form>
</div>

<script>
function toggleGalleryOptions() {
    const box = document.getElementById('fireflyGalleryOptions');
    box.style.display = box.style.display === 'block' ? 'none' : 'block';
}
</script>

    </div>

    <div class="firefly-gallery-form" id="fireflyGalleryForm"><div class="firefly-admin-4">
        <form method="post" enctype="multipart/form-data" action="<?= esc_url(admin_url('admin-post.php')); ?>">
            <input type="hidden" name="action" value="firefly_add_gallery_image">
            <input type="hidden" name="page_id" value="<?= esc_attr(get_the_ID()); ?>">
            <input type="hidden" name="direct_gallery_id" value="<?= esc_attr($gallery_id); ?>">
            <?php wp_nonce_field('firefly_add_gallery_image'); ?>

            <p><label>Upload Image:<br>
                <input type="file" name="gallery_image" accept="image/*" required></label></p>

            <p><label>Caption:<br>
                <input type="text" name="gallery_caption" style="width:100%;" placeholder="Write a short caption..."></label></p>

            <p><button type="submit">Add Image</button></p>
        </form>
        </div> </div> 
    </div></div>

<script>
    function toggleGalleryForm() {
        const form = document.getElementById('fireflyGalleryForm');
        form.style.display = form.style.display === 'block' ? 'none' : 'block';
    }

    function confirmDeleteGallery(galleryId) {
        if (confirm("Are you sure you want to delete this gallery?")) {
            window.location.href = "<?= esc_url(admin_url('admin-post.php')) ?>?action=firefly_delete_gallery&gallery_id=" + galleryId;
        }
    }

    function confirmDeleteAllImages(galleryId) {
        if (confirm("Are you sure you want to delete all images from this gallery?")) {
            window.location.href = "<?= esc_url(admin_url('admin-post.php')) ?>?action=firefly_delete_all_gallery_images&gallery_id=" + galleryId;
        }
    }

    function moveGalleryUp(galleryId) {
        // Placeholder for future logic
        alert("Move up clicked for gallery ID: " + galleryId);
    }

    function moveGalleryDown(galleryId) {
        // Placeholder for future logic
        alert("Move down clicked for gallery ID: " + galleryId);
    }
</script>


        <?php
    }

    // Then render the gallery itself
    echo do_shortcode('[foogallery id="' . $gallery_id . '"]');

    return ob_get_clean();
}

add_shortcode('fireflygallery', 'fireflygallery_shortcode_callback');


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

    $gallery_id = intval($_POST['gallery_id']);
    $template = sanitize_text_field($_POST['gallery_template']);
    $thumb_width = intval($_POST['thumb_width']);

    // Save settings
    update_post_meta($gallery_id, 'foogallery_template', $template);
    $settings = get_post_meta($gallery_id, 'foogallery_settings', true) ?: [];
    $settings['thumb_width'] = $thumb_width;
    update_post_meta($gallery_id, 'foogallery_settings', $settings);

    // Clear FooGallery cache to force update
    delete_post_meta($gallery_id, 'foogallery_gallery_hash');
    delete_post_meta($gallery_id, 'foogallery_rendered');
    delete_transient('foogallery_cache_' . $gallery_id);
    update_post_meta($gallery_id, 'foogallery_last_refresh', time());
    do_action('foogallery_gallery_updated', $gallery_id);


    update_post_meta($gallery_id, 'foogallery_template', $template); // Correct meta key
update_post_meta($gallery_id, 'foogallery_settings', $settings); // Already fine

// Clear FooGallery caches to force re-render
delete_post_meta($gallery_id, 'foogallery_gallery_hash');
delete_post_meta($gallery_id, 'foogallery_rendered');
delete_transient('foogallery_cache_' . $gallery_id);
update_post_meta($gallery_id, 'foogallery_last_refresh', time());



    // Redirect
    $redirect_url = isset($_SERVER['HTTP_REFERER']) ? esc_url_raw($_SERVER['HTTP_REFERER']) : home_url();
    wp_redirect($redirect_url);
    exit;
});
