<?php

/**
 * Plugin Name: REG121 Connect Platform
 * Description: A comprehensive WordPress plugin that integrates REG121 services and tools.
 * Version: 1.1.0
 * Author: 121 Digital Services Limited
 * Namespace: _121Digital\Connect
 *
 * Copyright 2025 121 Digital Services Limited (https://121digital.co.uk)
 */

defined('ABSPATH') || exit;

define('SC_FORCE_UI', true);

/**
 * Autoload classes using Composer or fallback autoloader
 */
$autoloadPath = __DIR__ . '/vendor/autoload.php';
if (file_exists($autoloadPath)) {
    require_once $autoloadPath;
} else {
    // Use fallback PSR-4 autoloader
    require_once __DIR__ . '/src/Core/Autoloader.php';
    $autoloader = new \_121Digital\Connect\Core\Autoloader(__DIR__ . '/src/');
    $autoloader->register();
}

// Load legacy function wrappers for backward compatibility
require_once __DIR__ . '/src/Integration/LegacyFunctions.php';

// Load plugin update checker library
require_once __DIR__ . '/plugin-update-checker/plugin-update-checker.php';
use YahnisElsts\PluginUpdateChecker\v5\PucFactory;

/**
 * Initialize plugin update checker
 */
$_SC_plugin_update_checker = null;
try {
    $_SC_plugin_update_checker = PucFactory::buildUpdateChecker(
        'https://wp-update-service.121domains.co.uk/121connect/metadata.json',
        __FILE__,
        '121_connect'
    );

    if (!isset($_SC_plugin_update_checker)) {
        throw new Exception('Could not init 121Connect plugin update service.');
    }
} catch (Exception $e) {
    \_121Digital\Connect\Core\Plugin::die($e->getMessage());
}

/**
 * Initialize and run the plugin
 */
function sc_init_plugin()
{
    $plugin = \_121Digital\Connect\Core\Plugin::getInstance();
    $plugin->init();
}
add_action('plugins_loaded', 'sc_init_plugin', 1);

/**
 * Plugin activation hook
 */
function sc_activate_plugin()
{
    // Schedule cron job on activation
    if (!wp_next_scheduled('sc_cron_hook')) {
        wp_schedule_event(time(), 'every_5_minutes', 'sc_cron_hook');
    }
}
register_activation_hook(__FILE__, 'sc_activate_plugin');

/**
 * Plugin deactivation hook
 */
function sc_deactivate_plugin()
{
    // Clear scheduled cron jobs
    \_121Digital\Connect\Core\Cron::clearScheduledJobs();
}
register_deactivation_hook(__FILE__, 'sc_deactivate_plugin');
