<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class AiController extends Controller
{
    public function generatePost(Request $request)
    {
        $validated = $request->validate([
            'prompt' => 'required|string|min:3|max:1000',
            'style' => 'nullable|string|in:casual,professional,funny,motivational,informative',
        ]);

        $prompt = $validated['prompt'];
        $style = $validated['style'] ?? 'casual';

        $stylePrefixes = [
            'casual' => 'Write in a casual, friendly tone: ',
            'professional' => 'Write in a professional, business tone: ',
            'funny' => 'Write in a humorous, entertaining tone: ',
            'motivational' => 'Write in an inspiring, motivational tone: ',
            'informative' => 'Write in an educational, informative tone: ',
        ];

        $systemPrompt = $stylePrefixes[$style] . $prompt . "\n\nAdd appropriate emojis, be concise (60-120 words), and avoid offensive content.";

        // Use a configurable provider; default to OpenAI compatible endpoint
        $apiKey = config('services.openai.key') ?? env('OPENAI_API_KEY');
        $baseUrl = config('services.openai.base_url') ?? env('OPENAI_BASE_URL', 'https://api.openai.com');
        $model = config('services.openai.model') ?? env('OPENAI_MODEL', 'gpt-3.5-turbo');

        if (empty($apiKey)) {
            // Fallback simple generator if no key provided
            $fallback = "✨ " . ucfirst($prompt) . " — Let's make today productive and meaningful. Keep pushing forward and share your wins! 💪";
            return response()->json(['status' => 200, 'data' => [ 'content' => $fallback ]]);
        }

        try {
            $resp = Http::withHeaders([
                'Authorization' => 'Bearer ' . $apiKey,
                'Content-Type' => 'application/json',
            ])->post(rtrim($baseUrl, '/') . '/v1/chat/completions', [
                'model' => $model,
                'messages' => [
                    ['role' => 'system', 'content' => 'You are a helpful copywriter for social posts.'],
                    ['role' => 'user', 'content' => $systemPrompt],
                ],
                'temperature' => 0.9,
                'max_tokens' => 180,
            ]);

            if (!$resp->ok()) {
                return response()->json(['status' => 502, 'message' => 'AI provider error'], 502);
            }

            $json = $resp->json();
            $content = $json['choices'][0]['message']['content'] ?? '';
            return response()->json(['status' => 200, 'data' => [ 'content' => $content ]]);
        } catch (\Throwable $e) {
            return response()->json(['status' => 500, 'message' => 'AI generation failed'], 500);
        }
    }

    public function generateImage(Request $request)
    {
        $validated = $request->validate([
            'prompt' => 'required|string|min:3|max:800',
            'style' => 'nullable|string|in:realistic,artistic,cartoon,abstract,vintage',
            'size' => ['nullable','regex:/^\d+x\d+$/'], // e.g., 512x512
        ]);

        $prompt = $validated['prompt'];
        $style = $validated['style'] ?? 'realistic';
        $size = $validated['size'] ?? '1024x1024';

        $stylePrefixes = [
            'realistic' => 'Photorealistic, high-detail depiction: ',
            'artistic' => 'Artistic illustration with rich colors: ',
            'cartoon' => 'Cartoon style, bold lines and flat colors: ',
            'abstract' => 'Abstract composition, geometric shapes and textures: ',
            'vintage' => 'Vintage, film grain, muted tones: ',
        ];

        $fullPrompt = $stylePrefixes[$style] . $prompt;

        $apiKey = config('services.openai.key') ?? env('OPENAI_API_KEY');
        $baseUrl = config('services.openai.base_url') ?? env('OPENAI_BASE_URL', 'https://api.openai.com');
        $model = config('services.openai.image_model') ?? env('OPENAI_IMAGE_MODEL', 'dall-e-3');

        if (empty($apiKey)) {
            // No API configured; return placeholder and let FE use it
            return response()->json(['status' => 200, 'data' => [ 'url' => 'https://picsum.photos/' . $size . '?random=' . rand(1,9999) ]]);
        }

        try {
            $resp = Http::withHeaders([
                'Authorization' => 'Bearer ' . $apiKey,
                'Content-Type' => 'application/json',
            ])->post(rtrim($baseUrl, '/') . '/v1/images/generations', [
                'model' => $model,
                'prompt' => $fullPrompt,
                'size' => $size,
                'n' => 1,
            ]);

            if (!$resp->ok()) {
                return response()->json(['status' => 502, 'message' => 'AI image provider error'], 502);
            }

            $json = $resp->json();
            $data = $json['data'][0] ?? null;
            if (!$data) {
                return response()->json(['status' => 500, 'message' => 'No image produced'], 500);
            }

            $imageBinary = null;
            if (!empty($data['b64_json'])) {
                $imageBinary = base64_decode($data['b64_json']);
            } elseif (!empty($data['url'])) {
                $download = Http::get($data['url']);
                if ($download->ok()) {
                    $imageBinary = $download->body();
                }
            }

            if (!$imageBinary) {
                return response()->json(['status' => 500, 'message' => 'Failed to obtain image data'], 500);
            }

            $filename = 'ai_' . time() . '_' . Str::random(8) . '.png';
            Storage::disk('public')->put('ai_images/'.$filename, $imageBinary);
            $url = asset('storage/ai_images/'.$filename);

            return response()->json(['status' => 200, 'data' => [ 'url' => $url ]]);
        } catch (\Throwable $e) {
            return response()->json(['status' => 500, 'message' => 'AI image generation failed'], 500);
        }
    }
}


