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

/**
 * VMO Media Integration Backend Hooks
 * Backend AI agent integration without frontend modifications
 */

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

// Add media integration ajax endpoint
add_action('wp_ajax_vmo_media_integration_request', 'vmo_handle_media_integration_request');

function vmo_handle_media_integration_request() {
    // Security check
    if (!current_user_can('edit_posts') || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'vmo_nonce')) {
        wp_die('Security check failed');
    }

    // Validate required data
    if (empty($_POST['media_id']) || empty($_POST['integration_prompt'])) {
        wp_send_json_error('Missing required data');
    }

    $media_id = intval($_POST['media_id']);
    $integration_prompt = sanitize_textarea_field($_POST['integration_prompt']);
    
    // Get media details
    $attachment = get_post($media_id);
    if (!$attachment || $attachment->post_type !== 'attachment') {
        wp_send_json_error('Invalid media file');
    }

    // Initialize Media Integration Agent
    if (class_exists('VMO_Media_Integration_Agent')) {
        $agent = new VMO_Media_Integration_Agent();
        
        // Process integration request
        $integration_data = [
            'media_id' => $media_id,
            'media_url' => wp_get_attachment_url($media_id),
            'media_title' => $attachment->post_title,
            'media_type' => $attachment->post_mime_type,
            'integration_prompt' => $integration_prompt,
            'placement_style' => sanitize_text_field($_POST['placement_style'] ?? 'contextual'),
            'animation_type' => sanitize_text_field($_POST['animation_type'] ?? 'none'),
            'responsive_behavior' => sanitize_text_field($_POST['responsive_behavior'] ?? 'adaptive'),
            'accessibility_notes' => sanitize_textarea_field($_POST['accessibility_notes'] ?? ''),
            'user_id' => get_current_user_id()
        ];
        
        $result = $agent->process_media_integration($integration_data);
        
        if ($result['success']) {
            wp_send_json_success($result);
        } else {
            wp_send_json_error($result['message']);
        }
    } else {
        wp_send_json_error('Media Integration Agent not available');
    }
}
