<?php
/**
 * Plugin Name: Free Backlinks & Guest Post Exchange - Consolety
 * Plugin URI: https://consolety.ai/
 * Description: Get free backlinks for your WordPress site: trade guest posts with Google-verified publishers. Earn points hosting, spend them publishing.
 * Version: 5.0.6
 * Requires at least: 5.8
 * Requires PHP: 8.0
 * Author: Consolety
 * Author URI: https://consolety.ai
 * License: GPLv2 or later
 * Text Domain: consolety
 * Domain Path: /languages
 */

if (!defined('ABSPATH')) {
    exit;
}

// PHP 8.0+ required for match() expressions
if (version_compare(PHP_VERSION, '8.0.0', '<')) {
    add_action('admin_notices', function() {
        echo wp_kses_post( '<div class="notice notice-error"><p><strong>Consolety</strong> ' . esc_html__( 'requires PHP 8.0 or higher. Your server is running PHP', 'consolety' ) . ' ' . esc_html( PHP_VERSION ) . '.</p></div>' );
    });
    return; // Prevent further loading
}

// Plugin constants
define('CONSOLETY_VERSION', '5.0.6');
define('CONSOLETY_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('CONSOLETY_PLUGIN_URL', plugin_dir_url(__FILE__));
define('CONSOLETY_HUB_URL', 'https://app.consolety.ai');

// i18n: textdomain loaded automatically by WordPress 4.6+ for plugins on wp.org

// Freemius SDK for premium licensing
require_once __DIR__ . '/includes/freemius-config.php';

// Autoload classes
spl_autoload_register(function ($class) {
    $prefix = 'Consolety\\';
    $base_dir = CONSOLETY_PLUGIN_DIR . 'includes/';

    $len = strlen($prefix);
    if (strncmp($prefix, $class, $len) !== 0) {
        return;
    }

    $relative_class = substr($class, $len);

    // Handle namespaced classes like Ajax\GuestPostsAjaxHandler
    $parts = explode('\\', $relative_class);
    if (count($parts) > 1) {
        // Subdirectory structure: Ajax\GuestPostsAjaxHandler -> ajax/class-guest-posts-ajax-handler.php
        $subdir = strtolower($parts[0]) . '/';
        $classname = $parts[1];
        // Convert CamelCase to kebab-case
        $filename = strtolower(preg_replace('/(?<!^)[A-Z]/', '-$0', $classname));
        $file = $base_dir . $subdir . 'class-' . $filename . '.php';
    } else {
        $file = $base_dir . 'class-' . strtolower(str_replace('\\', '-', $relative_class)) . '.php';
    }

    if (file_exists($file)) {
        require $file;
    }
});

// Initialize plugin
function consolety_init() {
    return \Consolety\Plugin::instance();
}

add_action('plugins_loaded', 'consolety_init');

// Activation hook
register_activation_hook(__FILE__, function() {
    // Fix folder permissions (some ZIP extractors set wrong permissions)
    $plugin_dir = plugin_dir_path(__FILE__);
    $dirs = ['admin', 'admin/css', 'admin/js', 'admin/views', 'includes', 'includes/ajax'];
    foreach ($dirs as $dir) {
        $path = $plugin_dir . $dir;
        if (is_dir($path) && !is_readable($path)) {
            WP_Filesystem();
            global $wp_filesystem;
            if ($wp_filesystem) {
                $wp_filesystem->chmod($path, 0755);
            }
        }
    }

    // Schedule heartbeat cron on activation
    if (!wp_next_scheduled('consolety_heartbeat')) {
        wp_schedule_event(time(), 'hourly', 'consolety_heartbeat');
    }

    do_action('consolety_activated');
});

// Deactivation hook
register_deactivation_hook(__FILE__, function() {
    // Notify Hub that this site is deactivating
    $token = get_option('consolety_trust_token');
    if (!empty($token)) {
        wp_remote_post(CONSOLETY_HUB_URL . '/api/v1/site/disconnect', [
            'method'   => 'POST',
            'timeout'  => 5,
            'blocking' => false,
            'headers'  => [
                'Authorization' => 'Bearer ' . $token,
                'X-Site-URL'    => home_url(),
                'Accept'        => 'application/json',
                'Content-Type'  => 'application/json',
            ],
            'body' => wp_json_encode(['reason' => 'plugin_deactivated']),
        ]);
    }

    // Clear ALL scheduled instances of our cron hooks to prevent orphans
    wp_clear_scheduled_hook('consolety_heartbeat');
    wp_clear_scheduled_hook('consolety_check_links');

    do_action('consolety_deactivated');
});
