<?php
set_time_limit(0);
require '../../vendor/autoload.php';
$GLOBALS["videoExt"] = array('mp4', 'avi');
$GLOBALS["pdfExt"] = array('doc', 'docx', 'ppt', 'pptx', 'pdf');
$isAJAX = false;
$GLOBALS["output"] = "";
$GLOBALS["ajax"] = [];

use NcJoes\OfficeConverter\OfficeConverter;
use Streaming\Representation;

$ffmpeg = Streaming\FFMpeg::create([
    'ffmpeg.binaries' => 'C:\FFmpeg\bin\ffmpeg.exe',
    'ffprobe.binaries' => 'C:\FFmpeg\bin\ffprobe.exe',
    'timeout'          => 3600,
]);

$GLOBALS["ffmpeg"] = $ffmpeg;

$root = '../../assets/API/Universal';
//$root = '../../上傳測試/Revit';
$folder = 'Revit/拖放元件';

if (isset($_POST["APIName"])) {
    $folder = $APIName;
    $root .= ('/'.$_POST['software']);
    $isAJAX = true;
}
FindPath($root, $folder, $ffmpeg);
if (!$isAJAX) {
    echo ($GLOBALS["output"]);
}else{
    echo (implode(",",$GLOBALS["ajax"]));
}


function ConvertVideo($file_path, $ffmpeg)
{

    $r_1080p = (new Representation)->setKiloBitrate(4096)->setResize(1920, 1080);

    $dir_name = pathinfo($file_path, PATHINFO_DIRNAME);
    $file_name = pathinfo($file_path, PATHINFO_FILENAME);
    $ext = pathinfo($file_path, PATHINFO_EXTENSION);
    if (!file_exists("../." . $dir_name . '/' . $file_name . ".m3u8")) {
        $video = $ffmpeg->open("../." . $file_path);
        $video->hls()
            ->x264()
            ->setHlsTime(300)
            ->addRepresentations([$r_1080p])
            ->save("../." . $dir_name . '/' . $file_name . ".m3u8");

        $GLOBALS["output"] .= "<span style='color:red;'>";
        $GLOBALS["output"] .= "   " . $ext . " ==> m3u8";
        $GLOBALS["output"] .= "</span>";
        array_push($GLOBALS["ajax"],$file_name);
    }
}


function FindPath($root, $folder, $ffmpeg)
{
    $rootPath = $root . '/' . $folder;
    $paths = array_diff(scandir($root . '/' . $folder), array('.', '..', 'Thumbs.db'));
    natsort($paths);
    $GLOBALS["output"] .= ("<ul>");
    foreach ($paths as $path) {
        if (str_contains($path, '.')) {
            $GLOBALS["output"] .= ("<li data-jstree='{ " . '"type" : "file"' . " }' >");
            $title = explode(".", $path)[0];
            $file_path = substr($rootPath, 4) . "/" . $path;
            $path = "title:" . $title . "path:" . $file_path . "  dir_id:" . $folder;
            $GLOBALS["output"] .= ($path);

            $ext = pathinfo($file_path, PATHINFO_EXTENSION);
            if (in_array($ext, $GLOBALS["videoExt"])) {
                ConvertVideo($file_path, $ffmpeg);
            } else if (in_array($ext, $GLOBALS["pdfExt"])) {
                //ConvertPdf($file_path);
            }
            $GLOBALS["output"] .= ("</li>");
        } else {
            $GLOBALS["output"] .= ("<li>");
            $GLOBALS["output"] .= ("dir_name: " . $path . "parent:  " . $folder);
            FindPath($rootPath, $path, $ffmpeg);
            $GLOBALS["output"] .= ("</li>");
        }
    }
    $GLOBALS["output"] .= ("</ul>");
}
