<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once("config.php");
require_once("user/protect.php");
require_once("user/user-lib.php");

file_put_contents("TEMPuserid.txt","USERID: ".$userid);

$add2=0;
if (file_exists("add2.php")){
	require_once("add2.php");
}
@set_time_limit(3000);
@ini_set('max_execution_time', 900);

$db = new PDO(
      "mysql:host=".USER_DB_HOST.";dbname=".USER_DB_NAME.";charset=".USER_DB_CHARSET,
      USER_DB_USER, USER_DB_PASSWORD, [
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);

if ($masterkeymode==false) {
	$query = "SELECT user_apikey FROM users WHERE user_id = :userid";
	$statement = $db->prepare($query);
	$statement->bindParam(':userid', $userid);
	$statement->execute();
	$result = $statement->fetch(PDO::FETCH_ASSOC);
	if ($result && !empty($result['user_apikey'])) {
		$api_key = $result['user_apikey'];
	} else {
		echo "NOUSERKEY";
		exit();
	}
} else {
	$api_key = $masterapikey;
}


// Check for credits system and set key accordingly

if ($add2==1){
	$api_key = $masterapikey;
}

$imageprompt=$_POST["imageprompt"];
$reviseprompt=$_POST["reviseprompt"];
$imagesize=$_POST["imagesize"];
$imagetype=$_POST["imagetype"];
$imagestyle=$_POST["imagestyle"];

$curl_imagesize="1024x1024";
$curl_imagetype="vivid";

if ($imagesize==1){$curl_imagesize="1792x1024";}
if ($imagesize==2){$curl_imagesize="1024x1792";}
if ($imagetype==1){$curl_imagetype="natural";}

$prompt_before="";
$prompt_after="";

// Add style if needed

switch ($imagestyle) {
	
	case 1:
		$prompt_before="Digital art in Abstract style showcasing a composition of vibrant shapes and patterns interacting dynamically. Shapes, Colors, Non-representational, Dynamic, Patterns. The subject is ";
		break;

	case 2:
		$prompt_before="Digital art in Abstract Geometry style with a composition of interlocking triangles and circles, radiating modern vibes. Geometric, Non-representational, Triangles, Circles, Moder. The subject is ";
		break;

	case 3:
		$prompt_before="Digital art in the Art Deco style showcasing symmetrical designs with radiant colors and bold geometric forms. Geometric, Symmetry, Radiant, Bold, 1920s. The subject is ";
		break;
		
	case 4:
		$prompt_before="Digital illustration in Art Nouveau style of a woman surrounded by intricate floral motifs and curvilinear designs. Flowing, Floral, Curvilinear, Organic, Dynamic. The subject is ";
		break;
		
	case 5:
		$prompt_before="Digital art inspired by the Bauhaus movement, focusing on geometric shapes and functional form. Geometric, Functional, Design, Minimalist, Modernist. The subject is ";
		break;
		
	case 6:
		$prompt_before="Digital art in Bokeh style of a city at night with blurred lights creating luminous and dreamy spots throughout the scene. Soft focus, Lights, Dreamy, Luminous, Night. The subject is ";
		break;
		
	case 7:
		$prompt_before="Digital representation of a Brutalist design concept, emphasizing raw textures and monolithic structures. Raw, Concrete, Blocky, Unrefined, Stark. The subject is ";
		break;
		
	case 8:
		$prompt_before="Digital art capturing the Byzantine essence, focusing on religious icons with gold backgrounds and vibrant colors. Icons, Gold, Mosaic, Religious, Vibrant. The subject is ";
		break;
	
	case 9:
		$prompt_before="Digital art piece in the Celtic style showcasing intricate knotwork and spiral designs. Knotwork, Spirals, Patterns, Medieval, Intricate. The subject is ";
		break;	

	case 10: //
		$prompt_before="Expertly drawn colorful cartoon style. The subject is ";
		break;

	case 11:
		$prompt_before="Digital art in Charcoal style with bold strokes and fine details on a textured background. Smudged, Raw, Textured, Bold, Fine details. The subject is ";
		break;

	case 12: //
		$prompt_before="An illustration for a childrens book. The subject is ";
		break;

	case 13:
		$prompt_before="Digital art in Chinese Brush Painting style showcasing a serene image, emphasizing fluid brush strokes. Ink, Brush, Nature, Fluid, Serene. The subject is ";
		break;
		
	case 14:
		$prompt_before="Digital art in Chiptune style showcasing a pixelated images, accompanied by retro game icons. Pixelated, Retro, Video game, Colorful, Nostalgic. The subject is ";
		break;
		
	case 15: //
		$prompt_before="Bold, colorful, ultra vibrant colors, simple comic book style illustration. The subject is ";
		break;
		
	case 16: //
		$prompt_before="Create an artwork in the Classic American Comic Style. Emphasize bold lines, vibrant colors, and a Silver Age comic book aesthetic. The subject is ";
		break;
		
	case 17: //
		$prompt_before="British Comic Book style similar to 2000AD. Sci-Fi gritty. Futuristic. British Sci-Fi comics like 2000AD. The subject is ";
		break;
		
	case 18: //
		$prompt_before="Create a manga-style artwork. Characters should have spiky hair and large, expressive eyes, wearing a futuristic costume. Characters should be in an action pose with speed lines indicating movement, set against a high-tech city background. Emphasize detailed line work and a dynamic expression, in a black and white traditional manga format. The subject is ";
		break;
	
	case 19:
		$prompt_before="Digital piece in Concept Art style. Visionary, Pre-production, Movies, Games, Detailed. The subject is ";
		break;	

	case 20:
		$prompt_before="Digital art inspired by the Constructivist style, combining geometric shapes with bold colors to convey a social message. Geometric, Bold, Russia, Social, Everyday Materials. The subject is ";
		break;

	case 21:
		$prompt_before="Digital art in Cyber Folk style of a traditional folk pattern combined with digital symbols and holographic effects. Traditional, Folklore, Futuristic, Digital symbols, Fusion. The subject is ";
		break;

	case 22:
		$prompt_before="Digital art in Cybernetic style of a city where humans and robots coexist, with holographic interfaces and tech elements. Futuristic, Technology, Humans, Robots, Interfaces. The subject is ";
		break;

	case 23:
		$prompt_before="Digital art in Cyberpunk style portraying a neon-lit futuristic city with advanced tech and cybernetic beings. Futuristic, Neon, Technology, Dystopian, Cybernetic. The subject is ";
		break;
		
	case 24: //
		$prompt_before="Neon cyberpunk color , heavy strokes, illustration. The subject is ";
		break;
		
	case 25: //
		$prompt_before="Neon cyberpunk colors. fine ultra-detailed realistic + ultra photorealistic + high definition + 8k photo-realistic + intricate + realism + maximalist detail + very realistic. The subject is ";
		break;
		
	case 26:
		$prompt_before="Digital art piece in the Dadaist style, incorporating collage elements and emphasizing the absurd and irrational. Collage, Absurd, Irrational, Nonsense, Anti-art. The subject is ";
		break;
		
	case 27:
		$prompt_before="Digital art in Data Art style visualizing cosmic data. Data, Visualizing, Numbers, Artistic, Informative. The subject is ";
		break;
		
	case 28:
		$prompt_before="Digital art in Digital Collage style merging the images crafting a surreal collage. Composite, Multiple images, Merged, New narrative, Digital. The subject is ";
		break;
	
	case 29:
		$prompt_before="Digital art in Cubism style, deconstructed into geometric shapes offering multiple angles simultaneously. Geometric, Deconstructed, Multiple perspectives, Shapes. The subject is ";
		break;	

	case 30:
		$prompt_before="Digital painting in Impressionism style, capturing the vibrancy and mood with loose digital brushstrokes. Essence, Loose brushstrokes, Vibrancy, Mood. The subject is ";
		break;
		
	case 31:
		$prompt_before="Digital painting capturing the hues and textures as if painted on canvas. Digital, Brushstrokes, Canvas, Traditional, Texture. The subject is ";
		break;

	case 32:
		$prompt_before="Digital art in Double Exposure style combining multiple images and blending them harmoniously. Merged, Multiple images, Juxtaposition, Unique, Contrast. The subject is ";
		break;

	case 33:
		$prompt_before="Digital art of a whimsical scene where ethereal creatures and glowing plants create a sense of wonder and magic. Ethereal creatures, Glowing, Whimsical, Forest, Magic. The subject is ";
		break;
		
	case 34:
		$prompt_before="Digital art in Dystopian style of ruins where nature has reclaimed the buildings and technology, with remnants of old tech scattered around. Post-apocalyptic, Ruined, Nature, Tech, Dark future. The subject is ";
		break;
		
	case 35:
		$prompt_before="Digital art in Etching style. Detailed with intricate lines and patterns replicating the etching process. Intricate lines, Detailed, Traditional, Patterns, Structure. The subject is ";
		break;
		
	case 36:
		$prompt_before="Digital art in the Expressionist style, showcasing a scene or subject with heightened emotion and distorted forms. Emotion, Distorted, Subjective, Intense, Vibrant. The subject is ";
		break;
		
	case 37:
		$prompt_before="Digital art inspired by Fauvism, emphasizing bold, wild colors and simple shapes. Wild, Bold Colors, Simplified, Intense, Vibrant. The subject is ";
		break;
		
	case 38:
		$prompt_before="Digital illustration in Flat Design style using clean lines and bold colors. Minimalistic, Bold colors, Clean, Modern, 2D. The subject is ";
		break;
	
	case 39: //
		$prompt_before="A professional, high resolution, color graded, appetizing, commerical quality advertisment, food photography style. The subject is ";
		break;	

	case 40:
		$prompt_before="Digital piece in Fractal Art style illustrating a spiral pattern that repeats infinitely with vibrant colors. Mathematical, Patterns, Infinite, Vibrant, Intricate. The subject is ";
		break;
		
	case 41:
		$prompt_before="Digital art piece in the Futurist style, showcasing dynamic movements, machinery, and the essence of speed. Speed, Dynamic, Modern, Technology, Movement. The subject is ";
		break;

	case 42:
		$prompt_before="Digital art in Glitch Art style disrupted with intentional digital errors and color shifts. Errors, Distortions, Digital, Aesthetic, Imperfect. The subject is ";
		break;

	case 43:
		$prompt_before="Digital art piece capturing the Gothic style, focusing on detailed patterns, pointed structures, and a sense of grandeur. Architecture, Detailed, Pointed, Grand, European. The subject is ";
		break;
		
	case 44:
		$prompt_before="Digital painting using gouache paint with opaque and vibrant colors and transparent layers. Opaque, Vibrant. The subject is ";
		break;
		
	case 45: //
		$prompt_before="Vibrant and highly detailed graphic novel style illustration. The subject is ";
		break;
		
	case 46:
		$prompt_before="Digital art inspired by Greco-Roman traditions, showcasing statues or structures emphasizing proportion and the human form. Proportion, Balance, Statues, Ancient, Human Body. The subject is ";
		break;
		
	case 47: //
		$prompt_before="Finely detailed + expertly drawn + colorful illustration style. The subject is ";
		break;
		
	case 48:
		$prompt_before="Digital art in Impressionism style with loose brushstrokes. Essence, Loose brushstrokes, Light, Mood, Moment. The subject is ";
		break;
	
	case 49: //
		$prompt_before="Loose brushwork, colorful, impressionist painting with light and shade capturing the essence over form. The subject is ";
		break;	

	case 50: //
		$prompt_before="Ultra detailed, crisp, clean, ink line art drawing. The subject is ";
		break;
		
	case 51:
		$prompt_before="Digital painting in Ink Wash style, capturing the spirit and essence of the subject. East Asian, Ink wash, Essence, Spirit, Flowy. The subject is ";
		break;

	case 52:
		$prompt_before="Digital illustration in Isometric Art style. 3D in 2D, Parallel projection, Geometric, Perspective, Angles. The subject is ";
		break;

	case 53:
		$prompt_before="Digital art in the Ukiyo-e style, showcasing a Japanese serenity using woodblock print aesthetics. Woodblock, Japanese, Traditional, Print. The subject is ";
		break;
		
	case 54:
		$prompt_before="Digital animation in Kinetic Typography style where words or shapes move dynamically on screen. Moving text, Narrative, Expressive, Dynamic, Animation. The subject is ";
		break;
		
	case 55:
		$prompt_before="Digital art inspired by Lithography, showcasing detailed designs or scenes using the aesthetic of stone-based printing. Printing, Stone, Detailed, Flat, Design. The subject is ";
		break;
		
	case 56:
		$prompt_before="Digital art in Low Poly style crafted using geometric shapes. 3D, Limited polygons, Geometric, Simple, Modern. The subject is ";
		break;
		
	case 57:
		$prompt_before="Digital art in a macabre style, emphasizing dark and eerie elements, possibly skeletal or decayed forms in a chilling environment. Dark, Death, Grotesque, Eerie, Decay. The subject is ";
		break;
		
	case 58:
		$prompt_before="Digital art piece in the Magic Realism style, blending everyday scenes with unexpected or fantastical elements. Magical, Realistic, Blend, Unexpected, Fantasy. The subject is ";
		break;
	
	case 59:
		$prompt_before="Digital art in the Minimalist style, focusing on simple geometric shapes, limited colors, and a clean composition. Simple, Clean, Geometric, Limited, Essence. The subject is ";
		break;	

	case 60:
		$prompt_before="Digital art reflecting the Modernist style, emphasizing abstract shapes, bold colors, and a departure from traditional forms. Abstract, New, Rejection, Bold, Narrative.  The subject is ";
		break;
		
	case 61:
		$prompt_before="A monogram design that combines two or more letters in an intertwined or connected fashion, showcasing a balanced and symmetrical style. The design should be elegant and versatile, incorporating decorative elements like flourishes and borders, and effectively using negative space to enhance the overall aesthetic of the monogram. Geometric, Elegant, Modern, Art Deco, Sophisticated. The subject is ";
		break;

	case 62:
		$prompt_before="Digital art in Mosaic style where colors and patterns come alive through tiny square tiles. Tiny pieces, Detailed, Patterns, Traditional, Square tiles. The subject is ";
		break;

	case 63:
		$prompt_before="Digital art in Neon Graffiti style on a brick wall with vibrant colors, edgy motifs, and street art elements. Vibrant, Neon colors, Edgy, Street art, Wall. The subject is ";
		break;
		
	case 64:
		$prompt_before="Digital art in Neon Noir style depicting a rain-soaked city street at night illuminated by neon signs and mysterious figures. Neon lights, Dark, Urban, Mystery, Retro-futuristic. The subject is ";
		break;
		
	case 65:
		$prompt_before="Digital art in Origami style, crafted to resemble a 3D folded paper structure. Paper folding, 3D, Crafted, Colorful. The subject is ";
		break;
		
	case 66:
		$prompt_before="Digital art in Papercut style giving a sense of depth with layered elements. Layered, Paper-like, Depth, Movement, Animation. The subject is ";
		break;
		
	case 67:
		$prompt_before="Digital art in Parallax style, where the foreground and background elements move at different paces. Depth, Layers, Movement, Different speeds, 3D illusion. The subject is ";
		break;
		
	case 68:
		$prompt_before="Digital art in a pastel style where the soft hues and delicate strokes capture the essence. Soft hues, Delicate strokes, Picturesque, Traditional. The subject is ";
		break;
	
	case 69: //
		$prompt_before="A monochrome pencil sketch. The subject is ";
		break;	

	case 70: //
		$prompt_before="Fine ultra-detailed realistic + ultra photorealistic + Hasselblad H6D + high definition + 8k + cinematic + color grading + depth of field + photo-realistic + film lighting + rim lighting + intricate + realism + maximalist detail + very realistic. The subject is ";
		break;
		
	case 71:
		$prompt_before="Digital art in the Photorealistic style, showcasing a detailed and lifelike depiction of a subject, resembling a high-resolution photograph. Detailed, Lifelike, Photograph, Real, Precise. The subject is ";
		break;

	case 72:
		$prompt_before="Digital art in Pixel Art style using detailed pixels. Pixelated, Detailed. The subject is ";
		break;

	case 73: //
		$prompt_before="Clay art, claymation, play-doh, craft style. The subject is ";
		break;
		
	case 74:
		$prompt_before="Digital art in Pointillism style constructed using countless colorful dots. Individual dots, Detailed, Technique. The subject is ";
		break;
		
	case 75:
		$prompt_before="Digital art in Polyart style made up of geometric polygons, capturing the essence in a unique manner. Geometric, Polygons, Unique, Modern, Aesthetic. The subject is ";
		break;
		
	case 76:
		$prompt_before="Pop Art Illustration. Vibrant and emphasizing bold colors, high contrast, and iconic pop culture symbols interspersed throughout. Bold colors, High contrast, Iconic, Pop culture, Vibrant. The subject is ";
		break;
		
	case 77:
		$prompt_before="Digital art in the Psychedelic style, emphasizing vibrant colors, swirling patterns, and trippy visuals. Vibrant, Swirling, Trippy, Hallucinogenic, Bright. The subject is ";
		break;
		
	case 78:
		$prompt_before="Digital painting in Baroque/Renaissance style with ornate details. Ornate, Realism, Classicism, Detailed, Humanism. The subject is ";
		break;
	
	case 79: //
		$prompt_before="Vibrant and enticing retail packaging style. commercial, product-focused, eye-catching, professional, highly detailed photography. The subject is ";
		break;	

	case 80:
		$prompt_before="Digital art in Retro Wave style. Neon-lit futuristic cars and a radiant sunset, reminiscent of the 1980s. 80s, Neon lights, Synth vibes, Chrome, Radiant. The subject is ";
		break;
		
	case 81:
		$prompt_before="Digital art piece in the Romantic style, showcasing a dramatic natural landscape or emotional scene, with an emphasis on the beauty of nature. Emotion, Nature, Dramatic, Individualism, Medieval. The subject is ";
		break;

	case 82: //
		$prompt_before="Sci fi style, futuristic, highly detailed, alien, cinematic lighting, offworld. The subject is ";
		break;

	case 83:
		$prompt_before="Digital art in Sci-Fi Fantasy style of a world with floating islands, dragons, and advanced civilizations. Futuristic, Mythical, Advanced tech, Dragons, Civilizations. The subject is ";
		break;
		
	case 84:
		$prompt_before="Digital art in Scratchboard style where details emerge by digitally scratching off the top layer. Scratching, Detailed, Technique, Layer, Emergent. The subject is ";
		break;
		
	case 85:
		$prompt_before="Digital art in Steampunk style. Victorian, Retro-futuristic, Brass, Gears, Steam-powered, Intricate Machinery. The subject is ";
		break;
		
	case 86:
		$prompt_before="Digital art in Stippling style with intricate details formed by countless tiny dots. Tiny dots, Detailed, Technique, Intricate, Majestic. The subject is ";
		break;
		
	case 87: //
		$prompt_before="Street photography, analog film, 35mm film, grainy photograph. The subject is ";
		break;
		
	case 88:
		$prompt_before="Digital art in Surrealism style with floating islands in the sky, oversized flora, and time-warped elements blending together. Dreamlike, Unreal, Digital, Unique, Merged. The subject is ";
		break;
	
	case 89:
		$prompt_before="Digital art in the Symbolist style, emphasizing symbolic elements to convey deeper meanings and emotions. Symbols, Deep, Emotions, Mystical, Meanings. The subject is ";
		break;	

	case 90: //
		$prompt_before="An ultra highly detailed technical illustration. The subject is ";
		break;
		
	case 91: //
		$prompt_before="Tilt-shift photo. highly detailed, vibrant, selective focus, miniature effect, blurred background, perspective control. The subject is ";
		break;

	case 92:
		$prompt_before="Digital art in the Trompe-l'oeil style, showcasing a scene that gives an optical illusion of depth or three-dimensionality. Illusion, Depth, Realistic, Deceptive, 3D. The subject is ";
		break;

	case 93:
		$prompt_before="Digital art in Vaporwave style with pastel sunsets, old computer graphics, and Greek statues, radiating retro vibes. Nostalgia, '80s, '90s, Pastel, Retro. The subject is ";
		break;
		
	case 94:
		$prompt_before="Digital art in Vector style with sharp edges and bold colors. Geometric, Paths, Scalable, Sharp, Clean. The subject is ";
		break;
		
	case 95:
		$prompt_before="Digital art in Voxel Art style constructed using 3D cubes. 3D cubes, Pixel-like, Vibrant, Detailed, Construction. The subject is ";
		break;
		
	case 96:
		$prompt_before="Digital painting in Watercolor style with soft hues blending seamlessly. Soft, Transparent, Water-based, Blending, Delicate. The subject is ";
		break;
		
	case 97: //
		$prompt_before="Watercolor painting. Vibrant, beautiful, painterly, detailed, textural, artistic. The subject is ";
		break;
		
	case 98: //
		$prompt_before="Soft + light + simple low detail watercolor painting for children. The subject is ";
		break;
	
	case 99:
		$prompt_before="Digital art inspired by Woodblock Printing, emphasizing the texture and aesthetic of traditional wood-carved prints. Carving, Ink, Texture, Traditional, Print. The subject is ";
		break;	

	case 100:
		$prompt_before="Digital art piece in the Zen Doodle style, showcasing intricate repetitive patterns and designs in a meditative composition. Patterns, Meditation, Intricate, Relaxation, Design. The subject is ";
		break;

}

$imageprompt=$prompt_before.$imageprompt.$prompt_after;

if ($reviseprompt==0){
	$curl_imageprompt="Use ONLY the prompt inbetween the square brackets as the revised prompt - do NOT revise the prompt futher - Do not create a revised_prompt - Do not add or subtract ANYTHING to the following prompt : [".$imageprompt."]  - This is the final revised prompt - do not change or revise it.";
} else if ($reviseprompt==1){
	$curl_imageprompt=$imageprompt;
}




sendPrompt($curl_imageprompt,$curl_imagesize,$curl_imagetype,$api_key,$userid);

function sendPrompt($curl_imageprompt,$curl_imagesize,$curl_imagetype,$api_key,$userid) {
    
	$modelname = "dall-e-3"; 
    $endpoint = "images/generations";


    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://api.openai.com/v1/' . $endpoint,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_HTTPHEADER => array(
            'Authorization: Bearer ' . $api_key,
            'Content-Type: application/json'
        ),
    ));

    $postFields = json_encode(array(
        "model" => $modelname,
        "n" => 1,
        "quality" => "hd",
		"style" => $curl_imagetype,
		"size" => $curl_imagesize,
		"prompt" => $curl_imageprompt,
		"response_format" => "b64_json"
    ));


    curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields);

    $responseJson = curl_exec($curl);
	
    if ($responseJson === false) {
        echo "API Error: " . curl_error($curl);
    } else {


		$responseArray = json_decode($responseJson, true);
		$base64String = $responseArray['data'][0]['b64_json'];
		$revised = $responseArray['data'][0]['revised_prompt'];
		file_put_contents("TEMPairesponse.txt","RESPONSE: ".$revised);
		$decodedData = base64_decode($base64String);
		
		if (!is_dir("u_img/".$userid)){
			mkdir("u_img/".$userid);
			file_put_contents("u_img/".$userid."/index.php","<?php echo '404'; ?>");
		}		

		$u_filename=$userid.uniqid().".png";
        $fileDestination = 'u_img/'.$userid."/".$u_filename;
		file_put_contents($fileDestination, $decodedData);
		echo $u_filename;
    }


    curl_close($curl);
}



?>
