<?php
/**
 * Media Sync class - handles media library synchronization between translations
 * 
 * @package LangForge
 */

if (!defined('ABSPATH')) {
    exit;
}

// IDE hints for autoloaded classes
if (false) {
    class LF_Core {}
}

class LF_Media_Sync {
    
    private static $instance = null;
    
    public static function instance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        $this->init_hooks();
    }
    
    private function init_hooks() {
        // Media library doesn't need language filtering by default
        // All translations share the same media library
        
        // Add language info to attachment details
        add_filter('attachment_fields_to_edit', [$this, 'add_attachment_fields'], 10, 2);
        add_filter('attachment_fields_to_save', [$this, 'save_attachment_fields'], 10, 2);
        
        // Sync featured image when creating translation
        add_action('lf_translation_created', [$this, 'sync_featured_image'], 10, 2);
        
        // Add media translation support for alt text, captions
        add_action('add_meta_boxes_attachment', [$this, 'add_attachment_meta_box']);
    }
    
    /**
 * Add language fields to attachment edit screen
 */
    public function add_attachment_fields($form_fields, $post) {
        $languages = LF_Core::instance()->get_active_languages();
        
        // Add translatable fields info
        $form_fields['lf_info'] = [
            'label' => __('Translations', 'langforge'),
            'input' => 'html',
            'html' => '<p class="description">' . __('Media files are shared across all languages. Only metadata (alt text, caption, description) can be translated.', 'langforge') . '</p>',
        ];
        
        return $form_fields;
    }
    
    /**
 * Save attachment language fields
 */
    public function save_attachment_fields($post, $attachment) {
        return $post;
    }
    
    /**
 * Add meta box for attachment translations
 */
    public function add_attachment_meta_box() {
        add_meta_box(
            'lf_attachment_translations',
            __('Media Translations', 'langforge'),
            [$this, 'render_attachment_meta_box'],
            'attachment',
            'side',
            'low'
        );
    }
    
    /**
 * Render attachment meta box
 */
    public function render_attachment_meta_box($post) {
        $languages = LF_Core::instance()->get_active_languages();
        $current_lang = LF_Core::instance()->get_current_language();
        ?>
        <div class="lf-attachment-translations">
            <p><strong><?php esc_html_e('Alt Text Translations:', 'langforge'); ?></strong>
                <?php if (class_exists('Forge_Docs_Link')) Forge_Docs_Link::render('langforge', 'translating-a-post-or-page', __('Alt text per language', 'langforge'), __('Per-language alt text for this image; falls back to the default when empty.', 'langforge')); ?></p>
            <?php foreach ($languages as $code => $lang): 
                $alt_key = '_wp_attachment_image_alt_' . $code;
                $alt_value = get_post_meta($post->ID, $alt_key, true);
                if ($code === $current_lang && !$alt_value) {
                    $alt_value = get_post_meta($post->ID, '_wp_attachment_image_alt', true);
                }
            ?>
            <p>
                <label><?php echo esc_html($lang['native_name']); ?>:</label><br>
                <input type="text" name="lf_alt_<?php echo esc_attr($code); ?>" 
                       value="<?php echo esc_attr($alt_value); ?>" class="widefat">
            </p>
            <?php endforeach; ?>
            
            <p><strong><?php esc_html_e('Caption Translations:', 'langforge'); ?></strong>
                <?php if (class_exists('Forge_Docs_Link')) Forge_Docs_Link::render('langforge', 'translating-a-post-or-page', __('Caption per language', 'langforge'), __('Per-language caption for this attachment; used when rendered in that language.', 'langforge')); ?></p>
            <?php foreach ($languages as $code => $lang): 
                $caption_key = '_lf_caption_' . $code;
                $caption_value = get_post_meta($post->ID, $caption_key, true);
                if ($code === $current_lang && !$caption_value) {
                    $caption_value = $post->post_excerpt;
                }
            ?>
            <p>
                <label><?php echo esc_html($lang['native_name']); ?>:</label><br>
                <textarea name="lf_caption_<?php echo esc_attr($code); ?>" class="widefat" rows="2"><?php echo esc_textarea($caption_value); ?></textarea>
            </p>
            <?php endforeach; ?>
        </div>
        <?php
        wp_nonce_field('lf_attachment_meta', 'lf_attachment_nonce');
    }
    
    /**
 * Sync featured image when translation is created
 */
    public function sync_featured_image($original_id, $translation_id) {
        $thumbnail_id = get_post_thumbnail_id($original_id);
        if ($thumbnail_id) {
            set_post_thumbnail($translation_id, $thumbnail_id);
        }
    }
    
    /**
 * Get translated alt text
 */
    public function get_alt_text($attachment_id, $language = null) {
        if (!$language) {
            $language = LF_Core::instance()->get_current_language();
        }
        
        // Try language-specific alt
        $alt = get_post_meta($attachment_id, '_wp_attachment_image_alt_' . $language, true);
        
        // Fall back to default
        if (!$alt) {
            $alt = get_post_meta($attachment_id, '_wp_attachment_image_alt', true);
        }
        
        return $alt;
    }
    
    /**
 * Get translated caption
 */
    public function get_caption($attachment_id, $language = null) {
        if (!$language) {
            $language = LF_Core::instance()->get_current_language();
        }
        
        // Try language-specific caption
        $caption = get_post_meta($attachment_id, '_lf_caption_' . $language, true);
        
        // Fall back to default
        if (!$caption) {
            $attachment = get_post($attachment_id);
            $caption = $attachment ? $attachment->post_excerpt : '';
        }
        
        return $caption;
    }
    
    /**
 * Copy all media attachments from one post to another
 */
    public function copy_attachments($source_id, $target_id) {
        // Featured image
        $thumbnail_id = get_post_thumbnail_id($source_id);
        if ($thumbnail_id) {
            set_post_thumbnail($target_id, $thumbnail_id);
        }
        
        // Gallery images (if stored as meta)
        $gallery = get_post_meta($source_id, '_gallery_images', true);
        if ($gallery) {
            update_post_meta($target_id, '_gallery_images', $gallery);
        }
    }
    
    /**
 * Filter image alt text based on language
 */
    public function filter_attachment_alt($alt, $attachment_id) {
        return $this->get_alt_text($attachment_id);
    }
    
    /**
 * Duplicate media for translation (if needed)
 * Usually not needed as media is shared
 */
    public function duplicate_attachment($attachment_id) {
        $attachment = get_post($attachment_id);
        if (!$attachment || $attachment->post_type !== 'attachment') {
            return false;
        }
        
        $new_attachment = [
            'post_title' => $attachment->post_title,
            'post_content' => $attachment->post_content,
            'post_excerpt' => $attachment->post_excerpt,
            'post_status' => 'inherit',
            'post_type' => 'attachment',
            'post_mime_type' => $attachment->post_mime_type,
            'guid' => $attachment->guid,
        ];
        
        $new_id = wp_insert_attachment($new_attachment);
        
        if ($new_id) {
            // Copy attachment metadata
            $metadata = wp_get_attachment_metadata($attachment_id);
            wp_update_attachment_metadata($new_id, $metadata);
            
            // Copy attached file
            update_post_meta($new_id, '_wp_attached_file', get_post_meta($attachment_id, '_wp_attached_file', true));
        }
        
        return $new_id;
    }
}
