<?php
/**
 * Plugin Name: Cross Site Copy Field for ACF
 * Description: Duplicate and transfer ACF field definitions between field groups and across WordPress sites. Supports nested fields, automatic key generation, and JSON-based transfer.
 * Version: 1.0.1
 * Author: Code and Core
 * Author URI: https://codeandcore.com
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: cross-site-copy-field-for-acf
 * Domain Path: /languages
 * Requires at least: 5.8
 * Requires PHP: 7.4
 */

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

// Define plugin constants
define('CSCF_ACF_VERSION', time());
define('CSCF_ACF_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('CSCF_ACF_PLUGIN_URL', plugin_dir_url(__FILE__));
define('CSCF_ACF_PLUGIN_FILE', __FILE__);

/**
 * Check if ACF Pro is active
 */
function cscf_acf_check_dependencies()
{
    // Check if ACF Pro is active
    if (!class_exists('ACF') && !function_exists('acf')) {
        add_action('admin_notices', 'cscf_acf_missing_acf_notice');

        // Deactivate the plugin
        deactivate_plugins(plugin_basename(__FILE__));

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This is unsetting a WordPress core parameter during plugin deactivation, not processing user input
        if (isset($_GET['activate'])) {
            unset($_GET['activate']);
        }

        return false;
    }

    return true;
}

/**
 * Display admin notice when ACF is not active
 */
function cscf_acf_missing_acf_notice()
{
    ?>
    <div class="notice notice-error is-dismissible">
        <p>
            <strong><?php esc_html_e('Cross Site Copy Field for ACF', 'cross-site-copy-field-for-acf'); ?></strong>
            <?php esc_html_e('could not be activated because it requires Advanced Custom Fields (ACF) or ACF Pro to be installed and activated.', 'cross-site-copy-field-for-acf'); ?>
        </p>
        <p>
            <?php
            printf(
                /* translators: %s: URL to ACF Pro website */
                esc_html__('Please install and activate %s first.', 'cross-site-copy-field-for-acf'),
                '<a href="https://www.advancedcustomfields.com/" target="_blank">Advanced Custom Fields</a>'
            );
            ?>
        </p>
    </div>
    <?php
}

/**
 * Autoloader for plugin classes
 */
spl_autoload_register(function ($class) {
    // Only autoload classes from this plugin
    $prefix = 'CSCF_ACF_';

    // Check if the class uses the namespace prefix
    if (strpos($class, $prefix) !== 0) {
        return;
    }

    // Get the relative class name
    $relative_class = substr($class, strlen($prefix));

    // Convert class name to file name
    // Example: Field_Serializer -> class-field-serializer.php
    $file_name = 'class-' . strtolower(str_replace('_', '-', $relative_class)) . '.php';

    // Build the file path
    $file = CSCF_ACF_PLUGIN_DIR . 'includes/' . $file_name;

    // If the file exists, require it
    if (file_exists($file)) {
        require_once $file;
    }
});

/**
 * Initialize the plugin
 */
function cscf_acf_init()
{
    // Check dependencies first
    if (!cscf_acf_check_dependencies()) {
        return;
    }

    // Initialize core components
    if (is_admin()) {
        // Initialize admin UI
        $admin_ui = new CSCF_ACF_Admin_UI();
        $admin_ui->init();
    }

    // Initialize REST API
    $rest_api = new CSCF_ACF_Rest_API();
    $rest_api->init();

    // Initialize Tracking
    // Check for "do not track" constant if you want to be nice, but standard is just the option
    $tracking = new CSCF_ACF_Tracking();
    $tracking->init();

    // Initialize Deactivation Feedback
    $deactivation = new CSCF_ACF_Deactivation();
    $deactivation->init();
}
add_action('plugins_loaded', 'cscf_acf_init');

/**
 * Activation hook
 */
function cscf_acf_activate()
{
    // Check dependencies on activation
    if (!cscf_acf_check_dependencies()) {
        return;
    }

    // Set activation flag
    update_option('cscf_acf_activated', true);

    // Flush rewrite rules for REST API
    flush_rewrite_rules();

    // Tracking
    if (class_exists('CSCF_ACF_Tracking')) {
        $tracking = new CSCF_ACF_Tracking();
        $tracking->send_tracking('Activation');

        // Save current version for future comparisons
        if (!function_exists('get_plugin_data')) {
            require_once(ABSPATH . 'wp-admin/includes/plugin.php');
        }
        $info = get_plugin_data(__FILE__);
        update_option('cscf_acf_plugin_version', $info['Version']);
    }

    // Set transient for redirect
    set_transient('cscf_acf_activation_redirect', true, 30);
}
register_activation_hook(__FILE__, 'cscf_acf_activate');

/**
 * Deactivation hook
 */
function cscf_acf_deactivate()
{
    // Remove activation flag
    delete_option('cscf_acf_activated');

    // Flush rewrite rules
    flush_rewrite_rules();

    // Tracking
    if (class_exists('CSCF_ACF_Tracking')) {
        $tracking = new CSCF_ACF_Tracking();
        $tracking->send_tracking('Deactivation');
    }
}
register_deactivation_hook(__FILE__, 'cscf_acf_deactivate');

/**
 * Uninstall hook
 */
register_uninstall_hook(__FILE__, ['CSCF_ACF_Tracking', 'uninstall']);
