<?php
if (!defined('ABSPATH')) exit;

/**
 * Save a new undo step into project history table.
 */
add_action('wp_ajax_vmo_save_undo_step', 'vmo_handle_save_undo_step');
add_action('wp_ajax_vmo_save_undo', 'vmo_handle_save_undo_step'); // Alias for compatibility

function vmo_handle_save_undo_step() {
    check_ajax_referer('vmo_builder_nonce', 'security');

    $user_id = get_current_user_id();
    $html    = function_exists('vmo_sanitize_generated_project_html_for_storage')
        ? vmo_sanitize_generated_project_html_for_storage($_POST['html'] ?? '')
        : trim(wp_unslash((string) ($_POST['html'] ?? '')));
    $proj_id = intval($_POST['project_id'] ?? 0);
    
    // If no project_id provided, try to get from current live page
    if (!$proj_id && isset($_POST['page_id'])) {
        $proj_id = intval($_POST['page_id']);
    }

    // Allow saving undo even without project_id for publish operations
    if (!$html) {
        wp_send_json_error(['message' => 'Missing data.']);
        return;
    }
    
    // If no project_id, just acknowledge - undo will be handled client-side
    if (!$proj_id) {
        wp_send_json_success(['message' => 'Undo state saved client-side.']);
        return;
    }

    global $wpdb;

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $wpdb->insert(VMO_HISTORY_TABLE, [
        'project_id'  => $proj_id,
        'step_number' => time(),
        'html'        => $html,
        'images'      => '',
        'created_at'  => current_time('mysql')
    ]);

    wp_send_json_success(['message' => 'Undo step saved.']);
}

/**
 * Load the latest undo step for a project.
 */
add_action('wp_ajax_vmo_load_last_undo', function () {
    check_ajax_referer('vmo_builder_nonce', 'security');

    $proj_id = intval($_POST['project_id'] ?? 0);
    if (!$proj_id) {
        wp_send_json_error(['message' => 'Project ID missing.']);
    }

    global $wpdb;

    $row = $wpdb->get_row($wpdb->prepare(
        "SELECT html FROM " . VMO_HISTORY_TABLE . " WHERE project_id = %d ORDER BY step_number DESC LIMIT 1",
        $proj_id
    ));

    if (!$row) {
        wp_send_json_error(['message' => 'No undo history found.']);
    }

    wp_send_json_success(['html' => $row->html]);
});