<?php

//RETRIEVE URL PARAMETERS----------------------------------------------
$url = "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$params = urldecode(base64_decode(parse_url($url, PHP_URL_QUERY)));
parse_str($params, $parameter);
$model_name = $parameter['n'];
$model_id = $parameter['id'];
if(!$model_id){header("Location: editor");}

//RETRIEVE DIRECTORIES FROM CONFIG FILE---------------------------------------------------
include_once('config.php');
include_once('app/server/path.php');

$current_data_location = $json_instance_path.$model_name.'/'.$model_data_file;


//RETRIEVE JSON DATA---------------------------------------------------
$data = file_get_contents($current_data_location);
$json = json_decode($data);
foreach ($json as $item) 
{
    $i=$item->{'id'};
    if($i==$model_id)
    {
        $relative_model_path=$item->{'path'};
        $relative_model_path=str_replace('"', "", urldecode($relative_model_path));        
        $model_data=json_encode($item);
    }
}

//RETRIEVE MODEL FILES -----------------------------------------------
$formats=array("glb","gltf","obj","stl","fbx");
$image_formats = array('apng','avif','gif','jpg','jpeg','png','svg','webp');
$model_file="";
$model_type="";
$model_mtl="";
$model_attribution="";
$files = scandir($models_path.$relative_model_path);
foreach ($files as $file)
{
    if ($file === '.' || $file === '..') continue;
    $file_format=strtolower(pathinfo($file,PATHINFO_EXTENSION));
    $file_name=strtolower(pathinfo($file,PATHINFO_FILENAME));
    if (in_array($file_format, $formats) ) {
        $model_file=$file;
        $model_type=$file_format;
    }
    if ($file_format=="mtl"){
        $mtl_file=$file; 
    }
    if($file_name=="attribution" And ($file_format=="txt"))$model_attribution.=$file.';';
    if($file_name=="attribution" And in_array($file_format, $image_formats))$model_attribution.=$file.';';
}


//OBSFUCATE AND ECHO JAVASCRIPT VAR--------------------------------------
include_once 'app/server/utils/packer.php';
if (!function_exists('packer'))
{
    function packer($js)
    {
        $packer = new Tholu\Packer\Packer($js);
        return $packer->pack();
    }
}
$relative_model_path=base64_encode($relative_model_path);
$model_name=base64_encode($model_name);
$model_file=base64_encode($model_file);

echo "<script type='text/javascript'>";
ob_start();
echo "var sn3d = {
    D: '$model_data',
    P: '$relative_model_path',
    N: '$model_name',
    F: '$model_file',
    T: '$model_type',
    M: '$mtl_file',
    A: '$model_attribution'
}"; 
$script = ob_get_contents();
ob_clean();
echo packer($script);
echo "</script>";

