<?php

class WordProcessor
{

    /**
     * LibreOffice executable
     */
    private string $libreOffice;



    /**
     * Folder where converted PDFs are stored
     */
    private string $outputFolder;



    public function __construct()
    {

        /*
        Windows LibreOffice Path

        Change only if LibreOffice
        is installed elsewhere.
        */

        $this->libreOffice =
            'C:\Program Files\LibreOffice\program\soffice.exe';



        /*
        Output Folder
        */

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



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

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

        }

    }




    /**
     * Convert DOC/DOCX to PDF
     */
    public function convert(string $file): array
    {

        if (!file_exists($file)) {

            return [

                "success" => false,

                "message" => "Source file not found."

            ];

        }



        $extension = strtolower(

            pathinfo(
                $file,
                PATHINFO_EXTENSION
            )

        );



        if (

            $extension != "doc" &&
            $extension != "docx"

        ) {

            return [

                "success" => false,

                "message" => "Invalid Word document."

            ];

        }



        /*
        Expected PDF
        */

        $pdfName =
            pathinfo(
                $file,
                PATHINFO_FILENAME
            ) . ".pdf";



        $pdfPath =
            $this->outputFolder .
            DIRECTORY_SEPARATOR .
            $pdfName;



        /*
        Delete previous copy
        */

        if (file_exists($pdfPath)) {

            unlink($pdfPath);

        }



        /*
        LibreOffice Command
        */

        $command =

            '"' .

            $this->libreOffice .

            '" --headless ' .

            '--convert-to pdf ' .

            '--outdir "' .

            $this->outputFolder .

            '" "' .

            realpath($file) .

            '"';



        exec(

            $command,

            $output,

            $resultCode

        );



        /*
        Verify PDF
        */

        if (

            !file_exists($pdfPath)

        ) {

            return [

                "success" => false,

                "message" => "Conversion failed.",

                "command" => $command,

                "output" => $output,

                "resultCode" => $resultCode

            ];

        }



        return [

            "success" => true,

            "original" => $file,

            "pdf" => $pdfPath,

            "filename" => basename($pdfPath)

        ];

    }

}