<?php
/*-----------------------------------------------------------------------------------*/
/*  EXTHEM.ES
/*  PREMIUM WORDRESS THEMES
/*
/*  STOP DON'T TRY EDIT
/*  IF YOU DON'T KNOW PHP 
/*
/*-----------------------------------------------------------------------------------*/
 
/*
Background Image
https://wordpress.stackexchange.com/questions/421542/second-featured-image-only-shows-in-metabox-preview-after-saving-a-post-in-the-w
*/

add_action( 'admin_init', 'background_image_post_setup' );
function background_image_post_setup(){
add_action( 'add_meta_boxes', 'add_background_image_meta_box');
add_action( 'save_post', 'save_background_image_meta_box');
add_action( 'admin_head-post.php', 'background_image_script' );
add_action( 'admin_head-post-new.php', 'background_image_script' );
}

function add_background_image_meta_box() { 
        add_meta_box(
            'background_images_meta_box',
            'Background Image',
            'display_background_images_meta_box',
            'post',
            'side',
            'default'
        ); 
}
 
function background_image_script() {
    global $post;
    if( 'post' != $post->post_type ) 
        return;
    ?>  
	<script>
	jQuery(document).ready(function ($) {
    let mediaUploader;

    $('#upload_background_image_button').on('click', function (e) {
        e.preventDefault();

        // If the uploader object has already been created, reopen the dialog
        if (mediaUploader) {
            mediaUploader.open();
            return;
        }

        // Extend the wp.media object
        mediaUploader = wp.media({
            title: 'Choose Image',
            button: {
                text: 'Choose Image'
            },
            multiple: false
        });

        // When an image is selected, run a callback
        mediaUploader.on('select', function () {
            var attachment = mediaUploader.state().get('selection').first().toJSON();
            $('#for_background_images').val(attachment.id);

            // Update the image preview
            var imagePreview = $('#background_image_preview');
            if (imagePreview.length) {
                imagePreview.html('<img src="' + attachment.url + '" style="max-width: 100%; height: auto;">');
            } else {
                // If the preview element doesn't exist, create it
                $('#background_image_preview_container').append('<div id="background_image_preview"><img src="' + attachment.url + '" style="max-width: 100%; height: auto;"></div>');
            }

            $('#upload_background_image_button').text('Change Image');
            $('#remove_background_image_button').show();
        });

        // Open the uploader dialog
        mediaUploader.open();
    });

    $('#remove_background_image_button').on('click', function (e) {
        e.preventDefault();
        $('#for_background_images').val('');
        $('#background_image_preview').html('');
        $('#upload_background_image_button').text('Set background image');
        $(this).hide();
    });
});
	</script>
    <?php
}
 
function display_background_images_meta_box($post) {
    $background_images = get_post_meta($post->ID, 'background_images', true);
    ?>

    <style>
        .image-preview img {
            max-width: 100%;
            height: auto;
            cursor: pointer;
            margin-top: 10px;
        }
        .edit-image-link,
        .remove-image-link {
            margin-top: 5px;
            display: block;
        }
    </style>
 
    <div class="image-preview" id="background_image_preview">
        <?php if (!empty($background_images)) : ?>
            <?php echo wp_get_attachment_image($background_images, 'full'); ?>
        <?php endif; ?>
    </div>
 
	<table style="width:100%"> 
	  <tr>
		<td style="text-align: left;font-size: small;"><span style="color: #2271b1;text-decoration: underline;cursor: pointer;line-height: 40px;" class="upload-image-button" id="upload_background_image_button"><?php echo empty($background_images) ? 'Set background image' : 'Change Image'; ?></span></td> 
		<td style="text-align: right;font-size: small;<?php echo empty($background_images) ? ' display: none; ' : ''; ?>" ><span style="color: #2271b1;text-decoration: underline;cursor: pointer;line-height: 40px;" class="remove-image-button" id="remove_background_image_button" <?php echo empty($background_images) ? 'style="display: none;"' : ''; ?>>Remove Image</span></td> 
	  </tr>
	</table>

	<!--
    <button class="upload-image-button button" id="upload_background_image_button">Upload/Select Image</button>
    <button class="remove-image-button button" id="remove_background_image_button" <?php echo empty($background_images) ? 'style="display: none;"' : ''; ?>>Remove Image</button>
	-->
    <input type="hidden" id="for_background_images" name="for_background_images" value="<?php echo esc_attr($background_images); ?>" style="width: 100%;">

    <?php
}

// Save the second featured image when the post is saved
function save_background_image_meta_box($post_id) {
    if (isset($_POST['for_background_images'])) {
        $background_images = absint($_POST['for_background_images']); // Use absint to ensure it's an integer
        update_post_meta($post_id, 'background_images', $background_images);

        // Check if the remove image button was clicked
        if (isset($_POST['remove_second_featured_image']) && $_POST['remove_second_featured_image'] === 'true') {
            delete_post_meta($post_id, 'background_images');
        }
    }
}
 