<?php
/**
 * Gallery Carousel Template
 * 
 * This template displays the gallery carousel for single property pages.
 * 
 * HOW TO OVERRIDE THIS TEMPLATE:
 * 1. Copy this file from: wp-content/plugins/havenlytics/templates/single-property/gallery-carousel.php
 * 2. Paste it to your theme at: wp-content/themes/your-theme/havenlytics/single-property/gallery-carousel.php
 * 3. Modify the copied file to customize the gallery carousel
 * 
 * @package     Havenlytics
 * @subpackage  Templates/single-property/
 * @since       2.0.0
 */
if (!defined('ABSPATH')) {
    exit;
}

// Prefix all variables with hvnly_ to avoid global namespace conflicts
$hvnly_property_id = get_the_ID();

// NEW: Get all gallery images from ANY gallery field in this property
$hvnly_gallery_image_ids = array();

// Get all sections from database
$hvnly_sections = get_option('hvnly_property_builder.sections', array());

// Loop through all sections to find gallery fields
foreach ($hvnly_sections as $hvnly_section) {
    if (empty($hvnly_section['fields']) || !is_array($hvnly_section['fields'])) {
        continue;
    }
    
    foreach ($hvnly_section['fields'] as $hvnly_field) {
        // Check if this is a gallery field (type 'gallery' or has gallery in name)
        $hvnly_is_gallery = false;
        
        if (isset($hvnly_field['type']) && $hvnly_field['type'] === 'gallery') {
            $hvnly_is_gallery = true;
        }
        
        if (isset($hvnly_field['group_type']) && $hvnly_field['group_type'] === 'gallery') {
            $hvnly_is_gallery = true;
        }
        
        if (isset($hvnly_field['name']) && strpos($hvnly_field['name'], 'gallery_') === 0) {
            $hvnly_is_gallery = true;
        }
        
        if ($hvnly_is_gallery && isset($hvnly_field['name'])) {
            $hvnly_meta_key = $hvnly_field['name'];
            $hvnly_images = get_post_meta($hvnly_property_id, $hvnly_meta_key, true);
            
            if (!empty($hvnly_images)) {
                // Handle different formats
                if (is_string($hvnly_images)) {
                    // Check if it's a comma-separated string
                    if (strpos($hvnly_images, ',') !== false) {
                        $hvnly_ids = explode(',', $hvnly_images);
                        foreach ($hvnly_ids as $hvnly_id) {
                            $hvnly_id = trim($hvnly_id);
                            if (is_numeric($hvnly_id)) {
                                $hvnly_gallery_image_ids[] = absint($hvnly_id);
                            }
                        }
                    } 
                    // Check if it's a JSON array
                    elseif (strpos($hvnly_images, '[') === 0 || strpos($hvnly_images, '{') === 0) {
                        $hvnly_decoded = json_decode($hvnly_images, true);
                        if (is_array($hvnly_decoded)) {
                            foreach ($hvnly_decoded as $hvnly_item) {
                                if (is_numeric($hvnly_item)) {
                                    $hvnly_gallery_image_ids[] = absint($hvnly_item);
                                } elseif (is_array($hvnly_item) && isset($hvnly_item['id'])) {
                                    $hvnly_gallery_image_ids[] = absint($hvnly_item['id']);
                                }
                            }
                        }
                    }
                    // Single ID
                    elseif (is_numeric($hvnly_images)) {
                        $hvnly_gallery_image_ids[] = absint($hvnly_images);
                    }
                } 
                // Array of IDs
                elseif (is_array($hvnly_images)) {
                    foreach ($hvnly_images as $hvnly_image) {
                        if (is_numeric($hvnly_image)) {
                            $hvnly_gallery_image_ids[] = absint($hvnly_image);
                        } elseif (is_array($hvnly_image) && isset($hvnly_image['id'])) {
                            $hvnly_gallery_image_ids[] = absint($hvnly_image['id']);
                        }
                    }
                }
            }
        }
    }
}

// Remove duplicates and ensure they're integers
$hvnly_gallery_image_ids = array_unique(array_map('absint', $hvnly_gallery_image_ids));

// If no gallery images found from dynamic fields, try the legacy meta key as fallback
if (empty($hvnly_gallery_image_ids)) {
    $hvnly_legacy_images = get_post_meta($hvnly_property_id, '_hvnly_property_gallery_images', true);
    if (!empty($hvnly_legacy_images)) {
        if (is_string($hvnly_legacy_images) && strpos($hvnly_legacy_images, ',') !== false) {
            $hvnly_gallery_image_ids = array_map('absint', explode(',', $hvnly_legacy_images));
        } elseif (is_array($hvnly_legacy_images)) {
            $hvnly_gallery_image_ids = array_map('absint', $hvnly_legacy_images);
        }
    }
}

$hvnly_featured_image = get_the_post_thumbnail_url($hvnly_property_id, 'full');
$hvnly_gallery_title = get_post_meta($hvnly_property_id, '_hvnly_property_gallery_title', true);

// Prepare display images
$hvnly_display_images = array();
$hvnly_has_images = false;

// First, try to use gallery images
if (!empty($hvnly_gallery_image_ids)) {
    $hvnly_has_images = true;
    foreach ($hvnly_gallery_image_ids as $hvnly_image_id) {
        $hvnly_image_url = wp_get_attachment_image_url($hvnly_image_id, 'full');
        $hvnly_image_thumb = wp_get_attachment_image_url($hvnly_image_id, 'medium');
        if ($hvnly_image_url) {
            $hvnly_display_images[] = array(
                'type' => 'gallery',
                'url' => esc_url($hvnly_image_url),
                'thumb' => $hvnly_image_thumb,
                'id' => absint($hvnly_image_id),
                'title' => get_the_title($hvnly_image_id),
                'alt' => get_post_meta($hvnly_image_id, '_wp_attachment_image_alt', true)
            );
        }
    }
}

// If no gallery images, use featured image
if (!$hvnly_has_images && $hvnly_featured_image) {
    $hvnly_has_images = true;
    $hvnly_display_images[] = array(
        'type' => 'featured',
        'url' => esc_url($hvnly_featured_image),
        'thumb' => $hvnly_featured_image,
        'id' => 'featured',
        'title' => get_the_title($hvnly_property_id),
        'alt' => get_post_meta($hvnly_property_id, '_wp_attachment_image_alt', true)
    );
}

// If still no images, use placeholder
if (!$hvnly_has_images) {
    $hvnly_display_images[] = array(
        'type' => 'placeholder',
        'url' => HVNLYNAB_ASSETS_URL . 'images/placeholder.jpg',
        'thumb' => HVNLYNAB_ASSETS_URL . 'images/placeholder-thumb.jpg',
        'id' => 'placeholder',
        'title' => get_the_title($hvnly_property_id),
        'alt' => get_the_title($hvnly_property_id)
    );
}

$hvnly_total_images = count($hvnly_display_images);
?>
<!-- Property Gallery Carousel with Smooth Zoom Effects -->
<div class="hvnly-property-single__gallery">

    <div class="hvnly-property-single__gallery-main" id="hvnlyPropertySingleGalleryMain">
        <!-- Gallery Slides -->
        <?php foreach ($hvnly_display_images as $hvnly_index => $hvnly_image_data): 
            $hvnly_is_active = $hvnly_index === 0 ? ' hvnly-property-single__gallery-slide--active' : '';
            $hvnly_slide_index = absint($hvnly_index);
        ?>
        <div class="hvnly-property-single__gallery-slide<?php echo esc_attr( $hvnly_is_active ); ?>"
            style="background-image: url('<?php echo esc_url($hvnly_image_data['url']); ?>');"
            data-slide-index="<?php echo esc_attr($hvnly_slide_index); ?>"
            data-image-id="<?php echo esc_attr($hvnly_image_data['id']); ?>"
            data-image-title="<?php echo esc_attr($hvnly_image_data['title']); ?>"
            data-image-alt="<?php echo esc_attr($hvnly_image_data['alt']); ?>">
        </div>
        <?php endforeach; ?>

        <div class="hvnly-property-single__gallery-counter" id="hvnlyPropertySingleGalleryCounter">
            <?php if ($hvnly_total_images > 0): ?>
            1/<?php echo esc_html($hvnly_total_images); ?>
            <?php else: ?>
            0/0
            <?php endif; ?>
        </div>

        <?php if ($hvnly_total_images > 1): ?>
        <div class="hvnly-property-single__gallery-indicators" id="hvnlyPropertySingleGalleryIndicators">
            <?php for ($hvnly_i = 0; $hvnly_i < $hvnly_total_images; $hvnly_i++): 
                    $hvnly_indicator_active = $hvnly_i === 0 ? ' hvnly-property-single__gallery-indicator--active' : '';
                ?>
            <div class="hvnly-property-single__gallery-indicator<?php echo esc_attr( $hvnly_indicator_active ); ?>"
                data-index="<?php echo esc_attr($hvnly_i); ?>"></div>
            <?php endfor; ?>
        </div>
        <?php endif; ?>

        <?php if ($hvnly_total_images > 1): ?>
        <div class="hvnly-property-single__gallery-controls">
            <button class="hvnly-property-single__gallery-btn hvnly-property-single__gallery-btn--prev"
                aria-label="<?php esc_attr_e('Previous image', 'havenlytics'); ?>">
                <i class="fas fa-chevron-left"></i>
            </button>
            <button class="hvnly-property-single__gallery-btn hvnly-property-single__gallery-btn--next"
                aria-label="<?php esc_attr_e('Next image', 'havenlytics'); ?>">
                <i class="fas fa-chevron-right"></i>
            </button>
        </div>
        <?php endif; ?>
    </div>

    <?php if ($hvnly_total_images > 1): ?>
    <div class="hvnly-property-single__thumbnail-container" id="hvnlyPropertySingleGalleryThumbnails">
        <!-- Thumbnails will be populated by JavaScript -->
    </div>
    <?php endif; ?>
</div>