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

/**
 * AJAX: Handle media upload (images and videos)
 */
add_action('wp_ajax_vmo_upload_media', function () {
    // Dual-nonce validation: accept either admin nonce (nonce) or builder nonce (security)
    $admin_nonce   = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
    $builder_nonce = isset($_POST['security']) ? sanitize_text_field(wp_unslash($_POST['security'])) : '';

    $admin_ok   = $admin_nonce && wp_verify_nonce($admin_nonce, 'vmo_admin_nonce');
    $builder_ok = $builder_nonce && wp_verify_nonce($builder_nonce, 'vmo_builder_nonce');

    if (!($admin_ok || $builder_ok)) {
        // Non-fatal invalid nonce response with HTTP 200 to avoid SPA disruptions
        wp_send_json_error(['message' => 'Security check failed', 'status' => 'invalid_nonce']);
    }

    if (!current_user_can('upload_files')) {
        // Capability failures use 403
        wp_send_json_error(['message' => 'Permission denied.', 'status' => 'forbidden'], 403);
    }

    if (empty($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
        wp_send_json_error(['message' => 'No file uploaded or upload error.']);
    }

    $file = $_FILES['file'];

    // Validate file type - expanded to allow documents and audio for AI analysis
    $allowed_types = [
        // Images
        'image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml',
        // Videos
        'video/mp4', 'video/webm', 'video/ogg', 'video/avi', 'video/mov', 'video/quicktime',
        // Audio
        'audio/mpeg', 'audio/mp3', 'audio/wav', 'audio/ogg', 'audio/mp4', 'audio/x-m4a', 'audio/aac',
        // Documents
        'application/pdf', 'text/plain', 'text/csv', 'application/json',
        'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
        // Archives (optional)
        'application/zip'
    ];

    $mime = mime_content_type($file['tmp_name']);

    if (!in_array($mime, $allowed_types, true)) {
        wp_send_json_error(['message' => 'Invalid file type. Allowed: images, videos, audio, and documents (PDF, DOCX, XLSX, PPTX, TXT, CSV).']);
    }

    // Validate file size by category
    $is_video = strpos($mime, 'video/') === 0;
    $is_image = strpos($mime, 'image/') === 0;
    $is_audio = strpos($mime, 'audio/') === 0;
    $is_doc   = !$is_video && !$is_image && !$is_audio; // application/* and text/*

    if ($is_video) {
        $max_size = 50 * 1024 * 1024; // 50MB for video
    } elseif ($is_image) {
        $max_size = 10 * 1024 * 1024; // 10MB for images
    } elseif ($is_audio) {
        $max_size = 20 * 1024 * 1024; // 20MB for audio
    } else { // documents
        $max_size = 20 * 1024 * 1024; // 20MB for documents
    }
    
    if ($file['size'] > $max_size) {
        $max_size_mb = $is_video ? '50MB' : '10MB';
        wp_send_json_error(['message' => "File too large (max {$max_size_mb})."]);
    }

    // Use WordPress upload handling
    require_once ABSPATH . 'wp-admin/includes/file.php';
    require_once ABSPATH . 'wp-admin/includes/media.php';
    require_once ABSPATH . 'wp-admin/includes/image.php';

    $overrides = ['test_form' => false];
    $uploaded = wp_handle_upload($file, $overrides);

    if (isset($uploaded['error'])) {
        wp_send_json_error(['message' => $uploaded['error']]);
    }

    // Create attachment record
    $attachment = [
        'post_mime_type' => $uploaded['type'],
        'post_title'     => sanitize_file_name(pathinfo($file['name'], PATHINFO_FILENAME)),
        'post_content'   => '',
        'post_status'    => 'inherit'
    ];
    
    $attach_id = wp_insert_attachment($attachment, $uploaded['file']);
    
    // Generate metadata for images
    if ($is_image) {
        $attach_data = wp_generate_attachment_metadata($attach_id, $uploaded['file']);
        wp_update_attachment_metadata($attach_id, $attach_data);
    }

    $url = wp_get_attachment_url($attach_id);

    wp_send_json_success([
        'url' => esc_url_raw($url),
        'id' => $attach_id,
        'type' => $is_video ? 'video' : ($is_image ? 'image' : ($is_audio ? 'audio' : 'document'))
    ]);
});
