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

namespace HvnlyNab\Database\FieldTypes;

class VideoField extends BaseFieldType {
    public function __construct() {
        parent::__construct('video');
        $this->requires_assets = true;
    }
    
    public function render($field, $value, $post_id) {
        ob_start();
        ?>
<div class="hvnly-video-field-container" data-field-id="<?php echo esc_attr($field['id']); ?>"
    data-group-base-id="<?php echo esc_attr($field['group_base_id'] ?? ''); ?>">
    <?php 
            $this->render_video_fields($field, $post_id);
            ?>
</div>
<?php
        
        $html = ob_get_clean();
        $html .= $this->render_description($field);
        
        return $html;
    }
    
    /**
     * Render video fields with proper unique names
     */
    private function render_video_fields($field, $post_id) {
        // Get the base ID for this group
        $group_base_id = $field['group_base_id'] ?? '';
        $metaKey = $field['metaKey'] ?? '';
        
        // Generate field names based on group_base_id
        if (!empty($group_base_id)) {
            $title_field = $group_base_id . '_title';
            $url_field = $group_base_id . '_url';
            $thumbnail_field = $group_base_id . '_thumbnail';
        } else {
            // Fallback for older fields
            $title_field = $field['name'] ?? '_hvnly_video_title';
            $url_field = str_replace('_title', '_url', $title_field);
            $thumbnail_field = str_replace('_title', '_thumbnail', $title_field);
        }
        
        // Get values with backward compatibility
        $title_value = $this->get_video_value($post_id, $title_field, 'title');
        $url_value = $this->get_video_value($post_id, $url_field, 'url');
        $thumbnail_value = $this->get_video_value($post_id, $thumbnail_field, 'thumbnail');
        
        // Render fields
        $this->render_text_field(
            $title_field,
            $title_value,
            __('Video Title', 'havenlytics'),
            __('Enter video title', 'havenlytics')
        );
        
        $this->render_text_field(
            $url_field,
            $url_value,
            __('Video URL', 'havenlytics'),
            __('Enter full YouTube URL or ID', 'havenlytics')
        );
        
        $this->render_thumbnail_field(
            $thumbnail_field,
            $thumbnail_value,
            __('Video Thumbnail', 'havenlytics')
        );
    }
    
    /**
     * Get video value with backward compatibility
     */
    private function get_video_value($post_id, $primary_key, $type) {
        // Try primary key first (new unique key)
        $value = get_post_meta($post_id, $primary_key, true);
        
        // If no value, try legacy keys
        if (empty($value)) {
            $legacy_keys = [
                'title' => '_hvnly_video_title',
                'url' => '_hvnly_video_url',
                'thumbnail' => '_hvnly_video_thumbnail'
            ];
            
            if (isset($legacy_keys[$type])) {
                $value = get_post_meta($post_id, $legacy_keys[$type], true);
            }
        }
        
        return $value;
    }
    
    /**
     * Render text field
     */
    private function render_text_field($name, $value, $label, $placeholder) {
        $field_id = sanitize_title($name);
        ?>
<div class="hvnly__dyamic_metabox_tab__field" data-field-id="<?php echo esc_attr($field_id); ?>" data-field-type="text">
    <div class="hvnly__dyamic_metabox_tab__field-input">
        <label><?php echo esc_html($label); ?></label>
        <input type="text" id="<?php echo esc_attr($field_id); ?>" name="<?php echo esc_attr($name); ?>"
            value="<?php echo esc_attr($value); ?>" placeholder="<?php echo esc_attr($placeholder); ?>"
            class="hvnly__dyamic_metabox_tab__input" data-field-type="text">
    </div>
</div>
<?php
    }
    
    /**
     * Render thumbnail field with preview
     */
    private function render_thumbnail_field($name, $value, $label) {
        $field_id = sanitize_title($name);
        ?>
<div class="hvnly__dyamic_metabox_tab__field" data-field-id="<?php echo esc_attr($field_id); ?>" data-field-type="file">
    <div class="hvnly__dyamic_metabox_tab__field-input">
        <label><?php echo esc_html($label); ?></label>
        <div class="hvnly-meta-field" style="display: block;margin:0px">
            <div class="hvnly-meta-input hvnly-popup-meta-input">
                <input type="text" id="<?php echo esc_attr($field_id); ?>" name="<?php echo esc_attr($name); ?>"
                    class="widefat" value="<?php echo esc_attr($value); ?>"
                    placeholder="<?php esc_attr_e('Enter image URL or upload', 'havenlytics'); ?>">
                <div class="hvnly-preview-container">
                    <?php if (!empty($value)): ?>
                    <div class="hvnly-preview-wrapper">
                        <img src="<?php echo esc_url($value); ?>" alt="" style="max-width: 150px; height: auto;">
                        <button type="button" class="hvnly-remove-preview"
                            data-target="#<?php echo esc_attr($field_id); ?>">
                            <span class="dashicons dashicons-no-alt"></span>
                        </button>
                    </div>
                    <?php endif; ?>
                </div>
                <button type="button" class="button hvnly-upload-button"
                    data-target="#<?php echo esc_attr($field_id); ?>" data-type="image">
                    <?php esc_html_e('Upload Thumbnail', 'havenlytics'); ?>
                </button>
            </div>
        </div>
    </div>
</div>
<?php
    }
    
    public function save($post_id, $field_name, $value) {
        // Save to the unique field name
        update_post_meta($post_id, $field_name, $value);
        
        // For backward compatibility, also save to legacy key if this is a video field
        if (strpos($field_name, 'video_') === 0) {
            if (strpos($field_name, '_title') !== false) {
                update_post_meta($post_id, '_hvnly_video_title', $value);
            } elseif (strpos($field_name, '_url') !== false) {
                update_post_meta($post_id, '_hvnly_video_url', $value);
            } elseif (strpos($field_name, '_thumbnail') !== false) {
                update_post_meta($post_id, '_hvnly_video_thumbnail', $value);
            }
        }
    }
    
    public function sanitize($value) {
        return sanitize_text_field($value);
    }
    
    public function validate($value, $field) {
        return true;
    }
    
    public function enqueue_assets() {
        wp_enqueue_media();
        
        wp_enqueue_script(
            'hvnly-video-field',
            HVNLYNAB_ASSETS_URL . '/admin/js/hvnly-video-field.js',
            ['jquery'],
            HVNLYNAB_VERSION,
            true
        );
    }
}