<?php
/**
 * DALL-E Diagnostic Tool for LuxStrat International
 *
 * Drop this file into your plugin root: wp-content/plugins/damalion-blog-ai/
 * Then go to: WP Admin → DBA Settings → DALL-E Diagnostic
 *
 * It tests every step of the image pipeline independently:
 *   1. API key present?
 *   2. DBA_Image_Generator class loaded? Method exists?
 *   3. Can PHP reach api.openai.com?
 *   4. Does DALL-E 3 API actually return an image URL?
 *   5. Can we download that image?
 *   6. Can we sideload it into the WP media library?
 *   7. Can we set it as a post thumbnail?
 *
 * Remove this file after debugging.
 *
 * @package DamalionBlogAI
 */

if ( ! defined( 'ABSPATH' ) ) exit;

// ── Register admin page ──
add_action( 'admin_menu', function() {
    add_submenu_page(
        'dba-settings',
        'DALL-E Diagnostic',
        '🔬 DALL-E Diagnostic',
        'manage_options',
        'dba-dalle-diagnostic',
        'dba_dalle_diagnostic_page'
    );
}, 99 );

// ── Register AJAX handler ──
add_action( 'wp_ajax_dba_dalle_diagnostic_run', 'dba_dalle_diagnostic_ajax' );

function dba_dalle_diagnostic_ajax() {
    check_ajax_referer( 'dba_dalle_diagnostic', 'nonce' );
    if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error( 'Permission denied.' );

    @set_time_limit( 300 );
    @ini_set( 'max_execution_time', '300' );

    $results = array();
    $post_id = absint( $_POST['post_id'] ?? 0 );

    // ═══════════════════════════════════════════
    //  TEST 1: PHP Environment
    // ═══════════════════════════════════════════
    $results[] = array(
        'test'   => 'PHP Environment',
        'status' => 'info',
        'detail' => 'max_execution_time=' . ini_get('max_execution_time') . 's | memory_limit=' . ini_get('memory_limit') . ' | PHP ' . phpversion(),
    );

    // ═══════════════════════════════════════════
    //  TEST 2: OpenAI API Key
    // ═══════════════════════════════════════════
    $dba_settings = get_option( 'dba_settings', array() );
    $api_key = ! empty( $dba_settings['openai_api_key'] ) ? $dba_settings['openai_api_key'] : '';

    if ( empty( $api_key ) ) {
        $results[] = array(
            'test'   => 'OpenAI API Key',
            'status' => 'FAIL',
            'detail' => 'No openai_api_key found in dba_settings option. DALL-E cannot work without this. Check DBA Settings → API Key.',
        );
        wp_send_json_success( $results );
        return;
    }

    $masked = substr( $api_key, 0, 8 ) . '...' . substr( $api_key, -4 );
    $results[] = array(
        'test'   => 'OpenAI API Key',
        'status' => 'PASS',
        'detail' => 'Key found: ' . $masked . ' (' . strlen( $api_key ) . ' chars)',
    );

    // ═══════════════════════════════════════════
    //  TEST 3: DBA_Image_Generator class
    // ═══════════════════════════════════════════
    if ( class_exists( 'DBA_Image_Generator' ) ) {
        $instance = DBA_Image_Generator::get_instance();
        $has_method = method_exists( $instance, 'generate_and_attach' );
        $results[] = array(
            'test'   => 'DBA_Image_Generator Class',
            'status' => $has_method ? 'PASS' : 'WARN',
            'detail' => 'Class exists. generate_and_attach() method: ' . ( $has_method ? 'YES' : 'NOT FOUND — LuxStrat will use direct fallback' ),
        );

        // Check method signature
        if ( $has_method ) {
            $ref = new ReflectionMethod( $instance, 'generate_and_attach' );
            $params = array();
            foreach ( $ref->getParameters() as $p ) {
                $params[] = '$' . $p->getName() . ( $p->isOptional() ? '=' . json_encode( $p->getDefaultValue() ) : '' );
            }
            $results[] = array(
                'test'   => 'generate_and_attach() Signature',
                'status' => 'info',
                'detail' => 'Parameters: (' . implode( ', ', $params ) . ') — LuxStrat calls it with ($prompt, $post_id, $title, $image_size)',
            );
        }
    } else {
        $results[] = array(
            'test'   => 'DBA_Image_Generator Class',
            'status' => 'WARN',
            'detail' => 'Class NOT loaded. LuxStrat will rely entirely on generate_image_direct().',
        );
    }

    // ═══════════════════════════════════════════
    //  TEST 4: Network — Can we reach OpenAI?
    // ═══════════════════════════════════════════
    $results[] = array(
        'test'   => 'Network Test',
        'status' => 'info',
        'detail' => 'Testing HTTPS connection to api.openai.com...',
    );

    $net_test = wp_remote_get( 'https://api.openai.com/v1/models', array(
        'timeout' => 15,
        'headers' => array( 'Authorization' => 'Bearer ' . $api_key ),
    ) );

    if ( is_wp_error( $net_test ) ) {
        $results[] = array(
            'test'   => 'Network to OpenAI',
            'status' => 'FAIL',
            'detail' => 'Cannot reach api.openai.com: ' . $net_test->get_error_message() . ' — Your host may block outbound HTTPS or have a firewall.',
        );
        wp_send_json_success( $results );
        return;
    }

    $net_code = wp_remote_retrieve_response_code( $net_test );
    if ( $net_code === 200 ) {
        $results[] = array(
            'test'   => 'Network to OpenAI',
            'status' => 'PASS',
            'detail' => 'HTTP 200 — Connection to api.openai.com works. API key is valid.',
        );
    } elseif ( $net_code === 401 ) {
        $results[] = array(
            'test'   => 'Network to OpenAI',
            'status' => 'FAIL',
            'detail' => 'HTTP 401 — API key is INVALID or expired. Network works, but key is rejected.',
        );
        wp_send_json_success( $results );
        return;
    } else {
        $results[] = array(
            'test'   => 'Network to OpenAI',
            'status' => 'WARN',
            'detail' => 'HTTP ' . $net_code . ' — Unexpected response. Body: ' . substr( wp_remote_retrieve_body( $net_test ), 0, 200 ),
        );
    }

    // ═══════════════════════════════════════════
    //  TEST 5: DALL-E 3 API Call (REAL)
    // ═══════════════════════════════════════════
    $results[] = array(
        'test'   => 'DALL-E 3 API Call',
        'status' => 'info',
        'detail' => 'Sending real DALL-E 3 request (1792x1024 landscape)... This takes 15-45 seconds.',
    );

    $test_prompt = 'Ultra-realistic professional photography of a modern commercial office building in a European financial district. Clean glass facade, blue sky, professional business atmosphere. Architectural photography style.';

    $start_time = microtime( true );

    $dalle_resp = wp_remote_post( 'https://api.openai.com/v1/images/generations', array(
        'timeout' => 120,
        'headers' => array(
            'Content-Type'  => 'application/json',
            'Authorization' => 'Bearer ' . $api_key,
        ),
        'body' => wp_json_encode( array(
            'model'           => 'dall-e-3',
            'prompt'          => $test_prompt,
            'n'               => 1,
            'size'            => '1792x1024',
            'quality'         => 'standard',
            'response_format' => 'url',
        ) ),
    ) );

    $elapsed = round( microtime( true ) - $start_time, 2 );

    if ( is_wp_error( $dalle_resp ) ) {
        $results[] = array(
            'test'   => 'DALL-E 3 API Call',
            'status' => 'FAIL',
            'detail' => 'FAILED after ' . $elapsed . 's — ' . $dalle_resp->get_error_message() . ' — This is likely a timeout or firewall issue.',
        );
        wp_send_json_success( $results );
        return;
    }

    $dalle_code = wp_remote_retrieve_response_code( $dalle_resp );
    $dalle_body = wp_remote_retrieve_body( $dalle_resp );

    if ( $dalle_code !== 200 ) {
        $results[] = array(
            'test'   => 'DALL-E 3 API Call',
            'status' => 'FAIL',
            'detail' => 'HTTP ' . $dalle_code . ' after ' . $elapsed . 's — ' . substr( $dalle_body, 0, 500 ),
        );
        wp_send_json_success( $results );
        return;
    }

    $dalle_data = json_decode( $dalle_body, true );
    $image_url = $dalle_data['data'][0]['url'] ?? '';

    if ( empty( $image_url ) ) {
        $results[] = array(
            'test'   => 'DALL-E 3 API Call',
            'status' => 'FAIL',
            'detail' => 'HTTP 200 but no image URL in response after ' . $elapsed . 's — Body: ' . substr( $dalle_body, 0, 300 ),
        );
        wp_send_json_success( $results );
        return;
    }

    $results[] = array(
        'test'   => 'DALL-E 3 API Call',
        'status' => 'PASS',
        'detail' => 'Image URL received in ' . $elapsed . 's (' . strlen( $image_url ) . ' char URL)',
    );

    // ═══════════════════════════════════════════
    //  TEST 6: Download Image
    // ═══════════════════════════════════════════
    if ( ! function_exists( 'media_sideload_image' ) ) {
        require_once ABSPATH . 'wp-admin/includes/media.php';
        require_once ABSPATH . 'wp-admin/includes/file.php';
        require_once ABSPATH . 'wp-admin/includes/image.php';
    }

    $dl_start = microtime( true );
    $tmp_file = download_url( $image_url );
    $dl_elapsed = round( microtime( true ) - $dl_start, 2 );

    if ( is_wp_error( $tmp_file ) ) {
        $results[] = array(
            'test'   => 'Image Download',
            'status' => 'FAIL',
            'detail' => 'download_url() failed after ' . $dl_elapsed . 's — ' . $tmp_file->get_error_message(),
        );
        wp_send_json_success( $results );
        return;
    }

    $file_size = filesize( $tmp_file );
    $results[] = array(
        'test'   => 'Image Download',
        'status' => 'PASS',
        'detail' => 'Downloaded in ' . $dl_elapsed . 's — temp file: ' . basename( $tmp_file ) . ' (' . round( $file_size / 1024 ) . ' KB)',
    );

    // ═══════════════════════════════════════════
    //  TEST 7: Sideload to Media Library
    // ═══════════════════════════════════════════
    $target_post_id = $post_id > 0 ? $post_id : 0;

    $media_id = media_handle_sideload(
        array(
            'name'     => 'dalle-diagnostic-test-' . time() . '.png',
            'tmp_name' => $tmp_file,
        ),
        $target_post_id,
        'DALL-E Diagnostic Test Image'
    );

    if ( is_wp_error( $media_id ) ) {
        $results[] = array(
            'test'   => 'Media Sideload',
            'status' => 'FAIL',
            'detail' => 'media_handle_sideload() failed — ' . $media_id->get_error_message(),
        );
        @unlink( $tmp_file );
        wp_send_json_success( $results );
        return;
    }

    $attachment_url = wp_get_attachment_url( $media_id );
    $results[] = array(
        'test'   => 'Media Sideload',
        'status' => 'PASS',
        'detail' => 'Media #' . $media_id . ' created — ' . $attachment_url,
    );

    // ═══════════════════════════════════════════
    //  TEST 8: Set as Featured Image (if post_id given)
    // ═══════════════════════════════════════════
    if ( $post_id > 0 ) {
        $post = get_post( $post_id );
        if ( ! $post ) {
            $results[] = array(
                'test'   => 'Set Featured Image',
                'status' => 'FAIL',
                'detail' => 'Post #' . $post_id . ' does not exist.',
            );
        } else {
            $set_result = set_post_thumbnail( $post_id, $media_id );
            $has_thumb  = has_post_thumbnail( $post_id );
            $results[] = array(
                'test'   => 'Set Featured Image',
                'status' => $has_thumb ? 'PASS' : 'FAIL',
                'detail' => $has_thumb
                    ? 'Featured image set on post #' . $post_id . ' ("' . $post->post_title . '") — Media #' . $media_id
                    : 'set_post_thumbnail() returned ' . var_export( $set_result, true ) . ' but has_post_thumbnail() is false.',
            );
        }
    } else {
        $results[] = array(
            'test'   => 'Set Featured Image',
            'status' => 'SKIP',
            'detail' => 'No post ID provided. Enter a post ID above to also test setting the featured image.',
        );
    }

    // ═══════════════════════════════════════════
    //  SUMMARY
    // ═══════════════════════════════════════════
    $fails = array_filter( $results, function( $r ) { return $r['status'] === 'FAIL'; } );
    $results[] = array(
        'test'   => 'OVERALL',
        'status' => empty( $fails ) ? 'ALL PASS' : count( $fails ) . ' FAILURE(S)',
        'detail' => empty( $fails )
            ? 'The entire DALL-E pipeline works. The problem is likely PHP timeout during the full post generation (content + DALL-E together).'
            : 'Failed tests: ' . implode( ', ', array_map( function($r){ return $r['test']; }, $fails ) ),
    );

    wp_send_json_success( $results );
}


/**
 * Render the diagnostic admin page.
 */
function dba_dalle_diagnostic_page() {
    if ( ! current_user_can( 'manage_options' ) ) wp_die( 'Access denied.' );

    // Find a recent LuxStrat FR post without a featured image
    $prefix = '_dba_luxstrat_fr_';
    $recent = get_posts( array(
        'post_type'      => 'post',
        'post_status'    => 'any',
        'posts_per_page' => 5,
        'orderby'        => 'date',
        'order'          => 'DESC',
        'meta_query'     => array( array( 'key' => $prefix . 'auto_created', 'compare' => 'EXISTS' ) ),
    ) );
    ?>
    <div class="wrap">
        <h1>🔬 DALL-E Diagnostic Tool</h1>
        <p style="font-size:14px;color:#555;max-width:700px;">
            This tool tests every step of the DALL-E image pipeline independently.
            It will make a <strong>real DALL-E API call</strong> (costs ~$0.04) and attempt to download, sideload, and attach the image.
        </p>

        <?php if ( ! empty( $recent ) ) : ?>
        <div style="background:#fff3cd;border:1px solid #ffc107;border-radius:6px;padding:16px;margin:16px 0;max-width:700px;">
            <strong>Recent LuxStrat FR posts (enter an ID below to also fix its missing image):</strong>
            <ul style="margin:8px 0 0;padding-left:20px;">
            <?php foreach ( $recent as $p ) :
                $has_img = has_post_thumbnail( $p->ID );
            ?>
                <li>
                    #<?php echo $p->ID; ?> — <?php echo esc_html( $p->post_title ); ?>
                    — Image: <strong style="color:<?php echo $has_img ? '#166534' : '#991b1b'; ?>;"><?php echo $has_img ? 'YES' : 'MISSING'; ?></strong>
                </li>
            <?php endforeach; ?>
            </ul>
        </div>
        <?php endif; ?>

        <div style="background:#fff;border:1px solid #ddd;border-radius:8px;padding:24px;margin:20px 0;max-width:700px;">
            <label><strong>Post ID (optional):</strong></label><br>
            <input type="number" id="dalle-diag-post-id" value="" placeholder="e.g. 12345" style="width:200px;padding:6px;margin:8px 0;">
            <p style="font-size:12px;color:#888;">If provided, the test image will be set as the featured image for this post.</p>
            <br>
            <button id="dalle-diag-run" class="button button-primary button-hero" style="font-size:16px;">
                🚀 Run Full DALL-E Diagnostic
            </button>
            <span id="dalle-diag-spinner" style="display:none;margin-left:12px;font-size:14px;color:#666;">
                ⏳ Running... this takes 30-60 seconds, do NOT close this page.
            </span>
        </div>

        <div id="dalle-diag-results" style="max-width:700px;"></div>
    </div>

    <script>
    jQuery(function($) {
        $('#dalle-diag-run').on('click', function() {
            var $btn = $(this);
            var $spinner = $('#dalle-diag-spinner');
            var $results = $('#dalle-diag-results');
            var postId = $('#dalle-diag-post-id').val() || 0;

            $btn.prop('disabled', true);
            $spinner.show();
            $results.html('<p style="color:#666;">Starting diagnostic...</p>');

            $.ajax({
                url: ajaxurl,
                method: 'POST',
                timeout: 300000, // 5 minutes
                data: {
                    action: 'dba_dalle_diagnostic_run',
                    nonce: '<?php echo wp_create_nonce( 'dba_dalle_diagnostic' ); ?>',
                    post_id: postId,
                },
                success: function(resp) {
                    $spinner.hide();
                    $btn.prop('disabled', false);

                    if (!resp.success || !resp.data) {
                        $results.html('<div style="background:#fee;padding:16px;border-radius:6px;border:1px solid #c00;">Error: ' + JSON.stringify(resp) + '</div>');
                        return;
                    }

                    var html = '';
                    resp.data.forEach(function(r) {
                        var color = '#333', bg = '#f9f9f9', icon = 'ℹ️';
                        if (r.status === 'PASS' || r.status === 'ALL PASS') {
                            bg = '#dcfce7'; color = '#166534'; icon = '✅';
                        } else if (r.status === 'FAIL') {
                            bg = '#fee2e2'; color = '#991b1b'; icon = '❌';
                        } else if (r.status === 'WARN') {
                            bg = '#fff3cd'; color = '#856404'; icon = '⚠️';
                        } else if (r.status === 'SKIP') {
                            bg = '#e2e8f0'; color = '#475569'; icon = '⏭️';
                        }

                        html += '<div style="background:' + bg + ';color:' + color + ';padding:14px 18px;margin:6px 0;border-radius:6px;border-left:4px solid ' + color + ';">';
                        html += '<strong>' + icon + ' ' + r.test + '</strong> <span style="float:right;font-weight:700;">' + r.status + '</span><br>';
                        html += '<span style="font-size:13px;opacity:0.9;">' + r.detail + '</span>';
                        html += '</div>';
                    });

                    $results.html(html);
                },
                error: function(xhr, status, err) {
                    $spinner.hide();
                    $btn.prop('disabled', false);
                    $results.html('<div style="background:#fee;padding:16px;border-radius:6px;border:1px solid #c00;"><strong>AJAX Error:</strong> ' + status + ' — ' + err + '<br><br>This likely means PHP timed out before the test could finish. Your host may have a hard limit on max_execution_time that cannot be overridden. Check with your hosting provider.</div>');
                }
            });
        });
    });
    </script>
    <?php
}
