<?php

namespace App\Modifiers;

use Imagick;
use ImagickDraw;
use Illuminate\Support\Facades\Storage;
use App\Models\ToolStats;

class Watermark
{
    public function make($fileName, $text)
    {
        $filePath = Storage::disk('temp')
            ->path($fileName);

        $imagick = new Imagick($filePath);
        $im = new Imagick();
        $draw = new ImagickDraw();

        $width = $imagick->getImageWidth();
        $height = $imagick->getImageHeight();

        $draw->setFont(
            public_path('assets/font/inter/Inter_18pt-SemiBold.ttf')
        );
        $draw->setFillColor('rgba(255,255,255,0.5)');
        $draw->setFontSize($width / 10);
        $draw->setGravity(Imagick::GRAVITY_NORTHWEST);
        $info = $im->queryFontMetrics($draw, $text);
        
        $x = ($width - $info['textWidth']) / 2;
        $y = ($height - $info['textHeight']) / 2;

        $imagick->annotateImage($draw, $x, $y, 0, $text);
        $result = $imagick->writeImage($filePath);
        $imagick->clear();
        $imagick->destroy();
        
        if ($result) {
            $toolStats = new ToolStats();
            $toolStats->processNew('watermark');
            return [
                true,
                $fileName
            ];
        }

        return [
            false,
            __('lang.file_watermark_error')
        ];
    }

}
