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

if (!function_exists('vmo_prepare_long_generation_runtime')) {
    function vmo_prepare_long_generation_runtime() {
        if (function_exists('set_time_limit')) {
            @set_time_limit(0);
        }
        if (function_exists('ignore_user_abort')) {
            @ignore_user_abort(true);
        }
        if (function_exists('ini_set')) {
            @ini_set('memory_limit', '512M');
        }
    }
}

if (!function_exists('vmo_generate_image_asset')) {
    function vmo_generate_image_asset($args = array()) {
        vmo_prepare_long_generation_runtime();

        $defaults = array(
            'user_id' => 0,
            'desc' => '',
            'position' => 'auto',
            'size' => '1024x1024',
            'section' => 'website-content',
            'project_id' => 0,
            'session_id' => '',
            'charge_tokens' => true,
            'require_consultation' => true,
            'model' => '',
        );

        $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']);
        $requested_model = sanitize_text_field($args['model']);
        $default_image_model = function_exists('vmo_get_model')
            ? vmo_get_model('image')
            : (defined('VMO_OPENAI_IMAGE_MODEL') ? VMO_OPENAI_IMAGE_MODEL : 'gpt-image-1');
        $allowed_models = array_filter(array_unique(array(
            $default_image_model,
            defined('VMO_OPENAI_IMAGE_MODEL') ? VMO_OPENAI_IMAGE_MODEL : '',
            defined('VMO_IMAGE_MODEL') ? VMO_IMAGE_MODEL : '',
            'openai-image-generation-2',
            'gpt-image-2',
            'gpt-image-1',
            'dall-e-3',
        )));
        $image_model = in_array($requested_model, $allowed_models, true) ? $requested_model : $default_image_model;
        $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;
        }

        $client_mode = defined('VMO_CLIENT_MODE') && VMO_CLIENT_MODE === true;
        $api_key = get_option('vmo_openai_api_key');
        if (!$client_mode && !$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' => 'AI 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;

        $request_timeout = function_exists('apply_filters') ? (int) apply_filters('vmo_image_generation_timeout', 180) : 180;
        $request_timeout = max(120, $request_timeout);
        $supported_sizes = array('1024x1024', '1536x1024', '1024x1536', '1792x1024', '1024x1792', 'auto');
        $base_request_size = in_array($size, $supported_sizes, true) ? $size : '1024x1024';
        $candidate_models = array_values(array_unique(array_filter(array(
            $image_model,
            function_exists('vmo_get_model') ? vmo_get_model('image') : '',
            function_exists('vmo_get_model') ? vmo_get_model('image_generation') : '',
            defined('VMO_OPENAI_IMAGE_MODEL') ? VMO_OPENAI_IMAGE_MODEL : '',
            defined('VMO_IMAGE_MODEL') ? VMO_IMAGE_MODEL : '',
            'gpt-image-1',
            'dall-e-3',
        ))));
        $image_url = '';
        $image_base64 = '';
        $successful_model = '';
        $last_error_message = '';

        foreach ($candidate_models as $candidate_model) {
            $is_gpt_image_model = (strpos($candidate_model, 'gpt-image') !== false || strpos($candidate_model, 'openai-image-generation') !== false);
            $request_size = $base_request_size;
            if (!$is_gpt_image_model && $request_size === '1536x1024') {
                $request_size = '1792x1024';
            } elseif (!$is_gpt_image_model && $request_size === '1024x1536') {
                $request_size = '1024x1792';
            } elseif (!$is_gpt_image_model && $request_size === 'auto') {
                $request_size = '1024x1024';
            }

            $request_body = array(
                'model' => $candidate_model,
                'prompt' => $enhanced_prompt,
                'n' => 1,
                'size' => $request_size,
            );

            if ($is_gpt_image_model) {
                $request_body['output_format'] = 'png';
            } else {
                $request_body['response_format'] = 'url';
            }

            $request_args = array(
                'headers' => array(
                    'Content-Type'  => 'application/json',
                ),
                'body' => wp_json_encode($request_body),
                'timeout' => $request_timeout,
                'sslverify' => true,
                'redirection' => 5,
                'httpversion' => '1.0',
                'blocking' => true,
            );

            if (!$client_mode) {
                $request_args['headers']['Authorization'] = 'Bearer ' . $api_key;
            }

            $response = function_exists('vmo_api_request')
                ? vmo_api_request('openai', 'v1/images/generations', $request_args, 'POST')
                : wp_remote_post('https://api.openai.com/v1/images/generations', $request_args);

            if (is_wp_error($response)) {
                $last_error_message = 'Image generation request failed with ' . $candidate_model . ': ' . $response->get_error_message();
                error_log('VMO AI Builder - Image API Error: ' . $last_error_message);
                continue;
            }

            $response_code = wp_remote_retrieve_response_code($response);
            $response_body = wp_remote_retrieve_body($response);
            $body = json_decode($response_body, true);
            $image_url = is_array($body) ? ($body['data'][0]['url'] ?? '') : '';
            $image_base64 = is_array($body) ? ($body['data'][0]['b64_json'] ?? '') : '';

            if ($response_code === 200 && ($image_url || $image_base64)) {
                $successful_model = $candidate_model;
                break;
            }

            $api_error_message = '';
            if (is_array($body) && isset($body['error'])) {
                $api_error = $body['error'];
                $api_error_message = trim((string) ($api_error['message'] ?? ''));
                $api_error_code = trim((string) ($api_error['code'] ?? ''));
                $api_error_type = trim((string) ($api_error['type'] ?? ''));
                if ($api_error_code !== '') {
                    $api_error_message .= ' Code: ' . $api_error_code . '.';
                }
                if ($api_error_type !== '') {
                    $api_error_message .= ' Type: ' . $api_error_type . '.';
                }
            }
            if ($api_error_message === '') {
                $api_error_message = trim(wp_strip_all_tags((string) $response_body));
            }

            $request_id = (string) (wp_remote_retrieve_header($response, 'x-request-id') ?: wp_remote_retrieve_header($response, 'openai-request-id'));
            $last_error_message = 'Image generation failed with ' . $candidate_model . ': HTTP ' . $response_code;
            if ($api_error_message !== '') {
                $last_error_message .= ' - ' . $api_error_message;
            }
            if ($request_id !== '') {
                $last_error_message .= ' Request ID: ' . $request_id . '.';
            }

            error_log('VMO AI Builder - Image HTTP Error: ' . $last_error_message);

            $can_try_next_model = in_array($response_code, array(400, 403, 404, 422), true)
                && !preg_match('/content policy|safety|policy/i', $api_error_message);
            if (!$can_try_next_model) {
                break;
            }
        }

        if (!$image_url && !$image_base64) {
            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' => $last_error_message ?: 'No image asset returned from AI.',
                'status' => 'generation_failed',
                'model' => $successful_model ?: $image_model,
            );
        }

        $file_extension = 'jpg';
        if ($image_url) {
            if (!function_exists('download_url')) {
                require_once ABSPATH . 'wp-admin/includes/file.php';
            }

            $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.');
            }
        } else {
            $decoded_image = base64_decode($image_base64, true);
            if ($decoded_image === false) {
                if ($tokens_charged && function_exists('vmo_add_tokens')) {
                    vmo_add_tokens($user_id, $token_cost, 'dalle_refund', 'Generated image decode failed - refund');
                }
                return array('error' => 'Image decode failed.');
            }

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

            $tmp = wp_tempnam('vmo-generated-image.png');
            if (!$tmp || file_put_contents($tmp, $decoded_image) === false) {
                if ($tokens_charged && function_exists('vmo_add_tokens')) {
                    vmo_add_tokens($user_id, $token_cost, 'dalle_refund', 'Generated image write failed - refund');
                }
                return array('error' => 'Generated image file could not be written.');
            }

            $file_extension = 'png';
        }

        $file_array = array(
            'name' => 'vmo-generated-' . time() . '.' . $file_extension,
            '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,
            'model' => $successful_model ?: $image_model,
            '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() {
    vmo_prepare_long_generation_runtime();

    // 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)),
        'model' => sanitize_text_field($_POST['model'] ?? $_POST['image_model'] ?? ''),
        '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);
}