<?php

namespace Modules\WebPilotAI\Http\Controllers\User;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\JsonResponse;
use Modules\WebPilotAI\Models\AIModel; // If listing specific image models
use App\Models\Setting;
use Illuminate\Support\Facades\Http; // For stock photo API
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator; // Ensure Validator is imported
use Illuminate\Support\Str;

class ImageStudioController extends Controller
{
    /**
     * Display the AI Image Studio page.
     */
    public function index()
    {
        $user = Auth::user();
        $imageStudioFeatureKey = 'webpilotai_ai_image_studio';
        $premiumAccessFeatureKey = 'webpilotai_premium_items_access'; // If premium image models exist

        $canAccessImageStudio = false;
        $canAccessPremiumImageModels = false;

        if ($user->currentSubscription() && $user->currentSubscription()->plan) {
            $planFeatures = $user->currentSubscription()->plan->features ?? [];
            foreach ($planFeatures as $feature) {
                if (isset($feature['key']) && $feature['key'] === $imageStudioFeatureKey) {
                    $canAccessImageStudio = true;
                }
                if (isset($feature['key']) && $feature['key'] === $premiumAccessFeatureKey) {
                    $canAccessPremiumImageModels = true;
                }
            }
        }

        if (!$canAccessImageStudio) {
            return redirect()->route('dashboard') // Or a more appropriate route
                             ->with('error', 'AI Image Studio feature is not available on your current plan.');
        }

        $aiImageModels = [];
        $dalleConfig = null; // Initialize $dalleConfig
        $dalleEnabled = Setting::getValue('webpilotai.enable_dalle_image_generation', false);

        if ($dalleEnabled) {
            $dalleDefaultModel = Setting::getValue('webpilotai.dalle_default_model', 'dall-e-3');
            $aiImageModels[] = (object)[
                'id' => $dalleDefaultModel, // Use the model identifier as ID
                'name' => 'OpenAI ' . str_replace('-', ' ', Str::title($dalleDefaultModel)),
                'provider' => 'OpenAI',
                // 'is_premium' => false // Determine if DALL-E access itself is premium based on your plans
            ];
            $dalleConfig = [
                'default_model' => $dalleDefaultModel,
                'default_size' => Setting::getValue('webpilotai.dalle_default_image_size', '1024x1024'),
                'default_quality' => Setting::getValue('webpilotai.dalle_default_image_quality', 'standard'),
                'default_style' => Setting::getValue('webpilotai.dalle_default_image_style', 'vivid'),
            ];
        }
        // TODO: Add other AI image model providers (e.g., Stability AI) if enabled in settings

        $pexelsEnabled = Setting::getValue('webpilotai.enable_pexels_stock_photos', false);

        return view('webpilotai::user.imagestudio.index', compact('aiImageModels', 'pexelsEnabled', 'dalleEnabled', 'dalleConfig'));
    }

    /**
     * Generate an image using AI (DALL-E).
     */
    public function generateImage(Request $request): JsonResponse
    {
        $user = Auth::user();
        $imageStudioFeatureKey = 'webpilotai_ai_image_studio';

        if (!$user->currentSubscription() || !$user->currentSubscription()->plan->hasFeature($imageStudioFeatureKey)) {
            return response()->json(['error' => 'Access to AI Image Studio denied.'], 403);
        }

        if (!Setting::getValue('webpilotai.enable_dalle_image_generation', false)) {
            return response()->json(['error' => 'DALL-E image generation is not enabled.'], 400);
        }

        // --- Credit System Integration ---
        $imageGenerationCost = 0; // Default to 0 if not found or plan doesn't exist
        if ($user->currentSubscription() && $user->currentSubscription()->plan) {
            $cost = $user->currentSubscription()->plan->getFeatureCreditCost($imageStudioFeatureKey);
            if (!is_null($cost)) {
                $imageGenerationCost = (int) $cost; // Ensure cost is an integer
            } else {
                // If cost is not defined for the feature, log it.
                // Depending on business logic, you might allow free use or return an error.
                Log::warning("Credit cost for feature '{$imageStudioFeatureKey}' is not defined in FeatureCreditCost table. Assuming 0 cost for user {$user->id}.");
            }
        } else {
            // User might not have a subscription, or plan details are missing.
            // Handle as per your business rules (e.g., deny access, assume 0 cost for a base free tier if applicable).
            Log::warning("User {$user->id} does not have an active subscription plan or plan details are missing. Credit cost check for '{$imageStudioFeatureKey}' resulted in 0 cost assumption.");
        }

        // Use the accessor from User model for current credit balance
        $userCreditBalance = $user->current_credit_balance; 

        // Check credits only if the feature has a cost
        if ($imageGenerationCost > 0 && $userCreditBalance < $imageGenerationCost) {
            return response()->json(['error' => "Insufficient credits. You need at least {$imageGenerationCost} credits to generate an image."], 402);
        }

        $validator = Validator::make($request->all(), [
            'prompt' => 'required|string|min:5|max:1000',
            'model' => 'nullable|string|in:dall-e-2,dall-e-3',
            'size' => 'nullable|string',
            'quality' => 'nullable|string|in:standard,hd',
            'style' => 'nullable|string|in:vivid,natural',
        ]);

        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()->first()], 422);
        }

        $validated = $validator->validated();

        $apiKey = Setting::getValue('webpilotai.openai_api_key');
        if (!$apiKey) {
            return response()->json(['error' => "OpenAI API key is not configured."], 400);
        }

        $dalleModel = $validated['model'] ?? Setting::getValue('webpilotai.dalle_default_model', 'dall-e-3');
        $imageSize = $validated['size'] ?? Setting::getValue('webpilotai.dalle_default_image_size', '1024x1024');
        $quality = $validated['quality'] ?? Setting::getValue('webpilotai.dalle_default_image_quality', 'standard');
        $style = $validated['style'] ?? Setting::getValue('webpilotai.dalle_default_image_style', 'vivid');

        $apiParams = [
            'model' => $dalleModel,
            'prompt' => $validated['prompt'],
            'n' => 1,
            'size' => $imageSize,
            'response_format' => 'url',
        ];

        if ($dalleModel === 'dall-e-3') {
            $apiParams['quality'] = $quality;
            $apiParams['style'] = $style;
        }

        if ($dalleModel === 'dall-e-3' && !in_array($imageSize, ['1024x1024', '1792x1024', '1024x1792'])) {
            return response()->json(['error' => "Invalid size '{$imageSize}' for DALL-E 3. Valid sizes: 1024x1024, 1792x1024, 1024x1792."], 422);
        } elseif ($dalleModel === 'dall-e-2' && !in_array($imageSize, ['256x256', '512x512', '1024x1024'])) {
            return response()->json(['error' => "Invalid size '{$imageSize}' for DALL-E 2. Valid sizes: 256x256, 512x512, 1024x1024."], 422);
        }

        try {
            $client = \OpenAI::client($apiKey);
            $response = $client->images()->create($apiParams);

            $imageUrl = $response->data[0]->url;

            // Deduct credits only if there was a cost
            if ($imageGenerationCost > 0) {
                $transactionType = 'spend_feature_webpilotai_ai_image_studio';
                $description = "AI Image Generation (DALL-E): " . Str::limit($validated['prompt'], 50);
                
                if (!$user->deductCredits($imageGenerationCost, $transactionType, $description /*, $generatedImageModelIfYouSaveIt */)) {
                    // This case implies an issue with the deduction logic itself or a race condition if balance was sufficient.
                    Log::error("Failed to deduct credits for user {$user->id} after successful image generation, though balance check passed. Cost: {$imageGenerationCost}");
                    // Consider if you should still return the image or an error indicating credit deduction failure.
                    // For now, the image is returned, but the credit deduction failure is logged.
                }
            }

            // TODO: Optionally save the generated image URL or info to a UserGeneratedImage model

            return response()->json(['success' => true, 'images' => [['url' => $imageUrl, 'prompt' => $validated['prompt']]]]);
        } catch (\Exception $e) {
            Log::error("DALL-E Image Generation Error for user {$user->id}: " . $e->getMessage(), ['params' => $apiParams]);
            return response()->json(['error' => 'Failed to generate image. ' . $e->getMessage()], 500);
        }
    }

    /**
     * Search for stock photos using Pexels API.
     */
    public function searchStockPhotos(Request $request): JsonResponse
    {
        $user = Auth::user();
        $imageStudioFeatureKey = 'webpilotai_ai_image_studio'; // Assuming stock photos are part of this feature

        if (!$user->currentSubscription() || !$user->currentSubscription()->plan->hasFeature($imageStudioFeatureKey)) {
            return response()->json(['error' => 'Access to AI Image Studio (Stock Photos) denied.'], 403);
        }

        if (!Setting::getValue('webpilotai.enable_pexels_stock_photos', false)) {
            return response()->json(['error' => 'Pexels stock photo search is not enabled.'], 400);
        }

        $validator = Validator::make($request->all(), [
            'query' => 'required|string|min:2|max:100',
            'per_page' => 'nullable|integer|min:5|max:80',
            'page' => 'nullable|integer|min:1',
        ]);

        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()->first()], 422);
        }

        $validated = $validator->validated();

        $pexelsApiKey = Setting::getValue('webpilotai.pexels_api_key');
        if (!$pexelsApiKey) {
            return response()->json(['error' => 'Pexels API key is not configured.'], 400);
        }

        try {
            $response = Http::withHeaders([
                'Authorization' => $pexelsApiKey,
            ])->get('https://api.pexels.com/v1/search', [
                'query' => $validated['query'],
                'per_page' => $validated['per_page'] ?? 15,
                'page' => $validated['page'] ?? 1,
            ]);

            if ($response->failed()) {
                Log::error("Pexels API Error for user {$user->id}: " . $response->body(), ['query' => $validated['query']]);
                return response()->json(['error' => 'Failed to fetch stock photos from Pexels. Service might be unavailable or API key invalid.'], $response->status());
            }

            $data = $response->json();
            $images = collect($data['photos'] ?? [])->map(function ($photo) {
                return [
                    'id' => $photo['id'],
                    'url' => $photo['src']['large2x'] ?? $photo['src']['original'], // Prefer large2x, fallback to original
                    'thumbnail_url' => $photo['src']['medium'] ?? $photo['src']['small'],
                    'photographer' => $photo['photographer'],
                    'photographer_url' => $photo['photographer_url'],
                    'alt' => $photo['alt'] ?? Str::limit($validated['query'], 50) . ' stock photo', // Pexels 'alt' can be empty
                ];
            })->all();

            return response()->json(['success' => true, 'images' => $images, 'total_results' => $data['total_results'] ?? 0, 'page' => $data['page'] ?? 1, 'per_page' => $data['per_page'] ?? 15]);

        } catch (\Exception $e) {
            Log::error("Pexels Stock Photo Search Exception for user {$user->id}: " . $e->getMessage(), ['query' => $validated['query']]);
            return response()->json(['error' => 'An unexpected error occurred while searching for stock photos.'], 500);
        }
    }
}
