<?php
/**
 * Divi Integration - copy Divi Builder data when creating translations
 *
 * @package LangForge
 */

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

class LF_Divi_Integration {

    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() {
        // Copy Divi data when creating a translation
        add_action('lf_translation_created', [$this, 'copy_divi_data'], 10, 3);
    }

    /**
 * Copy Divi Builder data to the new translation post
 */
    public function copy_divi_data($original_post_id, $new_post_id, $target_lang) {
        // Check if Divi is active
        if (!defined('ET_BUILDER_VERSION') && !function_exists('et_setup_theme')) {
            return;
        }

        // List of Divi meta keys to copy
        $divi_meta_keys = [
            '_et_pb_use_builder',
            '_et_pb_old_content',
            '_et_pb_built_for_post_type',
            '_et_pb_ab_subjects',
            '_et_pb_ab_current_shortcode',
            '_et_pb_custom_css',
            '_et_pb_page_layout',
            '_et_pb_side_nav',
            '_et_pb_post_hide_nav',
            '_et_pb_show_title',
            '_et_pb_gutter_width',
            // Global modules
            '_et_pb_ab_bounce_rate_limit',
            '_et_pb_enable_ab_testing',
        ];

        foreach ($divi_meta_keys as $meta_key) {
            $value = get_post_meta($original_post_id, $meta_key, true);
            if ($value !== '' && $value !== false) {
                update_post_meta($new_post_id, $meta_key, $value);
            }
        }

        // Copy the main Divi builder content (stored in post_content as shortcodes)
        // This is already handled by wp_insert_post copying post_content,
        // but make sure the builder flag is set
        $use_builder = get_post_meta($original_post_id, '_et_pb_use_builder', true);
        if ($use_builder === 'on') {
            update_post_meta($new_post_id, '_et_pb_use_builder', 'on');
        }

        // Copy Divi layout settings
        $layout_settings = get_post_meta($original_post_id, '_et_pb_page_layout', true);
        if ($layout_settings) {
            update_post_meta($new_post_id, '_et_pb_page_layout', $layout_settings);
        }
    }
}
