<?php

require_once __DIR__ . '/../vendor/autoload.php';


class ImageProcessor
{

    private string $outputFolder;

    public function __construct()
    {

        $this->outputFolder =
            realpath(__DIR__ . '/../storage')
            . DIRECTORY_SEPARATOR .
            'converted';

        if (!is_dir($this->outputFolder)) {

            mkdir(
                $this->outputFolder,
                0777,
                true
            );

        }

    }


    /**
     * Convert Image To PDF
     */
    public function convert(string $image): array
    {

        if (!file_exists($image)) {

            return [

                "success" => false,
                "message" => "Image not found."

            ];

        }


        $extension = strtolower(

            pathinfo(
                $image,
                PATHINFO_EXTENSION
            )

        );


        $allowed = [

            "jpg",
            "jpeg",
            "png"

        ];


        if (!in_array($extension, $allowed)) {

            return [

                "success" => false,
                "message" => "Unsupported image."

            ];

        }


        $pdfName =

            pathinfo(
                $image,
                PATHINFO_FILENAME
            ) . ".pdf";


        $pdfPath =

            $this->outputFolder .
            DIRECTORY_SEPARATOR .
            $pdfName;


        if (file_exists($pdfPath)) {

            unlink($pdfPath);

        }


        $pdf = new TCPDF();

        $pdf->SetCreator("SmartPrint");
        $pdf->SetAuthor("SmartPrint");
        $pdf->SetTitle("Converted Image");

        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);

        $pdf->SetMargins(0,0,0);

        $pdf->AddPage();


        /*
        Image Size
        */

        list($width,$height)=getimagesize($image);


        $pageWidth =
            $pdf->getPageWidth();

        $pageHeight =
            $pdf->getPageHeight();


        $ratio = min(

            $pageWidth/$width,

            $pageHeight/$height

        );


        $newWidth =
            $width*$ratio;

        $newHeight =
            $height*$ratio;


        $x =
            ($pageWidth-$newWidth)/2;

        $y =
            ($pageHeight-$newHeight)/2;


        /*
---------------------------------------
Handle PNG Alpha Channel
---------------------------------------
*/

$imageToUse = $image;

if ($extension === "png") {

    $png = imagecreatefrompng($image);

    imagesavealpha($png, false);

    $background = imagecreatetruecolor(

        imagesx($png),

        imagesy($png)

    );

    $white = imagecolorallocate(

        $background,

        255,

        255,

        255

    );

    imagefill(

        $background,

        0,

        0,

        $white

    );

    imagecopy(

        $background,

        $png,

        0,

        0,

        0,

        0,

        imagesx($png),

        imagesy($png)

    );

    $tempImage =

        sys_get_temp_dir()

        . DIRECTORY_SEPARATOR .

        uniqid("smartprint_")

        . ".jpg";

    imagejpeg(

        $background,

        $tempImage,

        100

    );

    imagedestroy($png);

    imagedestroy($background);

    $imageToUse = $tempImage;

}

$pdf->Image(

    $imageToUse,

    $x,

    $y,

    $newWidth,

    $newHeight

);

if (

    isset($tempImage)

    &&

    file_exists($tempImage)

) {

    unlink($tempImage);

}


        $pdf->Output(

            $pdfPath,

            "F"

        );


        if (!file_exists($pdfPath)) {

            return [

                "success"=>false,

                "message"=>"Conversion failed."

            ];

        }


        return [

            "success"=>true,

            "original"=>$image,

            "pdf"=>$pdfPath,

            "filename"=>basename($pdfPath)

        ];

    }

}