<?php
/**
 * Tool: restore_page_version
 *
 * Roll a Co-pilot-managed page back to a snapshot the cloud dashboard
 * keeps in page_versions. The dashboard's /app/api/restore route reads
 * the snapshot from the proxy DB and dispatches it to the site as the
 * `snapshot_html` input. We swap that into post_content and re-record
 * the (now-current) state as a fresh version so the user can ping-pong.
 */
if (!defined('ABSPATH')) exit;

function swcp_tool_restore_page_version($input, $ctx) {
    $post_id = isset($input['post_id']) ? (int) $input['post_id'] : 0;
    $snapshot = isset($input['snapshot_html']) ? (string) $input['snapshot_html'] : '';

    if (!$post_id || !$snapshot) {
        return ['ok' => false, 'message' => 'Need a post id and a snapshot to restore.'];
    }
    $post = get_post($post_id);
    if (!$post || !in_array($post->post_type, ['page', 'sailwp_page', 'post'], true)) {
        return ['ok' => false, 'message' => 'That page is no longer here.'];
    }

    // Capture the CURRENT content as a fresh BEFORE so the user can undo
    // the restore (ping-pong between two versions).
    $before_html = (string) $post->post_content;

    $update = wp_update_post([
        'ID'           => $post_id,
        'post_content' => $snapshot,
    ], true);
    if (is_wp_error($update)) {
        return ['ok' => false, 'message' => 'Could not restore that version. The page is unchanged.'];
    }

    // Mirror the design-meta state. If snapshot was a Co-pilot design
    // it already has the swcp-design-root marker; if it was a plain
    // Gutenberg state, _swcp_designed should be off.
    if (strpos($snapshot, 'swcp-design-root') !== false) {
        update_post_meta($post_id, '_swcp_designed', 1);
    } else {
        delete_post_meta($post_id, '_swcp_designed');
    }

    if (function_exists('swcp_log_page_version')) {
        swcp_log_page_version($post_id, $before_html, $snapshot);
    }

    if (function_exists('swcp_log_remote_event')) {
        swcp_log_remote_event('version_restored', ['post_id' => $post_id]);
    }

    return [
        'ok'        => true,
        'message'   => 'Restored.',
        'post_id'   => $post_id,
        'view_url'  => function_exists('swcp_view_url_for') ? swcp_view_url_for($post_id) : get_permalink($post_id),
        'edit_url'  => function_exists('swcp_edit_url_for') ? swcp_edit_url_for($post_id) : admin_url('post.php?post=' . $post_id . '&action=edit'),
    ];
}
