<?php
/*
 * Custom Post Type for Photo Albums
 * Avoids conflict with WordPress core 'gallery' terminology
 */

/**
 * Register Photo Album Custom Post Type
 */
function register_photo_album_post_type() {
    $labels = [
        'name'                  => _x('Photo Albums', 'Post type general name', 'textdomain'),
        'singular_name'         => _x('Photo Album', 'Post type singular name', 'textdomain'),
        'menu_name'             => _x('Photo Albums', 'Admin Menu text', 'textdomain'),
        'name_admin_bar'        => _x('Photo Album', 'Add New on Toolbar', 'textdomain'),
        'add_new'               => __('Add New', 'textdomain'),
        'add_new_item'          => __('Add New Photo Album', 'textdomain'),
        'new_item'              => __('New Photo Album', 'textdomain'),
        'edit_item'             => __('Edit Photo Album', 'textdomain'),
        'view_item'             => __('View Photo Album', 'textdomain'),
        'all_items'             => __('All Photo Albums', 'textdomain'),
        'search_items'          => __('Search Photo Albums', 'textdomain'),
        'not_found'             => __('No photo albums found.', 'textdomain'),
        'not_found_in_trash'    => __('No photo albums found in Trash.', 'textdomain'),
    ];

    $args = [
        'labels'                => $labels,
        'public'                => true,
        'publicly_queryable'    => true,
        'show_ui'               => true,
        'show_in_menu'          => true,
        'query_var'             => true,
        'rewrite'               => ['slug' => 'photo-album'],
        'capability_type'       => 'post',
        'has_archive'           => true,
        'hierarchical'          => false,
        'menu_position'         => 20,
        'menu_icon'             => 'dashicons-format-gallery',
        'supports'              => ['title', 'excerpt', 'thumbnail'],
        'taxonomies'            => ['album_category'],
        'show_in_rest'          => true,
    ];

    register_post_type('photo_album', $args);
}
add_action('init', 'register_photo_album_post_type');

/**
 * Register Album Category Taxonomy
 */
function register_album_category_taxonomy() {
    $labels = [
        'name'              => _x('Album Categories', 'Taxonomy general name', 'textdomain'),
        'singular_name'     => _x('Album Category', 'Taxonomy singular name', 'textdomain'),
        'search_items'      => __('Search Album Categories', 'textdomain'),
        'all_items'         => __('All Album Categories', 'textdomain'),
        'parent_item'       => __('Parent Album Category', 'textdomain'),
        'parent_item_colon' => __('Parent Album Category:', 'textdomain'),
        'edit_item'         => __('Edit Album Category', 'textdomain'),
        'update_item'       => __('Update Album Category', 'textdomain'),
        'add_new_item'      => __('Add New Album Category', 'textdomain'),
        'new_item_name'     => __('New Album Category Name', 'textdomain'),
        'menu_name'         => __('Album Categories', 'textdomain'),
    ];

    $args = [
        'hierarchical'      => true,
        'labels'            => $labels,
        'show_ui'           => true,
        'show_admin_column' => true,
        'query_var'         => true,
        'rewrite'           => ['slug' => 'album-category'],
        'show_in_rest'      => true,
    ];

    register_taxonomy('album_category', ['photo_album'], $args);
}
add_action('init', 'register_album_category_taxonomy');

/**
 * Add Meta Box for Album Images
 */
function add_album_images_meta_box() {
    add_meta_box(
        'album_images',
        __('Album Images', 'textdomain'),
        'render_album_images_meta_box',
        'photo_album',
        'normal',
        'high'
    );
}
add_action('add_meta_boxes', 'add_album_images_meta_box');

/**
 * Render Meta Box Content
 */
function render_album_images_meta_box($post) {
    wp_nonce_field('save_album_images_nonce', 'album_images_nonce');
    $image_ids = get_post_meta($post->ID, '_album_images', true);
    $image_ids = !empty($image_ids) && is_array($image_ids) ? array_map('intval', $image_ids) : [];
    ?>
    <div id="album-images-container">
        <button type="button" class="button" id="add-album-images"><?php _e('Add Images', 'textdomain'); ?></button>
        <ul id="album-images-list" style="margin-top: 10px; display: flex; flex-wrap: wrap; gap: 10px;">
            <?php foreach ($image_ids as $image_id):
                $image_url = wp_get_attachment_image_url($image_id, 'thumbnail');
                if ($image_url): ?>
                    <li class="album-image-item" data-image-id="<?php echo esc_attr($image_id); ?>" style="position: relative; width: 100px;">
                        <img src="<?php echo esc_url($image_url); ?>" style="width: 100px; height: auto; display: block;" />
                        <button type="button" class="remove-image button" style="position: absolute; top: 0; right: 0; background: red; color: white; border: none; line-height: 1; padding: 2px 5px;">X</button>
                    </li>
                <?php endif;
            endforeach; ?>
        </ul>
        <input type="hidden" name="album_images" id="album_images" value="<?php echo esc_attr(implode(',', $image_ids)); ?>">
    </div>

    <script>
    jQuery(document).ready(function($) {
        var frame;

        // Add Images
        $('#add-album-images').on('click', function(e) {
            e.preventDefault();

            if (frame) {
                frame.open();
                return;
            }

            frame = wp.media({
                title: '<?php _e('Select or Upload Images', 'textdomain'); ?>',
                button: { text: '<?php _e('Use Images', 'textdomain'); ?>' },
                library: { type: 'image' },
                multiple: true
            });

            frame.on('select', function() {
                var selection = frame.state().get('selection');
                var imageIds = $('#album_images').val().split(',').filter(id => id).map(id => parseInt(id));
                var imageList = $('#album-images-list');

                selection.map(function(attachment) {
                    attachment = attachment.toJSON();
                    if (!imageIds.includes(attachment.id)) {
                        imageIds.push(attachment.id);
                        var imgUrl = attachment.sizes && attachment.sizes.thumbnail ? attachment.sizes.thumbnail.url : attachment.url;
                        imageList.append(
                            '<li class="album-image-item" data-image-id="' + attachment.id + '" style="position: relative; width: 100px;">' +
                            '<img src="' + imgUrl + '" style="width: 100px; height: auto; display: block;" />' +
                            '<button type="button" class="remove-image button" style="position: absolute; top: 0; right: 0; background: red; color: white; border: none; line-height: 1; padding: 2px 5px;">X</button>' +
                            '</li>'
                        );
                    }
                });

                $('#album_images').val(imageIds.join(','));
                console.log('Updated image IDs:', $('#album_images').val()); // Debug
            });

            frame.open();
        });

        // Remove Image
        $(document).on('click', '.remove-image', function() {
            var $item = $(this).closest('.album-image-item');
            var imageId = parseInt($item.data('image-id'));
            var imageIds = $('#album_images').val().split(',').filter(id => id).map(id => parseInt(id));
            imageIds = imageIds.filter(id => id !== imageId);
            $item.remove();
            $('#album_images').val(imageIds.join(','));
            console.log('Removed image ID:', imageId, 'New IDs:', $('#album_images').val()); // Debug
        });

        // Debug form submission
        $('#post').on('submit', function() {
            console.log('Form submitting with album_images:', $('#album_images').val());
        });
    });
    </script>
    <?php
}

/**
 * Save Album Images
 */
function save_album_images($post_id) {
    // Log for debugging
    error_log('save_album_images called for post_id: ' . $post_id);

    // Verify nonce
    if (!isset($_POST['album_images_nonce']) || !wp_verify_nonce($_POST['album_images_nonce'], 'save_album_images_nonce')) {
        error_log('Nonce verification failed');
        return;
    }

    // Prevent autosave
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        error_log('Autosave detected, exiting');
        return;
    }

    // Check permissions
    if (!current_user_can('edit_post', $post_id)) {
        error_log('User lacks edit_post permission');
        return;
    }

    // Check post type
    if (get_post_type($post_id) !== 'photo_album') {
        error_log('Incorrect post type: ' . get_post_type($post_id));
        return;
    }

    // Save images
    if (isset($_POST['album_images']) && !empty($_POST['album_images'])) {
        $image_ids = array_map('intval', array_filter(explode(',', sanitize_text_field($_POST['album_images']))));
        error_log('Saving image IDs: ' . print_r($image_ids, true));
        if (!empty($image_ids)) {
            update_post_meta($post_id, '_album_images', $image_ids);
        } else {
            delete_post_meta($post_id, '_album_images');
            error_log('No valid image IDs, deleted meta');
        }
    } else {
        delete_post_meta($post_id, '_album_images');
        error_log('No album_images data, deleted meta');
    }

    // Verify save
    $saved_ids = get_post_meta($post_id, '_album_images', true);
    error_log('After save, _album_images meta: ' . print_r($saved_ids, true));
}
add_action('save_post', 'save_album_images', 10, 1);

/**
 * Shortcode to Display Photo Albums
 */
function photo_albums_shortcode($atts) {
    ob_start();
    $args = [
        'post_type'      => 'photo_album',
        'posts_per_page' => -1,
    ];

    $query = new WP_Query($args);

    if ($query->have_posts()): ?>
        <div class="photo-albums" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 20px;">
            <?php while ($query->have_posts()): $query->the_post();
                $image_ids = get_post_meta(get_the_ID(), '_album_images', true);
                $image_ids = !empty($image_ids) && is_array($image_ids) ? $image_ids : [];
                ?>
                <div class="album-card" style="border: 1px solid #ddd; padding: 10px;">
                    <?php if (has_post_thumbnail()): ?>
                        <a href="<?php the_permalink(); ?>">
                            <img src="<?php the_post_thumbnail_url('medium'); ?>" alt="<?php the_title_attribute(); ?>" style="width: 100%; height: auto;" />
                        </a>
                    <?php endif; ?>
                    <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
                    <?php if (get_the_excerpt()): ?>
                        <p><?php the_excerpt(); ?></p>
                    <?php endif; ?>
                    <?php if (!empty($image_ids)): ?>
                        <div class="album-images" style="display: flex; flex-wrap: wrap; gap: 5px;">
                            <?php foreach (array_slice($image_ids, 0, 4) as $image_id):
                                $image_url = wp_get_attachment_image_url($image_id, 'thumbnail');
                                if ($image_url): ?>
                                    <img src="<?php echo esc_url($image_url); ?>" alt="Album image" style="width: 50px; height: 50px; object-fit: cover;" />
                                <?php endif;
                            endforeach; ?>
                            <?php if (count($image_ids) > 4): ?>
                                <span>+<?php echo count($image_ids) - 4; ?> more</span>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                </div>
            <?php endwhile; ?>
        </div>
    <?php else: ?>
        <p><?php _e('No photo albums found.', 'textdomain'); ?></p>
    <?php endif;

    wp_reset_postdata();
    return ob_get_clean();
}
add_shortcode('photo_albums', 'photo_albums_shortcode');

/**
 * Enqueue Admin Styles
 */
function album_admin_styles() {
    global $post_type;
    if ($post_type === 'photo_album') {
        ?>
        <style>
            #album-images-list { list-style: none; padding: 0; }
            .album-image-item { position: relative; display: inline-block; }
            .remove-image:hover { background: darkred; cursor: pointer; }
        </style>
        <?php
    }
}
add_action('admin_head', 'album_admin_styles');

//Shortcode to Display Gallery in 3 Columns
function galleryi_shortcode($atts) {
    ob_start();
    $args = [
        'post_type' => 'photo-album',
        'posts_per_page' => -1,
    ];

    $query = new WP_Query($args);

    if ($query->have_posts()) : ?>
        <div class="row gallery-grid">
            <?php while ($query->have_posts()) : $query->the_post();
                $images = get_post_meta(get_the_ID(), '_album_images', true);
                ?>
                <div class="col-md-4 mb-4">
                    <a href="<?php the_permalink(); ?>">
                    <div class="card h-100 shadow-sm">
                        <?php if (has_post_thumbnail()) : ?>
                            <img src="<?php the_post_thumbnail_url('Full'); ?>" class="card-img-top">
                        <?php endif; ?>
                        <div class="card-body">
                            <h5><?php the_title(); ?></h5>
                            <p><?php the_excerpt(); ?></p>
                        </div>
                        <?php if (!empty($images)) : ?>
                            <div class="card-footer">
                                <div class="d-flex flex-wrap gap-2">
                                    <?php foreach ($images as $id) : ?>
                                        <img src="<?php echo wp_get_attachment_image_url($id, 'Full'); ?>" style="width: 60px; height: 60px; object-fit: cover;">
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                    </a>
                </div>
            <?php endwhile; ?>
        </div>
    <?php
    endif;
    wp_reset_postdata();
    return ob_get_clean();
}
add_shortcode('photo_gallery', 'galleryi_shortcode');

 
