<?php

use Roots\Acorn\Application;

/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| our theme. We will simply require it into the script here so that we
| don't have to worry about manually loading any of our classes later on.
|
*/

if (! file_exists($composer = __DIR__.'/vendor/autoload.php')) {
    wp_die(__('Error locating autoloader. Please run <code>composer install</code>.', 'turbo'));
}

require $composer;

/*
|--------------------------------------------------------------------------
| Register The Bootloader
|--------------------------------------------------------------------------
|
| The first thing we will do is schedule a new Acorn application container
| to boot when WordPress is finished loading the theme. The application
| serves as the "glue" for all the components of Laravel and is
| the IoC container for the system binding all of the various parts.
|
*/

Application::configure()
    ->withProviders([
        App\Providers\ThemeServiceProvider::class,
    ])
    ->boot();

/*
|--------------------------------------------------------------------------
| Register Sage Theme Files
|--------------------------------------------------------------------------
|
| Out of the box, Sage ships with categorically named theme files
| containing common functionality and setup to be bootstrapped with your
| theme. Simply add (or remove) files from the array below to change what
| is registered alongside Sage.
|
*/

collect(['setup', 'filters', 'customizer', 'post-types'])
    ->each(function ($file) {
        if (! locate_template($file = "app/{$file}.php", true, true)) {
            wp_die(
                sprintf(__('Error locating <code>%s</code> for inclusion.', 'turbo'), $file)
            );
        }
    });

/**
 * Resolve metadata URL used by plugin-update-checker for the BBI Turbo theme.
 */
function bt_theme_get_update_metadata_url(): string {
    $default_url = defined( 'BBI_TURBO_THEME_UPDATE_METADATA_URL' )
        ? (string) BBI_TURBO_THEME_UPDATE_METADATA_URL
        : '';

    if ( '' === $default_url && defined( 'BBI_UPDATES_BASE_URL' ) ) {
        $default_url = trailingslashit( (string) BBI_UPDATES_BASE_URL ) . 'bbi-turbo/info.json';
    }

    return (string) apply_filters( 'bbi_turbo_theme_update_metadata_url', $default_url );
}

/**
 * Boot plugin-update-checker for the BBI Turbo theme.
 */
function bt_theme_bootstrap_update_checker(): void {
    $metadata_url = trim( bt_theme_get_update_metadata_url() );
    if ( '' === $metadata_url ) {
        return;
    }

    if ( ! class_exists( 'Puc_v4_Factory' ) ) {
        $puc_path = __DIR__ . '/vendor/plugin-update-checker/plugin-update-checker.php';
        if ( file_exists( $puc_path ) ) {
            require_once $puc_path;
        }
    }

    if ( ! class_exists( 'Puc_v4_Factory' ) ) {
        return;
    }

    $update_checker = Puc_v4_Factory::buildUpdateChecker(
        $metadata_url,
        __FILE__,
        'bbi-turbo'
    );

    $branch = (string) apply_filters( 'bbi_turbo_theme_update_branch', '' );
    if ( '' !== $branch && is_object( $update_checker ) && method_exists( $update_checker, 'setBranch' ) ) {
        $update_checker->setBranch( $branch );
    }
}

bt_theme_bootstrap_update_checker();

$bbi_turbo_theme_use_freemius = defined( 'BBI_TURBO_THEME_USE_FREEMIUS' )
    ? (bool) BBI_TURBO_THEME_USE_FREEMIUS
    : false;

$bbi_turbo_theme_use_freemius = (bool) apply_filters( 'bbi_turbo_theme_use_freemius', $bbi_turbo_theme_use_freemius );





if ( $bbi_turbo_theme_use_freemius && ! function_exists( 'bt_fstheme' ) ) {
    // Create a helper function for easy SDK access.
    function bt_fstheme() {
        global $bt_fstheme;

        if ( ! isset( $bt_fstheme ) ) {
            // Include Freemius SDK.
            $vendor_sdk_path = dirname( __FILE__ ) . '/vendor/freemius/start.php';
            $local_sdk_path  = dirname( __FILE__ ) . '/freemius/start.php';

            if ( file_exists( $vendor_sdk_path ) ) {
                require_once $vendor_sdk_path;
            } elseif ( file_exists( $local_sdk_path ) ) {
                require_once $local_sdk_path;
            } else {
                return null;
            }

            if ( ! function_exists( 'fs_dynamic_init' ) ) {
                return null;
            }

            $bt_fstheme = fs_dynamic_init( array(
                'id'                  => '24969',
                'slug'                => 'bbi-turbo',
                'type'                => 'theme',
                'public_key'          => 'pk_e6dccc3ec60f3a16770ce87863b5c',
                'is_premium'          => false,
                'has_addons'          => false,
                'has_paid_plans'      => false,
                'has_premium_version' => false,
                'is_org_compliant'    => false,
                'anonymous_mode'      => true,
                'menu'                => array(
                    'account' => false,
                    'support' => false,
                ),
            ) );

            if ( is_object( $bt_fstheme ) && method_exists( $bt_fstheme, 'add_filter' ) ) {
                $bt_fstheme->add_filter( 'show_trial', '__return_false' );
                $bt_fstheme->add_filter( 'show_affiliate_program_notice', '__return_false' );
            }
        }

        return $bt_fstheme;
    }

    // Init Freemius.
    bt_fstheme();
    // Signal that SDK was initiated.
    do_action( 'bt_fstheme_loaded' );
}

if ( ! function_exists( 'theme_fs' ) ) {
    function theme_fs() {
        return function_exists( 'bt_fstheme' ) ? bt_fstheme() : null;
    }
}

if ( ! function_exists( 'bt_theme_strip_license_actions' ) ) {
    function bt_theme_strip_license_actions( array $actions ): array {
        foreach ( $actions as $key => $label ) {
            $key_text   = is_string( $key ) ? $key : '';
            $label_text = is_string( $label ) ? wp_strip_all_tags( $label ) : '';

            if (
                stripos( $key_text, 'activate_license' ) !== false ||
                stripos( $key_text, 'change_license' ) !== false ||
                stripos( $key_text, 'activate-license' ) !== false ||
                stripos( $label_text, 'Activate License' ) !== false ||
                stripos( $label_text, 'Change License' ) !== false
            ) {
                unset( $actions[ $key ] );
            }
        }

        if ( current_user_can( 'update_themes' ) ) {
            $check_url = wp_nonce_url(
                admin_url( 'themes.php?bbi_turbo_theme_manual_check=1' ),
                'bbi_turbo_theme_manual_check'
            );

            $actions['check_for_updates'] = sprintf(
                '<a href="%1$s">%2$s</a>',
                esc_url( $check_url ),
                esc_html__( 'Check for updates', 'turbo' )
            );
        }

        return $actions;
    }
}

add_filter( 'current_theme_actions', 'bt_theme_strip_license_actions', 9999 );
add_filter( 'theme_action_links_' . get_stylesheet(), 'bt_theme_strip_license_actions', 9999 );

if ( ! function_exists( 'bt_theme_handle_manual_update_check' ) ) {
    function bt_theme_handle_manual_update_check(): void {
        if ( ! is_admin() || ! current_user_can( 'update_themes' ) ) {
            return;
        }

        if ( ! isset( $_GET['bbi_turbo_theme_manual_check'] ) || '1' !== $_GET['bbi_turbo_theme_manual_check'] ) {
            return;
        }

        check_admin_referer( 'bbi_turbo_theme_manual_check' );

        if ( ! function_exists( 'wp_update_themes' ) ) {
            require_once ABSPATH . 'wp-admin/includes/update.php';
        }

        if ( function_exists( 'wp_clean_themes_cache' ) ) {
            wp_clean_themes_cache( true );
        }

        delete_site_transient( 'update_themes' );
        wp_update_themes();

        set_transient( 'bbi_turbo_theme_manual_check_notice', 1, MINUTE_IN_SECONDS );

        $redirect_url = remove_query_arg( array( 'bbi_turbo_theme_manual_check', '_wpnonce' ) );
        wp_safe_redirect( $redirect_url );
        exit;
    }
}
add_action( 'admin_init', 'bt_theme_handle_manual_update_check' );

if ( ! function_exists( 'bt_theme_maybe_show_manual_check_notice' ) ) {
    function bt_theme_maybe_show_manual_check_notice(): void {
        if ( ! is_admin() || ! current_user_can( 'update_themes' ) ) {
            return;
        }

        if ( ! get_transient( 'bbi_turbo_theme_manual_check_notice' ) ) {
            return;
        }

        delete_transient( 'bbi_turbo_theme_manual_check_notice' );

        echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'BBI Turbo Theme: update check completed.', 'turbo' ) . '</p></div>';
    }
}
add_action( 'admin_notices', 'bt_theme_maybe_show_manual_check_notice' );