<?php

if (!class_exists('crm_hardlock')) require_once("common_cadline_libraries/crm_hardlock.class.php");

$file           = $_GET['file']; // guid, .ifc kiterjesztessel
$projectName    = $_GET['project']; // a projekt eredeti neve
$token          = $_GET['token']; // user azonositas
$fileType       = $_GET['fType'];
$projectId      = $_GET['projectid'];
$status         = 1;
$dataType       = 0;
$ext            = pathinfo($file, PATHINFO_EXTENSION);
$entryName      = $_GET['entryname'] . '.' . $ext;
$converterUrl   = '';
$viewerUrl      = 'https://mobileview.archlinexp.com';
$webdavUrl      = 'https://webdav.cadline.hu/';
$directory      = 'mobileviewer';
$path           = '';
$projectUpdate  = false;
$updatedAt      = date('Y-m-d H:i:s');
$authorization  = 'Authorization: al-jHfdBNh458754bnfgjhsdfj834j54bndFjSFsdb348hN98jngUnjngRTbjngjn4x';

if ($token == '' || $projectId == '') {
    die();
}

if ($file == '' || $projectName == '') {
    die();
}

$nUserID = crm_hardlock::GetUserIdFromToken($token);

if (!$nUserID) {
    die();
}

$curl = curl_init($viewerUrl . '/api/getXeokitServer');
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json", $authorization));
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');

$json_response_url = curl_exec($curl);
curl_close($curl);
if ($json_response_url) {
    $entryUrlResponse = json_decode($json_response_url);
    if (!isset($entryUrlResponse->actualserver) || $entryUrlResponse->actualserver == '') {
        // TODO: HIBA
        die();
    }

    $converterUrl = $entryUrlResponse->actualserver;
}

if ($converterUrl == '') {
    // TODO: HIBA
    die();
}

if ($fileType == 'project') {
    $path = $directory . '/' . $file;
    $status = 2;
}

$query = "SELECT * FROM mobileview.projects WHERE id = ?";
Database::getInstance()->query($query, array('s', $projectId));
$project = Database::getInstance()->fetchNext();
if (empty($project)) {
    Database::getInstance()->insert(
        'mobileview.projects',
        array(
            'id'            => $projectId,
            'name'          => $projectName,
            'path'          => $path,
            'created_at'    => $updatedAt,
            'updated_at'    => $updatedAt,
            'nUserID'       => $nUserID,
            'status'        => $status
        ),
        'sssssii'
    );
} else {
    if ($fileType == 'project') {
        $projectUpdate  = true;
        $status         = 2;
    }
}

if ($fileType == 'entry') {
    $entryId = pathinfo($file, PATHINFO_FILENAME);

    $query = "SELECT * FROM mobileview.entries WHERE id = ?";
    Database::getInstance()->query($query, array('s', $entryId));
    $entry = Database::getInstance()->fetchNext();
    if (empty($entry)) {
        $query = "SELECT * FROM mobileview.entry_types WHERE ext LIKE ? LIMIT 1;";
        Database::getInstance()->query($query, array('s', ";%{$ext}%;"));
        $entryType = Database::getInstance()->fetchNext();
        if (!empty($entryType)) {
            $dataType = $entryType['id'];
        }

        Database::getInstance()->insert(
            'mobileview.entries',
            array(
                'id'            => $entryId,
                'project_id'    => $projectId,
                'created_at'    => date('Y-m-d H:i:s'),
                'updated_at'    => date('Y-m-d H:i:s'),
                'data'          => $file,
                'dataType'      => $dataType,
                'name'          => $entryName
            ),
            'sssssis'
        );
    }
}

if ($fileType == 'project') {
    $result = array();
    $result['path'] = $webdavUrl . $directory . '/' . $file;

    $jsonContent = json_encode($result);

    $curl = curl_init($converterUrl . '/convert');
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json", $authorization));
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $jsonContent);

    $json_response = curl_exec($curl);
    curl_close($curl);
    if ($json_response) {
        $response = json_decode($json_response);
        if ($response->return == false) {
            // TODO: HIBA
            die();
        }

        $storeResult = array();
        $storeResult['domain']  = $converterUrl . '/';
        $storeResult['path']    = $response->xktFilePath;
        $storeResult['fileId']  = $projectId;
        $storeResult['file']    = $file;
        $storeResult['userId']  = $nUserID;

        $storeJsonContent = json_encode($storeResult);

        $curl = curl_init($viewerUrl . '/api/project/store');
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json", $authorization));
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
        curl_setopt($curl, CURLOPT_POSTFIELDS, $storeJsonContent);

        $json_store_response = curl_exec($curl);
        curl_close($curl);
        if ($json_store_response) {
            $storeResponse = json_decode($json_store_response);
            if (isset($storeResponse->localPath) && $storeResponse->localPath != '' && $fileType == 'project') {
                $projectUpdate  = true;
                $status         = 3;
                $path           = $storeResponse->localPath;
            }
        }
    }

    if ($projectUpdate) {
        Database::getInstance()->update(
            "mobileview.projects",
            array(
                'path'          => $path,
                'updated_at'    => $updatedAt,
                'status'        => $status
            ),
            array('id' => $projectId),
            'ssis'
        );
    }
}

$entryStoreResult               = array();
$entryStoreResult['file']       = $fileType == 'entry' ? $file : $projectId . '.json';
$entryStoreResult['userId']     = $nUserID;
$entryStoreResult['projectId']  = $projectId;

$entryStoreJsonContent = json_encode($entryStoreResult);

$curl = curl_init($viewerUrl . '/api/entry/store');
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json", $authorization));
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($curl, CURLOPT_POSTFIELDS, $entryStoreJsonContent);

$json_entry_store_response = curl_exec($curl);
curl_close($curl);
if ($json_entry_store_response && $fileType == 'entry') {
    $entryStoreResponse = json_decode($json_entry_store_response);
    if (!isset($entryStoreResponse->message) || $entryStoreResponse->message != 'success') {
        // TODO: HIBA
        die();
    }
}

$previewResult               = array();
$previewResult['file']       = $projectId . '.png';
$previewResult['userId']     = $nUserID;
$previewResult['projectId']  = $projectId;

$previewResultJsonContent = json_encode($previewResult);

$curl = curl_init($viewerUrl . '/api/entry/store');
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type: application/json", $authorization));
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($curl, CURLOPT_POSTFIELDS, $previewResultJsonContent);

$json_preview_store_response = curl_exec($curl);
curl_close($curl);
if ($json_preview_store_response) {
    $previewStoreResponse = json_decode($json_preview_store_response);
    if (!isset($previewStoreResponse->message) || $previewStoreResponse->message != 'success') {
        // TODO: HIBA
        die();
    }
}
