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

// includes/vmo_upload_device_image.php

if (!function_exists('vmo_upload_device_image_handler')) {
    function vmo_upload_device_image_handler() {
        // 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 (empty($_FILES['image'])) {
            wp_send_json_error(['message' => 'No file received.']);
        }

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

        $attachment_id = media_handle_upload('image', 0);

        if (is_wp_error($attachment_id)) {
            wp_send_json_error(['message' => $attachment_id->get_error_message()]);
        }

        $url = wp_get_attachment_url($attachment_id);

        if (!$url) {
            wp_send_json_error(['message' => 'Upload failed.']);
        }

        wp_send_json_success([
            'id' => $attachment_id,
            'url' => esc_url($url)
        ]);
    }
}