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

if (!function_exists('vmo_generate_image_asset')) {
    function vmo_generate_image_asset($args = array()) {
        $defaults = array(
            'user_id' => 0,
            'desc' => '',
            'position' => 'auto',
            'size' => '1024x1024',
            'section' => 'website-content',
            'project_id' => 0,
            'session_id' => '',
            'charge_tokens' => true,
            'require_consultation' => true,
        );

        $args = wp_parse_args($args, $defaults);
        $user_id = intval($args['user_id']);
        $desc = sanitize_text_field($args['desc']);
        $position = sanitize_text_field($args['position']);
        $size = sanitize_text_field($args['size']);
        $section = sanitize_text_field($args['section']);
        $project_id = intval($args['project_id']);
        $session_id = sanitize_text_field($args['session_id']);
        $charge_tokens = !empty($args['charge_tokens']);
        $require_consultation = !empty($args['require_consultation']);
        $token_cost = function_exists('vmo_get_token_cost') ? vmo_get_token_cost('dalle_image') : 1080;
        $tokens_charged = false;

        if (!$desc || !$user_id) {
            return array('error' => 'Missing description or user context.');
        }

        if ($require_consultation) {
            if (!function_exists('vmo_is_consultation_ready')) {
                require_once plugin_dir_path(__FILE__) . 'consultation-profile.php';
            }

            if (!function_exists('vmo_is_consultation_ready') || !vmo_is_consultation_ready($user_id)) {
                return array(
                    'error' => 'Complete the Business Consultation to enable automated generation.',
                    'status' => 'consultation_required',
                );
            }
        }

        if ($charge_tokens && function_exists('vmo_deduct_tokens_for_operation')) {
            if (!vmo_deduct_tokens_for_operation($user_id, 'dalle_image')) {
                return array(
                    'error' => 'Insufficient tokens for image generation. Please top up your balance.',
                    'status' => 'insufficient_tokens',
                );
            }
            $tokens_charged = true;
        }

        $api_key = get_option('vmo_openai_api_key');
        if (!$api_key) {
            if ($tokens_charged && function_exists('vmo_add_tokens')) {
                vmo_add_tokens($user_id, $token_cost, 'dalle_refund', 'Image generation failed - refund');
            }
            return array('error' => 'OpenAI API key is missing.');
        }

        $enhanced_prompt = 'Ultra-realistic, cinematic, premium quality image for modern WordPress hero/section. '
            . 'Vibrant lighting, elegant composition, sharp details, soft background. '
            . 'Use-case: ' . $section . '. Placement: ' . $position . ', Size: ' . $size . '. '
            . 'No text, no watermark. Prompt: ' . $desc;

        $response = wp_remote_post('https://api.openai.com/v1/images/generations', array(
            'headers' => array(
                'Authorization' => 'Bearer ' . $api_key,
                'Content-Type'  => 'application/json',
            ),
            'body' => wp_json_encode(array(
                'model' => 'gpt-image-1',
                'prompt' => $enhanced_prompt,
                'n' => 1,
                'size' => '1024x1024',
                'response_format' => 'url',
            )),
            'timeout' => 120,
            'sslverify' => true,
            'redirection' => 5,
            'httpversion' => '1.0',
            'blocking' => true,
        ));

        if (is_wp_error($response)) {
            if ($tokens_charged && function_exists('vmo_add_tokens')) {
                vmo_add_tokens($user_id, $token_cost, 'dalle_refund', 'Image generation request failed - refund');
            }
            error_log('VMO AI Builder - DALL·E API Error: ' . $response->get_error_message());
            return array('error' => 'Image generation failed: ' . $response->get_error_message());
        }

        $response_code = wp_remote_retrieve_response_code($response);
        if ($response_code !== 200) {
            if ($tokens_charged && function_exists('vmo_add_tokens')) {
                vmo_add_tokens($user_id, $token_cost, 'dalle_refund', 'Image generation HTTP failure - refund');
            }
            $response_body = wp_remote_retrieve_body($response);
            error_log('VMO AI Builder - DALL·E HTTP Error ' . $response_code . ': ' . $response_body);
            return array('error' => 'OpenAI DALL·E API returned error code: ' . $response_code);
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);
        $image_url = $body['data'][0]['url'] ?? '';

        if (!$image_url) {
            if ($tokens_charged && function_exists('vmo_add_tokens')) {
                vmo_add_tokens($user_id, $token_cost, 'dalle_refund', 'Image generation returned no asset - refund');
            }
            return array('error' => 'No image URL returned from OpenAI.');
        }

        $tmp = download_url($image_url);
        if (is_wp_error($tmp)) {
            if ($tokens_charged && function_exists('vmo_add_tokens')) {
                vmo_add_tokens($user_id, $token_cost, 'dalle_refund', 'Generated image download failed - refund');
            }
            return array('error' => 'Image download failed.');
        }

        $file_array = array(
            'name' => 'vmo-generated-' . time() . '.jpg',
            'tmp_name' => $tmp,
        );

        if (!function_exists('media_handle_sideload')) {
            require_once ABSPATH . 'wp-admin/includes/image.php';
            require_once ABSPATH . 'wp-admin/includes/file.php';
            require_once ABSPATH . 'wp-admin/includes/media.php';
        }

        $attachment_id = media_handle_sideload($file_array, 0);
        if (is_wp_error($attachment_id)) {
            @unlink($tmp);
            if ($tokens_charged && function_exists('vmo_add_tokens')) {
                vmo_add_tokens($user_id, $token_cost, 'dalle_refund', 'Generated image upload failed - refund');
            }
            return array('error' => 'Media upload failed.');
        }

        wp_update_post(array(
            'ID' => $attachment_id,
            'post_author' => $user_id,
        ));

        update_post_meta($attachment_id, '_vmo_img_desc', $desc);
        update_post_meta($attachment_id, '_vmo_img_position', $position);
        update_post_meta($attachment_id, '_vmo_img_size', $size);
        update_post_meta($attachment_id, '_vmo_img_section', $section);
        update_post_meta($attachment_id, '_vmo_project_id', $project_id);

        $final_url = wp_get_attachment_url($attachment_id);
        if (!$final_url) {
            if ($tokens_charged && function_exists('vmo_add_tokens')) {
                vmo_add_tokens($user_id, $token_cost, 'dalle_refund', 'Generated image URL retrieval failed - refund');
            }
            return array('error' => 'Could not retrieve final image URL.');
        }

        try {
            if (!class_exists('VMO_Consultation_Database')) {
                require_once plugin_dir_path(__FILE__) . 'class-vmo-consultation-database.php';
            }
            if (class_exists('VMO_Consultation_Database')) {
                $db = new VMO_Consultation_Database();
                $consultation_id = 0;
                if ($session_id && method_exists($db, 'get_consultation_by_session')) {
                    $row = $db->get_consultation_by_session($session_id);
                    if ($row && isset($row->id)) {
                        $consultation_id = intval($row->id);
                    }
                }
                $db->save_consultation_media($consultation_id, array(
                    'url' => $final_url,
                    'type' => 'image',
                    'title' => $desc,
                    'context' => array(
                        'source' => 'generated_dalle',
                        'prompt' => $desc,
                        'attachment_id' => $attachment_id,
                        'project_id' => $project_id,
                        'user_id' => $user_id,
                        'position' => $position,
                        'size' => $size,
                        'section' => $section,
                        'created_via' => 'server-image-helper',
                    ),
                ));
            }
        } catch (\Throwable $e) {
            error_log('VMO generate-image DB record failed: ' . $e->getMessage());
        }

        return array(
            'success' => true,
            'url' => $final_url,
            'attachment_id' => $attachment_id,
            'message' => 'Image generated & saved ✅',
        );
    }
}

/**
 * AJAX: Generate a high-quality image via DALL·E and attach to Media Library with metadata
 */
add_action('wp_ajax_vmo_generate_image', 'vmo_generate_image');

function vmo_generate_image() {
    // 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'] : '';
    if (!(($admin_nonce && wp_verify_nonce($admin_nonce, 'vmo_admin_nonce')) || ($builder_nonce && wp_verify_nonce($builder_nonce, 'vmo_builder_nonce')))) {
        wp_send_json_error(['message' => 'Security check failed', 'status' => 'invalid_nonce']);
        return;
    }
    
    $user_id = get_current_user_id();
    $result = vmo_generate_image_asset(array(
        'user_id' => $user_id,
        'desc' => wp_unslash($_POST['desc'] ?? ''),
        'position' => wp_unslash($_POST['position'] ?? ''),
        'size' => wp_unslash($_POST['size'] ?? ''),
        'section' => wp_unslash($_POST['section'] ?? ''),
        'project_id' => intval($_POST['project_id'] ?? 0),
        'session_id' => sanitize_text_field($_POST['session_id'] ?? get_user_meta($user_id, 'vmo_current_session_id', true)),
        'charge_tokens' => true,
        'require_consultation' => true,
    ));

    if (!empty($result['error'])) {
        wp_send_json_error(array(
            'message' => $result['error'],
            'status' => $result['status'] ?? 'generation_failed',
        ));
    }

    wp_send_json_success($result);
}