<?php

// includes/save-project.php
if (!defined('ABSPATH')) exit;

if (!function_exists('vmo_sanitize_generated_project_html_for_storage')) {
    function vmo_sanitize_generated_project_html_for_storage($html) {
        if (is_array($html) || is_object($html)) {
            return '';
        }

        $html = wp_unslash((string) $html);

        if (function_exists('vmo_strip_editor_only_media_overlays')) {
            $html = vmo_strip_editor_only_media_overlays($html);
        } else {
            $html = preg_replace('/<button\b[^>]*(?:data-replace-media|data-vmo-editor-only=["\']media-replace-overlay["\']|class=["\'][^"\']*(?:vmo-replace-overlay|vmo-replace-btn|vmo-replace-media-btn|replace-image-btn|replace-video-btn)[^"\']*["\'])[^>]*>[\s\S]*?<\/button>/i', '', $html);
            $html = preg_replace('/\sdata-vmo-has-button=("[^"]*"|\'[^\']*\'|[^\s>]+)/i', '', $html);
            $html = preg_replace('/\sdata-vmo-editor-only=("[^"]*"|\'[^\']*\'|[^\s>]+)/i', '', $html);
        }

        $html = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F]/', '', $html);
        return trim(is_string($html) ? $html : '');
    }
}

if (!function_exists('vmo_with_generated_html_post_kses_disabled')) {
    function vmo_with_generated_html_post_kses_disabled($callback) {
        if (!is_callable($callback)) {
            return null;
        }

        $content_priority = has_filter('content_save_pre', 'wp_filter_post_kses');
        $filtered_priority = has_filter('content_filtered_save_pre', 'wp_filter_post_kses');

        if ($content_priority !== false) {
            remove_filter('content_save_pre', 'wp_filter_post_kses', $content_priority);
        }
        if ($filtered_priority !== false) {
            remove_filter('content_filtered_save_pre', 'wp_filter_post_kses', $filtered_priority);
        }

        try {
            return call_user_func($callback);
        } finally {
            if ($content_priority !== false) {
                add_filter('content_save_pre', 'wp_filter_post_kses', $content_priority);
            }
            if ($filtered_priority !== false) {
                add_filter('content_filtered_save_pre', 'wp_filter_post_kses', $filtered_priority);
            }
        }
    }
}

add_action('wp_ajax_vmo_save_project', function () {
    check_ajax_referer('vmo_builder_nonce', 'security');

    global $wpdb;

    $title  = sanitize_text_field($_POST['title'] ?? '');
    $html   = vmo_sanitize_generated_project_html_for_storage($_POST['html'] ?? '');
    $chat   = wp_unslash(sanitize_text_field(wp_unslash($_POST['chat'] ?? ''))); // Accept JSON string
    $state  = wp_unslash($_POST['state'] ?? ''); // Accept JSON string
    $images = wp_unslash($_POST['images'] ?? '');

    if (!$title || !$html) {
        wp_send_json_error(['message' => 'Title and HTML are required.']);
    }

    $user_id = get_current_user_id();

    // Save to custom post type (UI-visible projects)
    $existing = get_posts([
        'post_type'   => 'vmo_project',
        'title'       => $title,
        'author'      => $user_id,
        'post_status' => 'any',
        'numberposts' => 1
    ]);

    $post_data = [
        'post_title'   => $title,
        'post_content' => $html,
        'post_status'  => 'publish',
        'post_type'    => 'vmo_project',
        'post_author'  => $user_id
    ];

    if (!empty($existing)) {
        $post_data['ID'] = $existing[0]->ID;
        $post_id = vmo_with_generated_html_post_kses_disabled(function () use ($post_data) {
            return wp_update_post($post_data);
        });
    } else {
        $post_id = vmo_with_generated_html_post_kses_disabled(function () use ($post_data) {
            return wp_insert_post($post_data);
        });
    }

    if (is_wp_error($post_id)) {
        wp_send_json_error(['message' => 'Failed to save project.']);
    }

    delete_user_meta($user_id, 'vmo_builder_reset_to_demo');
    delete_post_meta($post_id, 'vmo_builder_archived_by_reset');
    delete_post_meta($post_id, 'vmo_builder_archived_at');
    delete_post_meta($post_id, 'vmo_builder_backup_id');

    update_post_meta($post_id, 'vmo_chat', $chat);
    update_post_meta($post_id, 'vmo_state', $state);
    update_post_meta($post_id, 'vmo_images', $images);
    update_post_meta($post_id, 'vmo_project_raw_html', $html);
    update_post_meta($post_id, 'vmo_project_html_storage_mode', 'generated_html_preserved');
    update_post_meta($post_id, 'vmo_last_updated', current_time('mysql'));
    update_post_meta($post_id, 'vmo_site_owner_id', $user_id); // ✅ For analytics tracking

    // Save to custom DB table for raw data access and version control
    $table_name = $wpdb->prefix . 'vmo_projects';
    $existing_entry = $wpdb->get_var($wpdb->prepare(
        "SELECT id FROM $table_name WHERE user_id = %d AND project_title = %s",
        $user_id, $title
    ));

    $data = [
        'user_id'        => $user_id,
        'project_title'  => $title,
        'html'           => $html,
        'images'         => maybe_serialize($images),
        'state_json'     => $state, // Save JSON state
        'chat'           => $chat,  // Save JSON chat
        'updated_at'     => current_time('mysql'),
    ];

    if ($existing_entry) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->update($table_name, $data, ['id' => $existing_entry]);
    } else {
        $data['created_at'] = current_time('mysql');
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->insert($table_name, $data);
    }

    do_action('vmo_project_saved', $post_id, $post_data);

    wp_send_json_success([
        'message' => 'Project saved',
        'id' => $post_id,
        'project_id' => $post_id
    ]);
});

// Register Post Type (fallback)
add_action('init', function () {
    register_post_type('vmo_project', [
        'labels' => [
            'name' => __('VMO Projects', 'vmo'),
            'singular_name' => __('VMO Project', 'vmo'),
        ],
        'public' => false,
        'show_ui' => true,
        'show_in_menu' => true,
        'menu_icon' => 'dashicons-portfolio',
        'supports' => ['title', 'editor'],
        'capability_type' => 'post',
        'has_archive' => false
    ]);
});