<?php

namespace App\Controllers;

class ImageGenerator extends BaseController
{
    public function index()
    {
        return view('generate_image');
    }

    public function generate()
    {
        $prompt = $this->request->getPost('prompt');

        $apiKey = env('OPENAI_API_KEY');

        $data = [
            "model" => "gpt-image-1",
            "prompt" => $prompt,
            "size" => "1024x1024"
        ];

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/images/generations');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);

        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $apiKey
        ]);

        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

        $response = curl_exec($ch);

        curl_close($ch);

        $result = json_decode($response, true);

        if (!isset($result['data'][0]['url'])) {
            echo "<pre>";
            print_r($result);
            exit;
        }

        $imageUrl = $result['data'][0]['url'];

        $imageContent = file_get_contents($imageUrl);

        $fileName = 'ai_' . time() . '.png';

        $savePath = FCPATH . 'uploads/' . $fileName;

        file_put_contents($savePath, $imageContent);

        return redirect()->to('/uploads/' . $fileName);
    }
}