<?php
/**
 * AI Content Writer AJAX Handlers
 *
 * Connects WordPress admin UI to WordChat backend API
 *
 * @package WordChat
 * @since 0.2.0
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * AJAX: Generate content
 */
add_action('wp_ajax_wordchat_generate_content', 'wordchat_ajax_generate_content');
function wordchat_ajax_generate_content() {
    check_ajax_referer('wordchat_query_nonce', 'nonce');

    if (!current_user_can('manage_options')) {
        wp_send_json_error('Insufficient permissions');
        return;
    }

    $site_id = get_option('wordchat_site_id');
    $api_key = get_option('wordchat_api_key');

    if (!$site_id || !$api_key) {
        wp_send_json_error('WordChat not configured. Please complete setup first.');
        return;
    }

    $topic = sanitize_text_field($_POST['topic'] ?? '');
    $tone = sanitize_text_field($_POST['tone'] ?? 'professional');
    $word_count = absint($_POST['target_word_count'] ?? 1000);
    $related_urls = array_map('esc_url_raw', $_POST['related_post_urls'] ?? []);

    if (empty($topic)) {
        wp_send_json_error('Topic is required');
        return;
    }

    // Call backend API
    $response = wp_remote_post(WORDCHAT_API_URL . '/content/generate', [
        'headers' => ['Content-Type' => 'application/json'],
        'body' => json_encode([
            'site_id' => $site_id,
            'api_key' => $api_key,
            'domain' => get_site_url(),
            'topic' => $topic,
            'tone' => $tone,
            'target_word_count' => $word_count,
            'related_post_urls' => $related_urls,
            'include_internal_links' => true
        ]),
        'timeout' => 60
    ]);

    if (is_wp_error($response)) {
        wp_send_json_error('API request failed: ' . $response->get_error_message());
        return;
    }

    $body = json_decode(wp_remote_retrieve_body($response), true);

    if (!$body['success']) {
        wp_send_json_error($body['error'] ?? 'Generation failed');
        return;
    }

    wp_send_json_success($body);
}

/**
 * AJAX: Save generated content as WordPress draft
 */
add_action('wp_ajax_wordchat_save_draft', 'wordchat_ajax_save_draft');
function wordchat_ajax_save_draft() {
    check_ajax_referer('wordchat_query_nonce', 'nonce');

    if (!current_user_can('edit_posts')) {
        wp_send_json_error('Insufficient permissions');
        return;
    }

    $title = sanitize_text_field($_POST['title'] ?? '');
    $content = wp_kses_post($_POST['content'] ?? '');
    $excerpt = sanitize_textarea_field($_POST['excerpt'] ?? '');

    if (empty($title) || empty($content)) {
        wp_send_json_error('Title and content are required');
        return;
    }

    // Convert markdown to HTML if needed (basic conversion)
    $content = wpautop($content);

    $post_id = wp_insert_post([
        'post_title' => $title,
        'post_content' => $content,
        'post_excerpt' => $excerpt,
        'post_status' => 'draft',
        'post_author' => get_current_user_id(),
        'post_type' => 'post'
    ]);

    if (is_wp_error($post_id)) {
        wp_send_json_error('Failed to create draft: ' . $post_id->get_error_message());
        return;
    }

    // Add meta to track AI generation
    add_post_meta($post_id, 'wordchat_ai_generated', true);
    add_post_meta($post_id, 'wordchat_generated_at', current_time('mysql'));

    wp_send_json_success([
        'post_id' => $post_id,
        'edit_url' => get_edit_post_link($post_id, 'raw')
    ]);
}

/**
 * AJAX: Suggest internal links
 */
add_action('wp_ajax_wordchat_suggest_links', 'wordchat_ajax_suggest_links');
function wordchat_ajax_suggest_links() {
    check_ajax_referer('wordchat_query_nonce', 'nonce');

    if (!current_user_can('edit_posts')) {
        wp_send_json_error('Insufficient permissions');
        return;
    }

    $site_id = get_option('wordchat_site_id');
    $api_key = get_option('wordchat_api_key');
    $post_id = absint($_POST['post_id'] ?? 0);

    if (!$post_id) {
        wp_send_json_error('Post ID is required');
        return;
    }

    $post = get_post($post_id);
    if (!$post) {
        wp_send_json_error('Post not found');
        return;
    }

    $post_url = get_permalink($post);
    $content = $post->post_content;

    // Call backend API
    $response = wp_remote_post(WORDCHAT_API_URL . '/content/suggest-links', [
        'headers' => ['Content-Type' => 'application/json'],
        'body' => json_encode([
            'site_id' => $site_id,
            'api_key' => $api_key,
            'domain' => get_site_url(),
            'post_url' => $post_url,
            'content' => wp_strip_all_tags($content),
            'max_suggestions' => 5
        ]),
        'timeout' => 60
    ]);

    if (is_wp_error($response)) {
        wp_send_json_error('API request failed: ' . $response->get_error_message());
        return;
    }

    $body = json_decode(wp_remote_retrieve_body($response), true);

    if (!$body['success']) {
        wp_send_json_error($body['error'] ?? 'Failed to get suggestions');
        return;
    }

    // Add post_id to response for later use
    $body['post_id'] = $post_id;

    wp_send_json_success($body);
}

/**
 * AJAX: Apply link suggestions to post
 */
add_action('wp_ajax_wordchat_apply_links', 'wordchat_ajax_apply_links');
function wordchat_ajax_apply_links() {
    check_ajax_referer('wordchat_query_nonce', 'nonce');

    if (!current_user_can('edit_posts')) {
        wp_send_json_error('Insufficient permissions');
        return;
    }

    $site_id = get_option('wordchat_site_id');
    $api_key = get_option('wordchat_api_key');
    $post_id = absint($_POST['post_id'] ?? 0);
    $accepted_indices = array_map('absint', $_POST['accepted_indices'] ?? []);

    if (!$post_id || empty($accepted_indices)) {
        wp_send_json_error('Post ID and accepted suggestions are required');
        return;
    }

    $post = get_post($post_id);
    if (!$post) {
        wp_send_json_error('Post not found');
        return;
    }

    $post_url = get_permalink($post);
    $content = $post->post_content;

    // Call backend API to apply edits with links
    $response = wp_remote_post(WORDCHAT_API_URL . '/content/edit', [
        'headers' => ['Content-Type' => 'application/json'],
        'body' => json_encode([
            'site_id' => $site_id,
            'api_key' => $api_key,
            'domain' => get_site_url(),
            'post_url' => $post_url,
            'content' => $content,
            'edit_instructions' => 'Add the accepted internal links in natural positions',
            'accepted_link_suggestions' => $accepted_indices
        ]),
        'timeout' => 60
    ]);

    if (is_wp_error($response)) {
        wp_send_json_error('API request failed: ' . $response->get_error_message());
        return;
    }

    $body = json_decode(wp_remote_retrieve_body($response), true);

    if (!$body['success']) {
        wp_send_json_error($body['error'] ?? 'Failed to apply links');
        return;
    }

    // Update post content
    $updated = wp_update_post([
        'ID' => $post_id,
        'post_content' => $body['edited_content']
    ]);

    if (is_wp_error($updated)) {
        wp_send_json_error('Failed to update post: ' . $updated->get_error_message());
        return;
    }

    // Add meta to track link additions
    add_post_meta($post_id, 'wordchat_links_applied', current_time('mysql'));

    wp_send_json_success([
        'post_id' => $post_id,
        'edit_url' => get_edit_post_link($post_id, 'raw'),
        'changes_summary' => $body['changes_summary']
    ]);
}

/**
 * AJAX: Edit content with AI
 */
add_action('wp_ajax_wordchat_edit_content', 'wordchat_ajax_edit_content');
function wordchat_ajax_edit_content() {
    check_ajax_referer('wordchat_query_nonce', 'nonce');

    if (!current_user_can('edit_posts')) {
        wp_send_json_error('Insufficient permissions');
        return;
    }

    $site_id = get_option('wordchat_site_id');
    $api_key = get_option('wordchat_api_key');
    $post_id = absint($_POST['post_id'] ?? 0);
    $instructions = sanitize_textarea_field($_POST['instructions'] ?? '');

    if (!$post_id || empty($instructions)) {
        wp_send_json_error('Post ID and instructions are required');
        return;
    }

    $post = get_post($post_id);
    if (!$post) {
        wp_send_json_error('Post not found');
        return;
    }

    $post_url = get_permalink($post);
    $content = $post->post_content;

    // Call backend API
    $response = wp_remote_post(WORDCHAT_API_URL . '/content/edit', [
        'headers' => ['Content-Type' => 'application/json'],
        'body' => json_encode([
            'site_id' => $site_id,
            'api_key' => $api_key,
            'domain' => get_site_url(),
            'post_url' => $post_url,
            'content' => wp_strip_all_tags($content),
            'edit_instructions' => $instructions,
            'accepted_link_suggestions' => []
        ]),
        'timeout' => 60
    ]);

    if (is_wp_error($response)) {
        wp_send_json_error('API request failed: ' . $response->get_error_message());
        return;
    }

    $body = json_decode(wp_remote_retrieve_body($response), true);

    if (!$body['success']) {
        wp_send_json_error($body['error'] ?? 'Edit failed');
        return;
    }

    // Add post_id to response
    $body['post_id'] = $post_id;

    wp_send_json_success($body);
}

/**
 * AJAX: Update post content
 */
add_action('wp_ajax_wordchat_update_post_content', 'wordchat_ajax_update_post_content');
function wordchat_ajax_update_post_content() {
    check_ajax_referer('wordchat_query_nonce', 'nonce');

    if (!current_user_can('edit_posts')) {
        wp_send_json_error('Insufficient permissions');
        return;
    }

    $post_id = absint($_POST['post_id'] ?? 0);
    $content = wp_kses_post($_POST['content'] ?? '');

    if (!$post_id || empty($content)) {
        wp_send_json_error('Post ID and content are required');
        return;
    }

    // Convert markdown to HTML if needed
    $content = wpautop($content);

    $updated = wp_update_post([
        'ID' => $post_id,
        'post_content' => $content
    ]);

    if (is_wp_error($updated)) {
        wp_send_json_error('Failed to update post: ' . $updated->get_error_message());
        return;
    }

    // Add meta to track AI edits
    add_post_meta($post_id, 'wordchat_ai_edited', current_time('mysql'));

    wp_send_json_success([
        'post_id' => $post_id,
        'edit_url' => get_edit_post_link($post_id, 'raw')
    ]);
}
