<?php
namespace Modules\API\APIInterne\Document\Controller;

use Skeleton\Controller\Controller;
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\Settings;
use Helpers\Ariane\Ariane;

class OfficeController extends Controller
{

    /**
     * Function to convert RTF files into Docx files
     *
     * @param string $input_file     : file to read
     * @param string $output_file    : file converted
     * @param string $log_file       : file to get for logs
     */
    public function convertRTFToDocAction() : string
    {
        $cheminSource               = $_SESSION['dir_tmp'];

        /********** TEST FILES ************/
        // Tests 1
        $input_rtf_file                     = $cheminSource . 'Contrat_espaces_verts.rtf';
        $output_doc_file                    = $cheminSource . 'Contrat_espaces_verts.docx';
        $output_html_file                   = $cheminSource . 'Contrat_espaces_verts.html';

        // Tests 2
        $test_file_rtf                      = $cheminSource . 'lorem_text_test.rtf';
        $test_rtf_output                    = $cheminSource . 'lorem_text_test.html';
        $test_doc_output                    = $cheminSource . 'lorem_text_test.docx';

        // Tests 3
        $test_file_html                     = $cheminSource . 'test_HTML.html';
        $test_html_output                   = $cheminSource . 'test_HTML.docx';
        /********** TEST FILES END *******/

        // Read & Convert RTF TO HTML
        $rtfFileReader                      = IOFactory::load($input_rtf_file, 'RTF');

        $sections                   = $rtfFileReader->getSections();

        foreach ($sections as $key => $value) {
            $sectionElement         = $value->getElements();

            foreach ($sectionElement as $elementKey => $elementValue) {
                if ($elementValue instanceof \PhpOffice\PhpWord\Element\TextRun) {
                    $secondSectionElement = $elementValue->getElements();

                    foreach ($secondSectionElement as $secondSectionElementKey => $secondSectionElementValue) {
                        if ($secondSectionElementValue instanceof \PhpOffice\PhpWord\Element\Text) {
                            //$test_text =
                            echo $secondSectionElementValue->getText() . '<br/>';
                        }
                    }
                }
            }
        }

        $htmlFileWriter                     = \PhpOffice\PhpWord\IOFactory::createWriter($rtfFileReader, 'HTML');
        $htmlFileWriter->save($output_html_file);

        // Handle manually & rewrite HTML File
        $phpHTMLFileRead                    = htmlentities(file_get_contents($output_html_file));
        $getHTMLEntities                    = html_entity_decode($phpHTMLFileRead);

        $searchStartLastOccurence           = strrpos($getHTMLEntities, '<p');
        $searchEndLastOccurence             = strrpos($getHTMLEntities, "</body>");
        $cleanedHTMLFile                    = substr_replace($getHTMLEntities, '', $searchStartLastOccurence, $searchEndLastOccurence-$searchStartLastOccurence);

        // $phpHTMLFileRead                    = file_put_contents($output_html_file, $cleanedHTMLFile);

        // Read & Convert HTML To Docx :: OK
        // $htmlFileReader                     = IOFactory::load($output_html_file, 'HTML');

        // $docFileWriter                      = \PhpOffice\PhpWord\IOFactory::createWriter($htmlFileReader, 'Word2007');
        // $docFileWriter->save($output_doc_file);
        
        /**
         * BBA Test
         */


        // $rtf = file_get_contents("E:\\OXALYS\\ENV1\\Oxadata\\tmp\\Contrat_espaces_verts.rtf");
        // $document = new \RtfHtmlPhp\Document($rtf);
        // $formatter = new \RtfHtmlPhp\Html\HtmlFormatter();
        // Fichier::createFichierTmp('baba.html',$formatter->Format($document));

        // $data = file_get_contents('E:\\OXALYS\\ENV1\\Oxadata\\tmp\\baba.html');
        // $data = str_replace('<br>','<br />',str_replace('&#1;','',(str_replace("'","\\'",explode('<body>',$data)[0]))));
        // $data = ' '.$data.' ';
 

        // $phpWord = new \PhpOffice\PhpWord\PhpWord();
        // $section = $phpWord->addSection();
        // \PhpOffice\PhpWord\Shared\Html::addHtml($section, utf8_encode($data));
        // header('Content-Type: application/octet-stream');
        // header('Content-Disposition: attachment;filename="test.docx"');
        // $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
        // $objWriter->save('E:\\OXALYS\\ENV1\\Oxadata\\tmp\\baba.docx');
        /**
         * Fin BBA Test
         */
        
        return $this->renderer->render('@API/test', [
            'menuLeft'          => 'GestionFournisseur',
            'menuActive'        => 'Fournisseur',
        ]);
    }

     /**
     * Function to convert Docx files into PDF
     *
     * @param string $input_file     : file to read
     * @param string $output_file    : file converted
     * @param string $log_file       : file to get for logs
     */
    public function convertDocToPDFAction() : string
    {
        $cheminSource = $_SESSION['dir_tmp'];
        
        $input_file = $cheminSource . 'lorem_text_test_doc.docx';
        $output_file = $cheminSource . 'lorem_text_test_doc.pdf';

        $domPdfPath = realpath('/../vendor/dompdf/dompdf');
        \PhpOffice\PhpWord\Settings::setPdfRendererPath($domPdfPath);
        \PhpOffice\PhpWord\Settings::setPdfRendererName('DomPDF');

        $phpWord = IOFactory::load($input_file, 'Word2007');



        $sections = $phpWord->getSections();


        foreach ($sections as $key => $value) {
            $sectionElement = $value->getElements();

            foreach ($sectionElement as $elementKey => $elementValue) {
                if ($elementValue instanceof \PhpOffice\PhpWord\Element\TextRun) {
                    $secondSectionElement = $elementValue->getElements();

                    foreach ($secondSectionElement as $secondSectionElementKey => $secondSectionElementValue) {
                        if ($secondSectionElementValue instanceof \PhpOffice\PhpWord\Element\Text) {
                            //$test_text =
                            echo $secondSectionElementValue->getText() . '<br/>';
                        }
                    }
                }
            }
        }

        // Settings::setPdfRenderer($rendererName, $rendererLibraryPath);

        // $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'PDF');
        // $objWriter->save($output_file);

        return $this->renderer->render('@API/test', [
            'menuLeft'          => 'GestionFournisseur',
            'menuActive'        => 'Fournisseur',
        ]);
    }

     /**
     * Function to convert Xls files into PDF
     *
     * @param string $input_file     : file to read
     * @param string $output_file    : file converted
     * @param string $log_file       : file to get for logs
     */
    public function convertXlsToPDFAction()
    {
        return $_SESSION['dir_tmp'];
    }
}
