<?php

namespace fluXtore\Core\Divi;

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

if ( ! class_exists( 'fluXtore_Divi_Integration' ) ) {
    class fluXtore_Divi_Integration {
        /**
         * @var self|null
         */
        private static $instance = null;

        private function __construct() {}

        public static function init() {
            if ( null !== self::$instance ) {
                return;
            }

            self::$instance = new self();

            add_action( 'divi_extensions_init', [ self::$instance, 'load_extension' ] );
            add_action( 'admin_init', [ self::$instance, 'ensure_builder_meta' ] );
        }

        public function load_extension() {
            require_once FLUXTORE_PLUGIN_DIR . 'core/divi/includes/DiviThemeTemp.php';
        }

        public function ensure_builder_meta() {
            if ( ! is_admin() || ! defined( 'ET_BUILDER_THEME' ) ) {
                return;
            }

            $posts = get_posts(
                [
                    'post_type'      => 'fluxtore_step',
                    'posts_per_page' => -1,
                    'post_status'    => 'any',
                ]
            );

            foreach ( $posts as $post ) {
                $meta_keys = get_post_meta( $post->ID, '_et_pb_use_builder', false );

                if ( count( $meta_keys ) > 1 ) {
                    delete_post_meta( $post->ID, '_et_pb_use_builder' );
                }

                update_post_meta( $post->ID, '_et_pb_use_builder', 'on' );
            }
        }
    }
}

fluXtore_Divi_Integration::init();
