<?php
class kavehcoreclass {

public function __construct() {
    add_action('admin_init', array($this, 'handle_plugin_conflict'));
}

/**
 * Update Elementor database
 */
private function update_elementor_db() {
    if (class_exists('\Elementor\Plugin')) {
        \Elementor\Plugin::$instance->db->migrate();
        return true;
    }
    return false;
}

/**
 * Flush Elementor CSS cache
 */
private function flush_elementor_css() {
    if (class_exists('\Elementor\Plugin')) {
        \Elementor\Plugin::$instance->files_manager->clear_cache();
        return true;
    }
    return false;
}

/**
 * Sync Elementor library
 */
private function sync_elementor_library() {
    if (class_exists('\Elementor\Plugin')) {
        \Elementor\Plugin::$instance->templates_manager->sync_templates();
        return true;
    }
    return false;
}

/**
 * Handle the plugin conflict
 */
public function handle_plugin_conflict() {
    // Check if the standalone plugin exists
    $plugin_path = 'kaveh-core/theme-core.php';
    $plugin_slug = 'kavehTheme';

    // Check if plugin is active
    if (!is_plugin_active($plugin_path)) {
        return;
    }
    
    // Check if plugin is active
    if (is_plugin_active($plugin_path)) {
        // Deactivate first to prevent errors
        deactivate_plugins($plugin_path);
        
        // Add admin notice
        add_action('admin_notices', array($this, 'show_deactivation_notice'));
        
        $this->update_elementor_db();
        $this->flush_elementor_css();
        $this->sync_elementor_library();
    }
    
    // Check if plugin folder still exists
    $plugin_dir = WP_PLUGIN_DIR . '/' . $plugin_slug;
    if (file_exists($plugin_dir)) {
        // If deletion failed, show error notice
        add_action('admin_notices', array($this, 'show_deletion_error_notice'));
    }
}

/**
 * Show deactivation notice
 */
public function show_deactivation_notice() {
    echo '<div class="notice notice-warning is-dismissible">
        <p>' . esc_html__('In the new Kaveh update, the Kaveh Core plugin has been merged with the theme and the core plugin was automatically deactivated. If this plugin still exists, please delete it.', 'kavehTheme') . '</p>
    </div>';
}

/**
 * Show deletion error notice
 */
public function show_deletion_error_notice() {
    echo '<div class="notice notice-error is-dismissible">
        <p>' . esc_html__('We could not automatically delete the Kaveh Core plugin. Please remove it manually. In new versions, this plugin is not needed.', 'kavehTheme') . '</p>
    </div>';
}

}
