<?php

namespace WeDevs\Wpuf\Pro;

/**
 * The Integrations class to handle all 3rd party theme/plugins integrations and compatibility
 */
class Integrations {
    /**
     * Holds various class instances
     *
     * @since 4.0.12
     *
     * @var array
     */
    public $container = [];

    private $integrations = [
        'Tribe__Events__Main' => 'Events_Calendar\Events_Calendar_Integration',
    ];

    public function __construct() {
        add_filter( 'loco_plugins_data', [ $this, 'overwrite_text_domain_for_loco' ] );
        $this->init_integrations();
    }

    private function init_integrations() {
        foreach ( $this->integrations as $external_class => $integration_class ) {
            if ( class_exists( $external_class ) ) {
                $full_class_name = __NAMESPACE__ . '\\Integrations\\' . $integration_class;
                try {
                    $this->container[ strtolower( $external_class ) ] = new $full_class_name();
                } catch ( \Exception $e ) {
                    \WP_User_Frontend::log( 'integration', print_r( $external_class . ' integration failed', true ) );
                }
            }
        }
    }

    /**
     * Overwrite text domain for loco translate
     *
     * @since 4.0.8
     *
     * @param array $cached
     *
     * @return array
     */
    public function overwrite_text_domain_for_loco( $cached ) {
        if ( ! isset( $cached['wp-user-frontend-pro/wpuf-pro.php'] ) ) {
            return $cached;
        }

        $cached['wp-user-frontend-pro/wpuf-pro.php']['TextDomain'] = 'wpuf-pro';

        return $cached;
    }

    /**
     * Magic getter to bypass referencing objects
     *
     * @since 4.1.8
     *
     * @param string $prop
     *
     * @return null|object Class Instance
     */
    public function __get( $prop ) {
        if ( array_key_exists( $prop, $this->container ) ) {
            return $this->container[ $prop ];
        }

        return null;
    }
}
