<?php
defined('ABSPATH') || exit;

/**
 * Endpoint to check if backup module is installed and active
 * URL: /wp-json/wpsec/v1/backup/status
 */
function wpsec_backup_module_status_endpoint($request) {
    $is_installed = is_plugin_active('wpfortai-security-backup/wpfortai-security-backup.php');
    $module_active = get_option('wpsec_backup_module_active', false);
    $module_version = get_option('wpsec_backup_module_version', null);
    
    // Check if backup classes are available
    $classes_available = class_exists('WPSEC_Backup_Manager') && 
                        class_exists('WPSEC_Backblaze') && 
                        class_exists('WPSEC_Backup_Endpoint');
    
    $status = [
        'module_installed' => $is_installed,
        'module_active' => $module_active,
        'module_version' => $module_version,
        'classes_loaded' => $classes_available,
        'endpoints_available' => $classes_available, // Backup endpoints loaded with classes
        'plugin_path' => 'wpfortai-security-backup/wpfortai-security-backup.php'
    ];
    
    // Overall status
    $status['status'] = ($is_installed && $module_active && $classes_available) ? 'active' : 'inactive';
    $status['message'] = $status['status'] === 'active' 
        ? 'Backup module is installed and fully functional' 
        : 'Backup module is not available - install WPFort Backup Pro addon';
    
    return rest_ensure_response([
        'success' => true,
        'data' => $status
    ], 200);
}

/**
 * Endpoint to get backup module installation instructions
 * URL: /wp-json/wpsec/v1/backup/install-info
 */
function wpsec_backup_install_info_endpoint($request) {
    return rest_ensure_response([
        'success' => true,
        'data' => [
            'plugin_slug' => 'wpfortai-security-backup',
            'plugin_file' => 'wpfortai-security-backup.php',
            'required_main_plugin' => 'wpfortai-security/wpfortai-security.php',
            'download_url' => 'https://wpfort.ai/pro/backup-addon',
            'installation_method' => 'manual', // Future: 'api' when we implement auto-install
            'requirements' => [
                'WPFort Security Suite must be active',
                'WordPress 5.0 or higher',
                'PHP 7.4 or higher'
            ]
        ]
    ], 200);
}

// Register endpoints
add_action('rest_api_init', function () {
    register_rest_route('wpsec/v1', '/backup/status', [
        'methods' => 'GET',
        'callback' => 'wpsec_backup_module_status_endpoint',
        'permission_callback' => 'wpsec_authenticate_request'
    ]);
    
    register_rest_route('wpsec/v1', '/backup/install-info', [
        'methods' => 'GET', 
        'callback' => 'wpsec_backup_install_info_endpoint',
        'permission_callback' => 'wpsec_authenticate_request'
    ]);
});
