<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
require_once SIFENCY_TB_PATH . 'includes/functions/metabox.php';
require_once SIFENCY_TB_PATH . 'includes/functions/metabox-helpers.php';

$theme_core_class = function_exists( 'sifency_addons_get_theme_core_class' )
	? sifency_addons_get_theme_core_class()
	: '';

if ( $theme_core_class && class_exists( $theme_core_class ) ) {
	$cpt_file       = SIFENCY_TB_PATH . 'post-type/templates/class-cpt.php';
	$functions_file = SIFENCY_TB_PATH . 'post-type/templates/functions.php';

	if ( file_exists( $cpt_file ) ) {
		require_once $cpt_file;
	}

	if ( file_exists( $functions_file ) ) {
		require_once $functions_file;
	}
}
add_action( 'admin_init', 'sifency_addons_custom_metaboxes_init' );

function sifency_addons_custom_metaboxes_init() {
	$metabox_definitions = sifency_addons_get_all_metabox_definitions();

	if ( empty( $metabox_definitions ) ) {
		return;
	}

	try {
		new Sifency_Addons_Master_Metabox( $metabox_definitions );
	} catch ( \Throwable $e ) {
		if ( function_exists( 'error_log' ) ) {
			error_log( '[Sifency] Failed to initialize metaboxes: ' . $e->getMessage() );
		}
	}
}

function sifency_addons_get_all_metabox_definitions() {
	$all_definitions = array();

	$definition_files = glob( SIFENCY_TB_PATH . 'post-type/*/*-meta.php' );

	if ( ! empty( $definition_files ) && is_array( $definition_files ) ) {
		foreach ( $definition_files as $file ) {
			$definitions = include $file;

			if ( is_array( $definitions ) ) {
				$all_definitions = array_merge( $all_definitions, $definitions );
			}
		}
	}

	$theme_core_class = sifency_addons_get_theme_core_class();

	if ( $theme_core_class && class_exists( $theme_core_class ) ) {
		$theme_meta_file = SIFENCY_TB_PATH . 'post-type/templates/class-meta.php';

		if ( file_exists( $theme_meta_file ) ) {
			$theme_definitions = include $theme_meta_file;

			if ( is_array( $theme_definitions ) ) {
				$all_definitions = array_merge( $all_definitions, $theme_definitions );
			}
		}
	}

	return apply_filters( 'sifency_addons_all_metabox_definitions', $all_definitions );
}
