<?php
/**
 * Elementor Kit Library Connection Override
 * 
 * This file can be included in another plugin to override the kit library connection check.
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit; // Exit if accessed directly.
}

// Prevent duplicate function definition
if ( ! function_exists( 'override_elementor_kit_library_connection' ) ) {
    /**
     * Override the kit library connection check by removing the is_connected condition
     */
    function override_elementor_kit_library_connection() {
        if ( ! class_exists( '\\Elementor\\Plugin' ) || ! class_exists( '\\ElementorPro\\License\\API' ) ) {
            return;
        }

        // Get Elementor instance
        $elementor = \Elementor\Plugin::instance();
        
        // Check if app is available
        if ( ! isset( $elementor->app ) || ! $elementor->app ) {
            return;
        }
        
        // Get current kit library settings
        $prev_settings = $elementor->app->get_settings( 'kit-library' );
        
        if ( ! $prev_settings || empty( $prev_settings ) ) {
            return;
        }
        
        // Check if common component exists
        if ( ! isset( $elementor->common ) || ! $elementor->common ) {
            return;
        }
        
        // Check if connect component exists
        if ( ! $elementor->common->get_component( 'connect' ) ) {
            return;
        }
        
        // Get kit library from connect
        $kit_library = $elementor->common->get_component( 'connect' )->get_app( 'kit-library' );
        
        if ( ! $kit_library ) {
            return;
        }
        
        // Override the existing settings
        $prev_settings['is_library_connected'] = \ElementorPro\License\API::is_license_active() && $kit_library;
        
        // Update settings
        $elementor->app->set_settings( 'kit-library', $prev_settings );
    }
}

// Add the hook only if it hasn't been added yet
if ( ! has_action( 'elementor/init', 'override_elementor_kit_library_connection' ) ) {
    // Make sure we run this after Elementor Pro has fully loaded
    add_action( 'elementor_pro/init', function() {
        // Add our override at a later priority to ensure it runs after ElementorPro's kit library module
        add_action( 'elementor/init', 'override_elementor_kit_library_connection', 20 );
    });
}
