<?php

require_once __DIR__ . "/WordProcessor.php";
require_once __DIR__ . "/ImageProcessor.php";
require_once __DIR__ . "/PageCounter.php";

class DocumentProcessor
{

    private WordProcessor $word;
    private ImageProcessor $image;
    private PageCounter $counter;

    public function __construct()
    {

        $this->word = new WordProcessor();

        $this->image = new ImageProcessor();

        $this->counter = new PageCounter();

    }



    /**
     * Process uploaded document
     */
    public function process(array $file): array
    {

        if (!isset($file["file_path"])) {

            return [

                "success" => false,

                "message" => "Invalid document."

            ];

        }


        $path = $file["file_path"];


        $extension = strtolower(

            pathinfo(

                $path,

                PATHINFO_EXTENSION

            )

        );



        switch ($extension) {

            /*
            ---------------------------------------
            PDF
            ---------------------------------------
            */

            case "pdf":

                $pdf = $path;

                break;



            /*
            ---------------------------------------
            DOC / DOCX
            ---------------------------------------
            */

            case "doc":

            case "docx":

                $convert = $this->word->convert($path);

                if (!$convert["success"]) {

                    return $convert;

                }

                $pdf = $convert["pdf"];

                break;



            /*
            ---------------------------------------
            IMAGE
            ---------------------------------------
            */

            case "jpg":

            case "jpeg":

            case "png":

                $convert = $this->image->convert($path);

                if (!$convert["success"]) {

                    return $convert;

                }

                $pdf = $convert["pdf"];

                break;



            default:

                return [

                    "success" => false,

                    "message" => "Unsupported file type."

                ];

        }



        /*
        ---------------------------------------
        Count Pages
        ---------------------------------------
        */

        $pages = $this->counter->count($pdf);

        if (!$pages["success"]) {

            return $pages;

        }



        /*
        ---------------------------------------
        Success
        ---------------------------------------
        */

        return [

            "success" => true,

            "original_name" => $file["original_name"],

            "type" => $extension,

            "pdf" => $pdf,

            "pages" => $pages["pages"]

        ];

    }

}