<?php
    require_once '../autoload.php';
    require_once 'JWT.php';
    use \Firebase\JWT\JWT;


    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);




    function SaveConvertedFile ( $fileUrl, $localFolder, $localFilename, $doc_id ) 
    {
        $retval = -1;

        $localFilePath = $localFolder .'/'.$localFilename;

        $fileHandle = fopen($localFilePath, 'w');

        if ( $fileHandle === false ) 
        {
            error_log ( "Unable to open local file (".$fileHandle.") !!!" );
            return $retval;
        }

        $ch = curl_init($fileUrl);
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER,  true        );
        curl_setopt ( $ch, CURLOPT_FILE,            $fileHandle );  
        curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION,  true        ); 

        $response = curl_exec($ch);

        if ( curl_errno($ch) ) 
        {
            error_log ( "CURL error : ".curl_error($ch) );
            return $retval;
        }
    
        curl_close($ch);

        fclose($fileHandle);

        if ($response === false)
        {
            $retval = -1;
            return $retval;
        }
        else
        {
            // Update document table
            $pdo = getPDO ();

            $s0 = $pdo->prepare ( "update document set file=:file where id=:doc_id;" );
            $s0->bindParam ( ":file",   $localFilename  );
            $s0->bindParam ( ":doc_id", $doc_id         );

            if ( $s0->execute () )
                $retval = $doc_id;
        }

        return $retval;
    }

    function SendConversionRequest ( $serverUrl, $postData ) 
    {
        error_log ( "SendConversionRequest..." );

        error_log ( " postData url : " .$postData['url'] );

        // Create token
        $jwt_secret = "xImEO#2017025#";
        $payload = $postData; 
        $jwt = JWT::encode($payload, $jwt_secret, 'HS256');


        $ch = curl_init($serverUrl);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json' , 'Accept: application/json',
        'Authorization: Bearer ' . $jwt ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));

        $response = curl_exec($ch);

        curl_close($ch);

        return json_decode($response, true);
    }


    error_log ( "=== OnlyOfficeConvert ===" );

    $result = array (
            "status"    => 'KO',
            "results"   => array ()
    );

    // Get document to convert
    
    $doc_id = $_POST['doc_id'];

    error_log ( " doc_id : " .$doc_id );

    $filename       = "";
    $pdfFilename    = "";
    $destPDFFolder  = "";

    $pdo = getPDO ();

    if ( $pdo )
    {
        $sql = "select sourcefile, folder from document where id = :doc_id";
        
        $s0 = $pdo->prepare ( $sql );
        $s0->bindParam ( ":doc_id", $doc_id );

        if ( $s0->execute () )
        {
            $d0 = $s0->fetchAll ( PDO::FETCH_ASSOC );

            $filename   = $d0[0]['sourcefile'];
            $folder     = $d0[0]['folder'];

            $pdfFilename = str_replace ( ".docx", ".pdf", $filename );

            $destPDFFolder = $GLOBALS["document_storage"] . "/" . $folder;
        }
    }

    $documentServerUrl = $GLOBALS["onlyoffice_server"].'/ConvertService.ashx';

    $inputDocUrl = $GLOBALS["document_storage_url"] . "/" . $folder . "/" . $filename;

    error_log ( " inputDocUrl : " . $inputDocUrl );
    error_log ( " pdfFilename : " . $pdfFilename );

    $extension = pathinfo($filename, PATHINFO_EXTENSION);
    error_log ( " extension : " . $extension );
    
    $uniqueKey = md5($inputDocUrl); // Doit rester identique entre les requêtes

    $postData = [
        "async"         => true,
        "filetype"      => $extension,
        "key"           => $uniqueKey,
        "outputtype"    => "pdf",
        "title"         => "converted.pdf",
        "url"           => $inputDocUrl
    ];

    $maxAttempts = 10;
    $waitSeconds = 2;
    $attempt = 0;

    while ( $attempt < $maxAttempts ) 
    {
        $res = sendConversionRequest($documentServerUrl, $postData);

        if (isset($res['percent'])) 
            error_log ( "Percent : " . $res['percent'] );
        
        if (isset($res['error'])) 
        {
            error_log ( "Erreur : " . $res['error'] );
            break;
        }

        if (!empty($res['endConvert'])) 
        {
            error_log ( "File converted : " . $res['fileUrl'] );

            if ( SaveConvertedFile ( $res['fileUrl'], $destPDFFolder, $pdfFilename, $doc_id ) != -1 )
            {
                $result ['status'] = 'OK';
                array_push ( $result ['results'], $doc_id );
            }

            break;
        }

        error_log ( "Conversion in progress" . ($attempt + 1) . " / " .$maxAttempts. " ..." );
        sleep($waitSeconds);
        $attempt++;
    }

    if ($attempt === $maxAttempts) 
    {
        error_log ( "La conversion n'est pas terminée après $maxAttempts tentatives." );
    }
    else
        error_log ( "Conversion terminée !!!" );

    header('Content-type: application/json');

    echo json_encode ( $result );
?>    