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

/**
 * AJAX: Handle image upload
 */
add_action('wp_ajax_vmo_upload_image', function () {
    // Accept both admin and builder nonces; return non-fatal JSON on failure
    $admin_nonce   = isset($_POST['nonce']) ? $_POST['nonce'] : '';
    $builder_nonce = isset($_POST['security']) ? $_POST['security'] : '';
    $valid = false;
    if ($admin_nonce && wp_verify_nonce($admin_nonce, 'vmo_admin_nonce')) $valid = true;
    if ($builder_nonce && wp_verify_nonce($builder_nonce, 'vmo_builder_nonce')) $valid = true;
    if (!$valid) {
        wp_send_json_error(['message' => 'Security check failed', 'status' => 'invalid_nonce']);
        return;
    }

    if (!current_user_can('upload_files')) {
        wp_send_json_error(['message' => 'Permission denied.'], 403);
        return;
    }

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

    $file = $_FILES['image'];

    // Validate file type
    $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml'];
    $mime = mime_content_type($file['tmp_name']);

    if (!in_array($mime, $allowed_types, true)) {
        wp_send_json_error(['message' => 'Invalid file type.']);
    }

    // Validate file size (limit: 5MB)
    $max_size = 5 * 1024 * 1024;
    if ($file['size'] > $max_size) {
        wp_send_json_error(['message' => 'File too large (max 5MB).']);
    }

    // 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']]);
    }

    // Optionally attach image to current user for ownership
    $attachment = [
        'post_mime_type' => $uploaded['type'],
        'post_title'     => sanitize_file_name($file['name']),
        'post_content'   => '',
        'post_status'    => 'inherit'
    ];
    $attach_id = wp_insert_attachment($attachment, $uploaded['file']);
    require_once ABSPATH . 'wp-admin/includes/image.php';
    wp_generate_attachment_metadata($attach_id, $uploaded['file']);

    $url = wp_get_attachment_url($attach_id);

    wp_send_json_success(['url' => esc_url_raw($url)]);
    wp_die(); // <- THIS IS CRITICAL
});

// Important: No closing PHP tag and **NO WHITESPACE** after this line!
