<?php
/**
 * Class for building third-party libraries
 *
 * @package cyberpress
 */

/**
 * Class CyberPress_Vendors
 */
class CyberPress_Vendors {
    /**
     * Should change carbon assets url when permalinks
     *
     * @var null
     */
    private $should_change_assets_urls = null;

    /**
     * CyberPress_Vendors constructor.
     */
    public function __construct() {
        require_once cyberpress()->plugin_path . 'vendor/autoload.php';
        require_once cyberpress()->plugin_path . 'vendor-plain/brand-svg-please/brand-svg-please.php';

        add_action( 'after_setup_theme', array( $this, 'carbon_fields_boot' ) );

        add_filter( 'script_loader_src', array( $this, 'assets_loader_src' ), 10, 2 );
        add_filter( 'style_loader_src', array( $this, 'assets_loader_src' ), 10, 2 );
    }

    /**
     * Boot Carbon Fields
     */
    public function carbon_fields_boot() {
        \Carbon_Fields\Carbon_Fields::boot();
    }

    /**
     * Fix urls for assets when plugin in symlink.
     *
     * @param string $url - Library path.
     * @param string $handle - Library handle slug.
     *
     * @return mixed
     */
    public function assets_loader_src( $url, $handle ) {
        if ( null === $this->should_change_assets_urls ) {
            $plugin_path                     = str_replace( '/', '\\', cyberpress()->plugin_path );
            $this->should_change_assets_urls = '' === \Carbon_Fields\URL && false !== strpos( \Carbon_Fields\DIR, $plugin_path );
        }

        // change it only if Carbon Fields used from CyberPress plugin.
        if ( $this->should_change_assets_urls && false !== strpos( $handle, 'carbon-' ) ) {
            $replace_url = '';

            switch ( $handle ) {
                case 'carbon-fields-core-css':
                case 'carbon-sidebar-manager-css':
                case 'carbon-fields-core':
                case 'carbon-fields-vendor':
                case 'carbon-fields-boot':
                case 'carbon-sidebar-manager':
                case 'carbon-fields-metaboxes':
                case 'carbon-fields-blocks':
                    $replace_url = 'vendor/htmlburger/carbon-fields/';
                    break;
                case 'carbon-field-icon-css':
                case 'carbon-field-icon':
                    $replace_url = 'vendor/htmlburger/carbon-field-icon/';
                    break;
                case 'carbon-field-react-select-css':
                case 'carbon-field-react-select':
                    $replace_url = 'vendor/nk-o/carbon-field-react-select/';
                    break;
            }

            if ( $replace_url ) {
                $url = str_replace( site_url( '/' ), cyberpress()->plugin_url . $replace_url, $url );
            }
        }

        return $url;
    }
}
new CyberPress_Vendors();
