<?php

function convert_to_pdf($filename) {
    // $filename = basename($filename);
    $ext = pathinfo($filename, PATHINFO_EXTENSION);
    // echo $ext;
    // if ( $ext === 'doc' ) {
    //    exec(  "abiword --to=pdf ".$filename_to_extract  , $py_output, $py_status); // ${uniqid()}
    // }
    // if ( $ext === 'docx' ) {
    if ( $ext !== 'pdf' ) {
       exec(  'cd fi ; doc2pdf  "'.$filename.'"'  , $py_output, $py_status); // ${uniqid()}
    }
    $filename_without_extension = pathinfo($filename, PATHINFO_FILENAME);

    $new_filename = $filename_without_extension . '.pdf';

    return $new_filename;
}

$zip = new ZipArchive();
$zip->open('../fi/documents.zip');

$filename_to_extract = '__08fc462c273763aa678a7dd99c6c55f6.pdf';

if ( isset($_GET['fi']) ) {
    $filename_to_extract = '__'.$_GET['fi'];
}
if ( isset($_POST['fi']) ) {
    $filename_to_extract = '__'.$_POST['fi'];
}
$extract = basename($filename_to_extract);


$file_index = $zip->locateName($extract);
if ($file_index !== false) {
    // Extract file to current directory
    $zip->extractTo('./fi/', $filename_to_extract);
    // echo "File extracted successfully.\n";


    $filename_to_extract = convert_to_pdf($filename_to_extract);


// echo "<object data='https://eyeformeta.com/apps/piller/documents/v/fi/$filename_to_extract#toolbar=1'  type='application/pdf'  width='100%' height='700px'>";
// echo "<embed data='https://eyeformeta.com/apps/piller/documents/v/fi/$filename_to_extract#toolbar=1'  type='application/pdf'  width='100%' height='700px'>";
// echo '<embed src="https://eyeformeta.com/apps/piller/documents/v/fi/'.$filename_to_extract.'#toolbar=1" type="application/pdf" width="100%" height="700px" />';
echo '<iframe src="https://docs.google.com/gview?url=https://eyeformeta.com/apps/piller/documents/v/fi/'.$filename_to_extract.'&embedded=true" style="width:100%; height:700px;" frameborder="0"></iframe>';


// header("Content-type:application/pdf");
// header("Content-Disposition:inline;filename='$filename_to_extract");
// readfile("$filename_to_extract");

} else {
    echo "File not found in zip file.\n";
}

$zip->close();

// unzip -d . documents.zip 011d52114cc9f7d72349cc0478c85bac.docx
// doc2pdf 011d52114cc9f7d72349cc0478c85bac.docx


?>