<?php
/**
 * Standalone Restore Endpoint
 * 
 * Bypasses the standard WordPress plugin loading sequence so that the restore
 * process can survive even when the database (e.g., wp_options) is temporarily
 * dropped or incomplete during a chunked SQL import.
 */

define('WP_INSTALLING', true);
ini_set('display_errors', 1);
error_reporting(E_ALL);

// Find wp-load.php
$wp_load_path = dirname(__FILE__, 4) . '/wp-load.php';
if (!file_exists($wp_load_path)) {
    $wp_load_path = dirname(__FILE__, 5) . '/wp-load.php';
}

if (!file_exists($wp_load_path)) {
    echo json_encode(['success' => false, 'data' => ['message' => 'Cannot find wp-load.php']]);
    exit;
}

require_once $wp_load_path;

if (!defined('FOXBLOCK_PLUGIN_DIR')) {
    define('FOXBLOCK_PLUGIN_DIR', plugin_dir_path(__FILE__));
}

require_once FOXBLOCK_PLUGIN_DIR . 'includes/Backup/StateManager.php';

$state = Foxblock_Backup_StateManager::get_restore_state();
$token = isset($_POST['restore_token']) ? sanitize_text_field($_POST['restore_token']) : '';

if (!$state || empty($state['restore_token']) || !hash_equals($state['restore_token'], $token)) {
    wp_send_json_error(['message' => 'Unauthorized']);
}

require_once FOXBLOCK_PLUGIN_DIR . 'includes/Backup/FileHandler.php';
require_once FOXBLOCK_PLUGIN_DIR . 'includes/Backup/SecurityHelper.php';
require_once FOXBLOCK_PLUGIN_DIR . 'includes/Backup/RestoreManager.php';

@set_time_limit(300);

$result = Foxblock_RestoreManager::run_step();

if (!empty($result['error'])) {
    Foxblock_Backup_StateManager::clear_restore_state();
    wp_send_json_error(['message' => $result['error']]);
}

wp_send_json_success($result);
