<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use App\Models\Setting;

class ImageBackgroundController extends Controller
{
    public function remove(Request $request)
    {
        $request->validate([
            'image' => 'required|file|image|max:5120',
        ]);

        $apiKey = Setting::where('key', 'removebg_api_key')->value('value') ?? config('services.removebg.key');
        $apiUrl = Setting::where('key', 'removebg_api_url')->value('value') ?? config('services.removebg.url', 'https://api.remove.bg/v1.0/removebg');

        if (!$apiKey) {
            return response()->json([
                'status' => 'error',
                'message' => 'Background removal API key is not configured. Please update AI settings in admin panel.',
            ], 422);
        }

        try {
            $file = $request->file('image');

            $response = Http::withHeaders([
                'X-Api-Key' => $apiKey,
            ])->asMultipart()->post($apiUrl, [
                [
                    'name' => 'image_file',
                    'contents' => fopen($file->getRealPath(), 'r'),
                    'filename' => $file->getClientOriginalName(),
                ],
                [
                    'name' => 'size',
                    'contents' => 'auto',
                ],
                [
                    'name' => 'format',
                    'contents' => 'png',
                ],
            ]);

            if (!$response->successful()) {
                Log::error('Remove.bg API error', [
                    'status' => $response->status(),
                    'body' => $response->body(),
                ]);

                return response()->json([
                    'status' => 'error',
                    'message' => 'Failed to remove background. Please check API configuration.',
                ], 500);
            }

            $binary = $response->body();
            if (!$binary) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'Background removal response was empty.',
                ], 500);
            }

            $originalName = $file->getClientOriginalName();
            $baseName = pathinfo($originalName, PATHINFO_FILENAME);
            $safeName = Str::slug($baseName) . '-nobg.png';

            return response($binary, 200, [
                'Content-Type' => 'image/png',
                'Content-Disposition' => 'inline; filename="' . $safeName . '"',
            ]);
        } catch (\Throwable $e) {
            Log::error('Background removal exception', [
                'message' => $e->getMessage(),
            ]);

            return response()->json([
                'status' => 'error',
                'message' => 'Unexpected error while removing background.',
            ], 500);
        }
    }
}

