<?php
if (!defined('ABSPATH')) {
    exit;
}
// includes/register.php

function wordchat_register_plugin() {
    $site_url = get_site_url();
    $admin_email = get_option('admin_email');

    // PRIORITY 1: Track activation attempt (regardless of registration status)
    wordchat_track_activation('attempting_registration');

    // Prevent re-registration if already registered
    $existing_site_id = get_option('wordchat_site_id');
    if ($existing_site_id) {
        error_log('WordChat: Already registered (site_id=' . $existing_site_id . '), skipping registration');
        update_option('wordchat_registration_status', 'success');
        wordchat_track_activation('already_registered');
        return;
    }

    error_log('WordChat: Starting registration process');

    // First, ping health check to wake up backend (non-blocking)
    wp_remote_get(WORDCHAT_API_URL . '/health', [
        'timeout' => 5,
        'blocking' => false  // Don't wait for response
    ]);

    // Wait a moment for server to wake up
    sleep(2);

    // Now attempt registration with longer timeout
    $response = wp_remote_post(WORDCHAT_API_URL . '/register', [
        'headers' => ['Content-Type' => 'application/json'],
        'body' => json_encode([
            'domain' => $site_url,
            'admin_email' => $admin_email
        ]),
        'timeout' => 90,  // Increased to 90 seconds for Render cold starts
        'blocking' => true
    ]);

    // Handle network/connection errors
    if (is_wp_error($response)) {
        $error = $response->get_error_message();
        error_log("WordChat: Registration request error - $error");

        // If timeout error, try to verify if registration actually succeeded
        if (strpos($error, 'timed out') !== false || strpos($error, 'timeout') !== false) {
            error_log("WordChat: Timeout detected, checking if registration succeeded anyway...");

            // Wait a moment, then try to verify credentials
            sleep(3);

            // Attempt to verify if we're already registered by checking with backend
            $verify_response = wp_remote_post(WORDCHAT_API_URL . '/register', [
                'headers' => ['Content-Type' => 'application/json'],
                'body' => json_encode([
                    'domain' => $site_url,
                    'admin_email' => $admin_email
                ]),
                'timeout' => 30,
                'blocking' => true
            ]);

            // Check if this returns existing credentials
            if (!is_wp_error($verify_response)) {
                $verify_code = wp_remote_retrieve_response_code($verify_response);
                $verify_body = wp_remote_retrieve_body($verify_response);
                $verify_data = json_decode($verify_body, true);

                if ($verify_code === 200 && isset($verify_data['site_id']) && isset($verify_data['api_key'])) {
                    // Registration actually succeeded!
                    update_option('wordchat_site_id', $verify_data['site_id']);
                    update_option('wordchat_api_key', $verify_data['api_key']);
                    update_option('wordchat_is_paid', '0');
                    update_option('wordchat_registration_status', 'success');
                    delete_option('wordchat_registration_error');
                    delete_option('wordchat_registration_retry_count');

                    error_log("WordChat: Registration recovered after timeout - site_id={$verify_data['site_id']}");
                    set_transient('wordchat_show_welcome', true, 60);
                    return;
                }
            }
        }

        // If we get here, registration truly failed
        update_option('wordchat_registration_status', 'failed');
        update_option('wordchat_registration_error', $error);
        update_option('wordchat_registration_retry_count', 0);

        // Track failed registration
        wordchat_track_activation('registration_failed', $error);
        wordchat_report_registration_failure($site_url, $admin_email, $error);
        return;
    }

    $status_code = wp_remote_retrieve_response_code($response);
    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);

    // Handle successful registration
    if ($status_code === 200 && isset($data['site_id']) && isset($data['api_key'])) {
        update_option('wordchat_site_id', $data['site_id']);
        update_option('wordchat_api_key', $data['api_key']);
        update_option('wordchat_is_paid', '0');
        update_option('wordchat_registration_status', 'success');
        delete_option('wordchat_registration_error');
        delete_option('wordchat_registration_retry_count');

        error_log("WordChat: Registration successful - site_id={$data['site_id']}");

        // Track successful registration
        wordchat_track_activation('registration_success');

        // Set transient for welcome message (expires in 60 seconds)
        set_transient('wordchat_show_welcome', true, 60);
        return;
    }

    // Handle API errors
    $error_msg = 'Unknown error';
    if (isset($data['error'])) {
        $error_msg = $data['error'];
    } elseif ($status_code !== 200) {
        $error_msg = "HTTP $status_code - Server error";
    }

    error_log("WordChat: Registration failed - $error_msg");
    update_option('wordchat_registration_status', 'failed');
    update_option('wordchat_registration_error', $error_msg);
    update_option('wordchat_registration_retry_count', 0);

    // Track failed registration
    wordchat_track_activation('registration_failed', $error_msg);
    wordchat_report_registration_failure($site_url, $admin_email, $error_msg);
}

/**
 * Track plugin activation (Priority 1: Track all activations)
 * This runs on EVERY activation, regardless of registration status
 */
function wordchat_track_activation($status = 'activation', $error = null) {
    $activation_data = [
        'site_url' => get_site_url(),
        'plugin_version' => WORDCHAT_VERSION,
        'wp_version' => get_bloginfo('version'),
        'php_version' => PHP_VERSION,
        'status' => $status,
        'error' => $error,
        'timestamp' => current_time('mysql'),
        'site_id' => get_option('wordchat_site_id', null)
    ];

    // Send to backend (non-blocking)
    wp_remote_post(WORDCHAT_API_URL . '/telemetry/activation', [
        'blocking' => false,
        'headers' => ['Content-Type' => 'application/json'],
        'body' => json_encode($activation_data),
        'timeout' => 5
    ]);

    error_log("WordChat: Activation tracked - status=$status");
}

/**
 * Report registration failure to backend for tracking
 * Helps identify which sites are having trouble registering
 */
function wordchat_report_registration_failure($site_url, $admin_email, $error) {
    $failure_data = [
        'domain' => $site_url,
        'admin_email' => $admin_email,
        'error' => $error,
        'plugin_version' => WORDCHAT_VERSION,
        'wp_version' => get_bloginfo('version'),
        'php_version' => PHP_VERSION,
        'timestamp' => current_time('mysql')
    ];

    // Send to backend (non-blocking)
    wp_remote_post(WORDCHAT_API_URL . '/telemetry/registration-failed', [
        'blocking' => false,
        'headers' => ['Content-Type' => 'application/json'],
        'body' => json_encode($failure_data),
        'timeout' => 5
    ]);
}
