
<?php


ini_set('display_errors', 1); 
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
class Image
{
    private const FONT_BOLD = './font/MinionPro-Regular.otf';
    private const FONT_SEMI_BOLD = './font/AlrightSansBlack.ttf';
    private const FONT_REGULAR = './font/MinionPro-Regular.otf';
    private const IMAGE_WIDTH = 854;
    private const IMAGE_HEIGHT = 480;
    private const CLIENT_NAME_LIMIT = 34;
    private const SERVICE_PROPERTIES_LIMIT = 4;

    private $validImageTypes = ['jpg', 'png'];
    private $imageType;
    private $clientName;
    private $clientPhone;
    private $serviceType;
    private $servicePrice;
    private $serviceAddress;
    private $serviceDate;
    private $serviceReference;
    private $serviceProperties;

    public function setImageType(string $imageType): self
    {
        if (!in_array($imageType, $this->validImageTypes)) {
            throw new Exception(sprintf('Invalid image type "%s".', $imageType));
        }

        $this->imageType = $imageType;

        return $this;
    }

    public function setClientName(string $clientName): self
    {
        $clientName = $clientName;
        if (strlen($clientName) > self::CLIENT_NAME_LIMIT) {
            $clientName = substr($clientName, 0, self::CLIENT_NAME_LIMIT) . ' ...';
        }

        $this->clientName = $clientName;

        return $this;
    }

    public function setClientPhone(string $clientPhone): self
    {
        $this->clientPhone = $clientPhone;

        return $this;
    }

    public function setClientType(string $serviceType): self
    {
        $this->serviceType = $serviceType;

        return $this;
    }

    public function setServicePrice(string $servicePrice): self
    {
        $this->servicePrice = $servicePrice;

        return $this;
    }

    public function setServiceAddress(string $serviceAddress): self
    {
        $this->serviceAddress = $serviceAddress;

        return $this;
    }

    public function setServiceDate(string $serviceDate): self
    {
        $this->serviceDate = $serviceDate;

        return $this;
    }

    public function setServiceReference(string $serviceReference): self
    {
        $this->serviceReference = $serviceReference;

        return $this;
    }

    public function setServiceProperties(iterable $serviceProperties): self
    {
        $this->serviceProperties = array_slice(array_filter($serviceProperties), 0, self::SERVICE_PROPERTIES_LIMIT);

        return $this;
    }
    
        
  private function wrapimagettftext($img, $fontSize, $drawFrame, $textColor,$fontType, $text, $lineHeight='',$wordSpacing='',$hAlign=0,$vAlign=0) {

if($wordSpacing===' ' || $wordSpacing==='') {
        $size = imagettfbbox($fontSize, 0, $fontType, ' ');
        $wordSpacing=abs($size[4]-$size[0]);
    }
    $size = imagettfbbox($fontSize, 0, $fontType, 'Zltfgyjp');
    $baseHeight=abs($size[5]-$size[1]);
    $size = imagettfbbox($fontSize, 0, $fontType, 'Zltf');
    $topHeight=abs($size[5]-$size[1]);

    if($lineHeight==='' || $lineHeight==='') {
        $lineHeight=$baseHeight*110/100;
    } else if(is_string($lineHeight) && $lineHeight{strlen($lineHeight)-1}==='%') {
        $lineHeight=floatVal(substr($lineHeight,0,-1));
        $lineHeight=$baseHeight*$lineHeight/100;
    } else {
          
       
    }

    $usableWidth=$drawFrame[2]-$drawFrame[0];
    $usableHeight=$drawFrame[3]-$drawFrame[1];

    $leftX=$drawFrame[0];
    $centerX=$drawFrame[0]+$usableWidth/2;
    $rightX=$drawFrame[0]+$usableWidth;

    $topY=$drawFrame[1];
    $centerY=$drawFrame[1]+$usableHeight/2;
    $bottomY=$drawFrame[1]+$usableHeight;

    $text = explode(" ", $text);

    $line_w=-$wordSpacing;
    $line_h=0;
    $total_w=0;
    $total_h=0;
    $total_lines=0;

    $toWrite=array();
    $pendingLastLine=array();

    for($i=0;$i<count($text);$i++) {
        $size = imagettfbbox($fontSize, 0, $fontType, $text[$i]);

        $width = abs($size[4] - $size[0]);
        $height = abs($size[5] - $size[1]);

        $x = -$size[0]-$width/2;
        $y = $size[1]+$height/2;

        if($line_w+$wordSpacing+$width>$usableWidth) {
            $lastLineW=$line_w;
            $lastLineH=$line_h;

            if($total_w<$lastLineW) $total_w=$lastLineW;
            $total_h+=$lineHeight*1.5;

            foreach($pendingLastLine as $aPendingWord) {

                if($hAlign<0) $tx=$leftX+$aPendingWord['tx'];
                else if($hAlign>0) $tx=$rightX-$lastLineW+$aPendingWord['tx'];
                else if($hAlign==0) $tx=$centerX-$lastLineW/2+$aPendingWord['tx'];

                $toWrite[]=array('line'=>$total_lines,'x'=>$tx,'y'=>$total_h,'txt'=>$aPendingWord['txt']);
            }
            $pendingLastLine=array();

            $total_lines++;
            $line_w=$width;
            $line_h=$height;

            $pendingLastLine[]=array('tx'=>0,'w'=>$width,'h'=>$height,'x'=>$x,'y'=>$y,'txt'=>$text[$i]);
        } else {

            $line_w+=$wordSpacing;
            $pendingLastLine[]=array('tx'=>$line_w,'h'=>$width,'w'=>$height,'x'=>$x,'y'=>$y,'txt'=>$text[$i]);
            $line_w+=$width;
            if($line_h<$height) $line_h=$height;
        }
    }

    $lastLineW=$line_w;
    $lastLineH=$line_h;

    if($total_w<$lastLineW) $total_w=$lastLineW;
    $total_h+=$lineHeight*1.5;

    foreach($pendingLastLine as $aPendingWord) {

        if($hAlign<0) $tx=$leftX+$aPendingWord['tx'];
        else if($hAlign>0) $tx=$rightX-$lastLineW+$aPendingWord['tx'];
        else if($hAlign==0) $tx=$centerX-$lastLineW/2+$aPendingWord['tx'];

        $toWrite[]=array('line'=>$total_lines,'x'=>$tx,'y'=>$total_h,'txt'=>$aPendingWord['txt']);
    }
    $pendingLastLine=array();
    $total_lines++;

    $total_h+=$lineHeight*1.5-$topHeight;

    foreach($toWrite as $aWord) {

        $posx = $aWord['x'];

        if($vAlign<0) $posy=$topY+$aWord['y'];
        else if($vAlign>0) $posy=$bottomY-$total_h+$aWord['y'];
        else if($vAlign==0) $posy=$centerY-$total_h/2+$aWord['y'];

        imagettftext($img, $fontSize, 0, $posx, $posy , $textColor, $fontType, $aWord['txt']);

    }
}

    public function create(): void
    {
        
          //$fontSize = 30;
    $lineHeight=32;
    $wordSpacing=' ';
    $hAlign=0; // -1:left  0:center 1:right
    $vAlign=0; // -1:top  0:middle 1:bottom
      $imgWidth = 1280;
    $imgHeight = 720;
    $drawFrame=array(100,40,$imgWidth-100,$imgHeight-140);
    //$drawFrame=array(190,340,1280-180,720-540);

     $fontType = 'font/Alright-Sans-Extra-Thin.ttf';
        
        // Create image from existing file
        $image = ($this->imageType === 'jpg')
            ? imagecreatefromjpeg('podloga/podloga.jpg')
            : imagecreatefrompng('/podloga/image/background.png');

        // Create text colours
        $white = imagecolorallocate($image, 255, 255, 255);
        $blue = imagecolorallocate($image, 51, 204, 255);
        $black=imagecolorallocate($image, 0, 0, 0);
        

        // Draw top and bottom line
       // imageline($image, 30, 74, 824, 74, $white);
       // imageline($image, 30, 385, 824, 385, $white);

        // Write client name
        //$this->writeText($image, 150, 36, $black, self::FONT_BOLD, 'Ime klijenta Ime klijentaIme klijentaIme klijentaIme klijentaIme');
        $this->wrapimagettftext($image, 36, $drawFrame, $black, $fontType, 'Ime klijenta Ime klijentaIme klijentaIme klijenta Ime klijenta Ime Ime klijenta Ime klijenta Ime klijenta Ime klijenta Ime klijenta', '100%',' ',$hAlign,$vAlign);
        // Write service type and price
        //$text = sprintf('%s - %s', $this->serviceType, $this->servicePrice);
       // $this->writeText($image, 124, 24, $white, self::FONT_SEMI_BOLD, $text);

        // Write service address and date
       // $text = sprintf('%s - Written on %s', $this->serviceAddress, 'test');
        $this->writeText1($image, 565, 20, $black, self::FONT_SEMI_BOLD, 'Ime i prezime autora po sredini');

        // Write service properties
    /*    $y = 214;
        foreach ($this->serviceProperties as $text) {
            $this->writeText($image, $y, 14, $blue, self::FONT_SEMI_BOLD, $text);

            $y = $y + 30;
        } */

        // Write client phone and service reference
      //  $text = sprintf('Phone: %s - Reference: %s', $this->clientPhone, $this->serviceReference);
     //   $this->writeText($image, 358, 14, $white, self::FONT_SEMI_BOLD, $text);

        // Save image
        ($this->imageType === 'jpg')
            ? imagejpeg($image, 'slike/image.jpg')
            : imagepng($image, '/slike/image.png');
    }

    private function writeText($image, int $y, int $fontSize, int $fontColour, string $fontPath, string $text): void
    {
        //$text=wordwrap($text,30,"\n");
        
        //$text= text($text, 'spacing=60', 'align=justify');
        
        //$text2="<div class='fulljustify'>".$text."</div>";
        
        $x = $this->getXcoordinate($image, $fontSize, $fontPath, $text);

        imagettftext($image, $fontSize, 0, $x, $y, $fontColour, $fontPath, $text);
    }
    
        private function writeText1($image, int $y, int $fontSize, int $fontColour, string $fontPath, string $text): void
    {
     
        
        $x = $this->getXcoordinate($image, $fontSize, $fontPath, $text);

        imagettftext($image, $fontSize, 0, $x, $y, $fontColour, $fontPath, $text);
    }
    
    
    


    


    private function getXcoordinate($image, int $fontSize, string $fontPath, string $text): int
    {
        $dimensions = imagettfbbox($fontSize, 0, $fontPath, $text);
        $width = abs($dimensions[4] - $dimensions[0]);

        return round((imagesx($image) - $width) / 2);
    }
}

$image = new Image();
$image
    ->setImageType('jpg')
   // ->setClientName('Inanzzz')
   // ->setClientPhone('012 3456 7890')
  //  ->setClientType('Blogger')
  //  ->setServicePrice('£1,000,000')
  //  ->setServiceAddress('Nice Street / London / England')
  //  ->setServiceDate('18/04/2018')
 //   ->setServiceReference('123ABC')
   /*->setServiceProperties([
        'Keep It Simple, Stupid',
        'Open Source',
        'Multiple Languages',
        '',
        'R&D',
        'Will be ignored',
        '  '
    ])*/
    ->create();
    
    echo "<img src='slike/image.jpg'>";

?>