<?php
/**
 * Builder detection for PressConduit.
 */

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

class PCD_PC_Builder {

	public static function primary(): string {
		if ( self::is_bricks() ) {
			return 'bricks';
		}
		if ( self::is_divi() ) {
			return 'divi';
		}
		return 'none';
	}

	public static function is_supported(): bool {
		return in_array( self::primary(), [ 'bricks', 'divi' ], true );
	}

	/**
	 * Return the active Divi data engine. This is intentionally site-level and
	 * authoritative: tool callers must not choose a different generation.
	 */
	public static function divi_generation(): string {
		if ( ! self::is_divi() ) {
			return 'none';
		}

		$template = wp_get_theme( get_template() );
		$name     = strtolower( (string) $template->get( 'Name' ) );
		$version  = (string) $template->get( 'Version' );
		if ( $version && ( false !== strpos( $name, 'divi' ) || false !== strpos( $name, 'extra' ) ) ) {
			return version_compare( $version, '5.0.0', '>=' ) ? 'divi5' : 'divi4';
		}

		if ( class_exists( '\\ET\\Builder\\VisualBuilder\\REST\\OutsideVb\\OutsideVbController' ) ) {
			return 'divi5';
		}

		$versions = [
			defined( 'ET_BUILDER_VERSION' ) ? ET_BUILDER_VERSION : '',
			defined( 'ET_CORE_VERSION' ) ? ET_CORE_VERSION : '',
		];
		foreach ( $versions as $version ) {
			if ( $version && version_compare( $version, '5.0.0', '>=' ) ) {
				return 'divi5';
			}
		}

		return 'divi4';
	}

	public static function is_divi4(): bool {
		return 'divi4' === self::divi_generation();
	}

	public static function is_divi5(): bool {
		return 'divi5' === self::divi_generation();
	}

	public static function is_bricks(): bool {
		$template = strtolower( (string) wp_get_theme( get_template() )->get( 'Name' ) );
		return defined( 'BRICKS_VERSION' )
			|| class_exists( '\\Bricks\\Theme' )
			|| class_exists( '\\Bricks\\Database' )
			|| function_exists( 'bricks_is_frontend' )
			|| post_type_exists( 'bricks_template' )
			|| false !== strpos( $template, 'bricks' );
	}

	public static function is_divi(): bool {
		$template = strtolower( (string) wp_get_theme( get_template() )->get( 'Name' ) );
		return defined( 'ET_BUILDER_VERSION' )
			|| defined( 'ET_CORE_VERSION' )
			|| function_exists( 'et_setup_theme' )
			|| function_exists( 'et_theme_builder_get_theme_builder_post_id' )
			|| post_type_exists( 'et_pb_layout' )
			|| false !== strpos( $template, 'divi' );
	}
}
