<?php
if ( ! defined( 'ABSPATH' ) ) exit;
class SBPAI_Service_Media {
    public static function fetch_image( $width = 800, $height = 600, $keyword = '' ) {
        require_once( ABSPATH . 'wp-admin/includes/media.php' );
        require_once( ABSPATH . 'wp-admin/includes/file.php' );
        require_once( ABSPATH . 'wp-admin/includes/image.php' );

        $tmp = wp_tempnam( 'sbpai-local-image' );
        if ( ! $tmp ) {
            return false;
        }

        $text = empty( $keyword ) || 'General' === $keyword ? 'SandboxPress AI' : ucwords( $keyword );

        // 1. Check if GD is available to build a high-quality JPG image
        if ( function_exists( 'imagecreatetruecolor' ) ) {
            $im = imagecreatetruecolor( $width, $height );
            
            // Generate clean pastel colors derived from the keyword/niche
            $hash = md5( $text );
            $r = hexdec( substr( $hash, 0, 2 ) );
            $g = hexdec( substr( $hash, 2, 2 ) );
            $b = hexdec( substr( $hash, 4, 2 ) );
            
            // Adjust to pastel tones (mix with white to keep it bright and modern)
            $r = (int) ( ( $r + 255 ) / 2 );
            $g = (int) ( ( $g + 255 ) / 2 );
            $b = (int) ( ( $b + 255 ) / 2 );
            
            $bg = imagecolorallocate( $im, $r, $g, $b );
            imagefill( $im, 0, 0, $bg );
            
            // Add clean border
            $border_color = imagecolorallocate( $im, max( 0, $r - 40 ), max( 0, $g - 40 ), max( 0, $b - 40 ) );
            imagerectangle( $im, 0, 0, $width - 1, $height - 1, $border_color );

            // Add niche label text in the center
            $text_color = imagecolorallocate( $im, max( 0, $r - 120 ), max( 0, $g - 120 ), max( 0, $b - 120 ) );
            
            $font_width  = imagefontwidth( 5 );
            $font_height = imagefontheight( 5 );
            $text_width  = $font_width * strlen( $text );
            
            $x = ( $width - $text_width ) / 2;
            $y = ( $height - $font_height ) / 2;
            
            imagestring( $im, 5, (int)$x, (int)$y, $text, $text_color );
            
            imagejpeg( $im, $tmp, 90 );
            imagedestroy( $im );

            $file_array = array(
                'name'     => 'sbpai-local-' . uniqid() . '.jpg',
                'tmp_name' => $tmp
            );
        } else {
            // 2. Fallback to writing a valid SVG file locally
            $svg_content = '<?xml version="1.0" encoding="utf-8"?>
            <svg xmlns="http://www.w3.org/2000/svg" width="' . intval($width) . '" height="' . intval($height) . '" viewBox="0 0 ' . intval($width) . ' ' . intval($height) . '">
                <rect width="100%" height="100%" fill="#f3f4f6" stroke="#e5e7eb" stroke-width="2"/>
                <text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" font-family="sans-serif" font-size="24" fill="#4b5563">' . esc_html( $text ) . '</text>
            </svg>';
            
            $svg_tmp = wp_tempnam( 'sbpai-fallback-svg' );
            if ( $svg_tmp ) {
                file_put_contents( $svg_tmp, $svg_content );
                $file_array = array(
                    'name'     => 'sbpai-local-' . uniqid() . '.svg',
                    'tmp_name' => $svg_tmp
                );
            } else {
                return false;
            }
        }

        $id = media_handle_sideload( $file_array, 0 );

        if ( is_wp_error( $id ) ) {
            wp_delete_file( $file_array['tmp_name'] );
            return false;
        }

        update_post_meta( $id, '_sbpai_media', '1' ); // Strict tracking key
        return $id;
    }
}
