<?php

namespace App\Services;

use App\Facades\Settings;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class RemoveBg
{
    public function handle($imageFile)
    {
        if (!self::enabled()) {
            return;
        }

        $image = fopen($imageFile->getPathname(), 'r');
        $response = Http::withHeaders([
            'X-API-Key' => Settings::get('remove-bg-api_key'),
        ])->attach('image_file', $image, $imageFile->getClientOriginalName())
            ->post('https://api.remove.bg/v1.0/removebg', [
                'size' => 'auto',
            ]);

        if ($response->successful()) {
            file_put_contents($imageFile->getPathname(), $response->body());
        } else {
            Log::error('Failed to remove background. Error: ' . $response->body());
        }
    }

    public static function enabled(): bool
    {
        if (Settings::get('remove-bg-enabled') && !empty(Settings::get('remove-bg-api_key'))) {
            return true;
        }

        return false;
    }
}
