<?php
/**
 * Gallery Field Handler 
 * 
 * @package HvnlyNab\Database\FieldTypes
 * @since 2.0.0
 */

namespace HvnlyNab\Database\FieldTypes;

class GalleryField extends BaseFieldType {
    
    public function __construct() {
        parent::__construct('gallery');
        $this->requires_assets = true;
    }
    
    public function render($field, $value, $post_id) {
        $html = $this->render_label($field);
        
        // Get the UNIQUE field name for this gallery
        $field_name = $field['name'] ?? $field['id'] ?? '';
        $group_base_id = $field['group_base_id'] ?? '';
        $metaKey = $field['metaKey'] ?? '';
        
        // Get saved images with backward compatibility
        $saved_value = $this->get_gallery_value($post_id, $field_name, $group_base_id, $metaKey);
        
        // Convert to array
        $gallery_images = !empty($saved_value) ? explode(',', $saved_value) : array();
        
        // Use field ID for gallery identification
        $gallery_id = $field['fieldid'] ?? $field['id'] ?? uniqid('gallery_');
        
        // Create UNIQUE input names based on gallery_id
        $title_input_name = 'hvnly_gallery_title_' . $gallery_id;
        $caption_input_name = 'hvnly_gallery_caption_' . $gallery_id;
        $ids_input_name = 'hvnly_gallery_ids_' . $gallery_id;
        
        ob_start();
        ?>
        
        <div class="hvnly-gallery-container" 
             data-field-id="<?php echo esc_attr($gallery_id); ?>" 
             data-gallery-id="<?php echo esc_attr($gallery_id); ?>"
             data-title-name="<?php echo esc_attr($title_input_name); ?>"
             data-caption-name="<?php echo esc_attr($caption_input_name); ?>"
             data-ids-name="<?php echo esc_attr($ids_input_name); ?>">
            
            <div class="hvnly-gallery-instructions">
                <?php esc_html_e('Add images to your gallery. Drag to reorder.', 'havenlytics'); ?>
            </div>
            
            <ul class="hvnly-gallery-images" id="hvnly-gallery-list-<?php echo esc_attr($gallery_id); ?>">
                <?php 
                if (!empty($gallery_images)) {
                    foreach ($gallery_images as $image_id): 
                        if (!empty($image_id)) {
                            $this->render_gallery_item($image_id, $gallery_id, $title_input_name, $caption_input_name, $ids_input_name);
                        }
                    endforeach; 
                }
                ?>
            </ul>
            
            <!-- Hidden field that stores the comma-separated image IDs -->
            <input type="hidden" 
                   id="hvnly_gallery_<?php echo esc_attr($gallery_id); ?>" 
                   name="<?php echo esc_attr($field_name); ?>" 
                   value="<?php echo esc_attr($saved_value); ?>" 
                   class="hvnly-gallery-hidden" />
            
            <div class="hvnly-gallery-actions">
                <button type="button" 
                        class="button button-primary hvnly-add-gallery" 
                        data-gallery-id="<?php echo esc_attr($gallery_id); ?>"
                        data-title-name="<?php echo esc_attr($title_input_name); ?>"
                        data-caption-name="<?php echo esc_attr($caption_input_name); ?>"
                        data-ids-name="<?php echo esc_attr($ids_input_name); ?>"
                        data-target-field="#hvnly_gallery_<?php echo esc_attr($gallery_id); ?>"
                        data-type="image">
                    <span class="dashicons dashicons-plus"></span>
                    <?php esc_html_e('Add Images', 'havenlytics'); ?>
                </button>
                <button type="button" 
                        class="button hvnly-clear-gallery" 
                        data-gallery-id="<?php echo esc_attr($gallery_id); ?>"
                        data-target-field="#hvnly_gallery_<?php echo esc_attr($gallery_id); ?>">
                    <span class="dashicons dashicons-trash"></span>
                    <?php esc_html_e('Clear Gallery', 'havenlytics'); ?>
                </button>
            </div>
        </div>
        <?php
        
        $html .= ob_get_clean();
        $html .= $this->render_description($field);
        
        return $html;
    }
    
    /**
     * Get gallery value with backward compatibility
     */
    private function get_gallery_value($post_id, $field_name, $group_base_id, $metaKey) {
        // Try primary key first
        $value = get_post_meta($post_id, $field_name, true);
        
        // If no value and this is a gallery images field, try legacy
        if (empty($value) && $metaKey === 'images') {
            $value = get_post_meta($post_id, '_hvnly_property_gallery_images', true);
        }
        
        // If no value and this is a gallery title field, try legacy
        if (empty($value) && $metaKey === 'title') {
            $value = get_post_meta($post_id, '_hvnly_property_gallery_title', true);
        }
        
        return $value;
    }
    
    /**
     * Render a single gallery item
     */
    private function render_gallery_item($image_id, $gallery_id, $title_input_name, $caption_input_name, $ids_input_name) {
        if ($image = wp_get_attachment_image_src($image_id, 'thumbnail')) {
            $attachment = get_post($image_id);
            $title = $attachment ? $attachment->post_title : '';
            $caption = $attachment ? $attachment->post_excerpt : '';
            ?>
            <li class="hvnly-gallery-item" 
                data-id="<?php echo esc_attr($image_id); ?>" 
                data-gallery-id="<?php echo esc_attr($gallery_id); ?>">
                
                <img src="<?php echo esc_url($image[0]); ?>" 
                     alt="<?php echo esc_attr($title); ?>" />
                
                <div class="hvnly-gallery-item-actions">
                    <a href="#" class="hvnly-gallery-edit" title="<?php esc_attr_e('Edit Image', 'havenlytics'); ?>">
                        <span class="dashicons dashicons-edit"></span>
                    </a>
                    <a href="#" class="hvnly-gallery-remove" title="<?php esc_attr_e('Remove Image', 'havenlytics'); ?>">
                        <span class="dashicons dashicons-no"></span>
                    </a>
                </div>
                
                <input type="hidden" 
                       name="<?php echo esc_attr($title_input_name); ?>[]" 
                       value="<?php echo esc_attr($title); ?>" />
                       
                <input type="hidden" 
                       name="<?php echo esc_attr($caption_input_name); ?>[]" 
                       value="<?php echo esc_attr($caption); ?>" />
                       
                <input type="hidden" 
                       name="<?php echo esc_attr($ids_input_name); ?>[]" 
                       value="<?php echo esc_attr($image_id); ?>" />
            </li>
            <?php
        }
    }
    
    public function save($post_id, $field_name, $value) {
        // Sanitize and save to the unique field name
        $image_ids = explode(',', sanitize_text_field($value));
        $image_ids = array_map('intval', array_filter($image_ids));
        $clean_value = implode(',', $image_ids);
        
        // Save to unique meta key
        update_post_meta($post_id, $field_name, $clean_value);
        
        // For backward compatibility, also save to legacy key if this is a gallery field
        if (strpos($field_name, 'gallery_') === 0 && strpos($field_name, '_images') !== false) {
            update_post_meta($post_id, '_hvnly_property_gallery_images', $clean_value);
        }
        
        if (strpos($field_name, 'gallery_') === 0 && strpos($field_name, '_title') !== false) {
            $title_value = $value; // For title fields, just save the string
            update_post_meta($post_id, '_hvnly_gallery_title', $title_value);
        }
    }
    
    public function sanitize($value) {
        $image_ids = explode(',', $value);
        return implode(',', array_map('intval', array_filter($image_ids)));
    }
    
    public function validate($value, $field) {
        if (isset($field['is_required']) && $field['is_required'] && empty($value)) {
            return new \WP_Error('required_gallery', sprintf(
                /* translators: %s: gallery field is required */
                __('The gallery field "%s" is required.', 'havenlytics'),
                esc_html($field['label'])
            ));
        }
        return true;
    }
    
    public function enqueue_assets() {
        wp_enqueue_media();
        wp_enqueue_script('jquery-ui-sortable');
        
        wp_enqueue_script(
            'hvnly-gallery-field',
            HVNLYNAB_ASSETS_URL . '/admin/js/hvnly-gallery-field.js',
            ['jquery', 'jquery-ui-sortable'],
            HVNLYNAB_VERSION,
            true
        );
    }
}