<?php
/**
 * Sifency Post Type Frontend Template Render Init
 * Conditionally loads and instantiates modules based on user settings.
 */
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

if (
    class_exists( 'Sifency_Addons_Theme_Builder_Master' ) &&
    method_exists( 'Sifency_Addons_Theme_Builder_Master', 'sifency_addons_is_legal' ) &&
    Sifency_Addons_Theme_Builder_Master::sifency_addons_is_legal()
) {

    $sifency_settings = get_option( 'sifency_addons_settings', [] );
    $sifency_enabled_cpts = $sifency_settings['cpt_enabled'] ?? [];

    $sifency_config_file = SIFENCY_ADDONS_DIR . 'theme-builder/post-type/sifency-cpt-config.php';

    if ( file_exists( $sifency_config_file ) ) {
        $sifency_all_cpts_config = include $sifency_config_file;

        if ( is_array( $sifency_all_cpts_config ) ) {
            foreach ( $sifency_all_cpts_config as $sifency_cpt_slug => $sifency_cpt_data ) {

                $sifency_is_enabled = ! empty( $sifency_enabled_cpts[ $sifency_cpt_slug ] )
                                      && $sifency_enabled_cpts[ $sifency_cpt_slug ] === 'on';

                if ( ! $sifency_is_enabled ) {
                    continue;
                }

                // Load files
                if ( ! empty( $sifency_cpt_data['files'] ) && is_array( $sifency_cpt_data['files'] ) ) {
                    foreach ( $sifency_cpt_data['files'] as $sifency_file ) {
                        $sifency_file_path = SIFENCY_TB_PATH . $sifency_file;
                        if ( file_exists( $sifency_file_path ) ) {
                            require_once $sifency_file_path;
                        }
                    }
                }

                // Load classes
                if ( ! empty( $sifency_cpt_data['classes'] ) && is_array( $sifency_cpt_data['classes'] ) ) {
                    foreach ( $sifency_cpt_data['classes'] as $sifency_class_name ) {
                        if ( class_exists( $sifency_class_name ) ) {
                            new $sifency_class_name();
                        }
                    }
                }
            }
        }
    }
}

// Other Builder Items
$sifency_builder_items = [
    'popup',
    'scrollup',
    'subheader',
    'error-page',
    'offcanvas',
];

foreach ( $sifency_builder_items as $sifency_item ) {
    $sifency_file_path = SIFENCY_TB_PATH . 'builder-item/' . $sifency_item . '.php';
    if ( file_exists( $sifency_file_path ) ) {
        require_once $sifency_file_path;
    }
}

// Header & Footer
$sifency_header_files = [
    'header/class-header-render.php',
    'footer/class-footer-render.php',
    'footer/class-before-footer-render.php',
];

foreach ( $sifency_header_files as $sifency_file ) {
    $sifency_path = SIFENCY_TB_PATH . $sifency_file;
    if ( file_exists( $sifency_path ) ) {
        require_once $sifency_path;
    }
}
