<?php

namespace kernel\helpers;

class ImageGD
{
    public \GdImage $img;

    public function __construct(string $resource = '', int $width = 200, int $height = 200)
    {
        if ($resource){
            $this->img = imagecreatefrompng($resource);
        }
        else {
            $this->img = imagecreatetruecolor($width, $height);
        }
        imagesavealpha($this->img, true);
    }

    public function addText(string $font_size, int $degree, int $x, int $y, string $color, string $font, string $text): void
    {
        $rgbArr = $this->hexToRgb($color);
        $color = imagecolorallocate($this->img, $rgbArr[0], $rgbArr[1], $rgbArr[2]);
        imagettftext($this->img, $font_size, $degree, $x, $y, $color, $font, $text);
    }

    public function addImg(\GdImage $gdImage, int $location_x, int $location_y, int $offset_src_x, int $offset_src_y, int $src_width, int $src_height, int $no_transparent): void
    {
        imagecopymerge($this->img, $gdImage, $location_x, $location_y, $offset_src_x, $offset_src_y, $src_width, $src_height, $no_transparent);
    }

    public function getImg()
    {
        return $this->img;
    }

    public function save(string $path): void
    {
        imagepng($this->img, $path);
        imagedestroy($this->img);
    }

    protected function hexToRgb(string $hex)
    {
        return sscanf($hex, "#%02x%02x%02x");
    }

}