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

$lang = $_GET['lang'];
$getFile = str_replace(' ', '+', $_GET['file']);
$fileName = $_SERVER['DOCUMENT_ROOT'] . '/webdav/cloud_library/' . $getFile;
$file = $fileName . '.json';
$needUpload = true;

if (!file_exists($file))
    die();

$query = "SELECT id FROM `" . JMLADATBAZIS . "`.`jml_phocadownload` WHERE filename = ?";
Database::getInstance()->query($query, array('s', 'cloud_library/' . $getFile . '.environment'));
$uploadedFile = Database::getInstance()->fetchNext();

if (!empty($uploadedFile)) {
    $needUpload = false;
    $itemID = $uploadedFile['id'];
}

$json = file_get_contents($file);
$data = json_decode($json);

if ($needUpload) {
    $query = "SELECT * FROM `" . JMLADATBAZIS . "`.`jml_phocadownload_categories` WHERE parent_id = ? AND title = ?";
    Database::getInstance()->query($query, array('is', 41, ucfirst($data->Type)));
    $type = Database::getInstance()->fetchNext();

    $query = "SELECT ordering FROM `" . JMLADATBAZIS . "`.`jml_phocadownload_categories` ORDER BY ordering DESC LIMIT 1";
    Database::getInstance()->query($query);
    $ordering = Database::getInstance()->fetchNext();

    $order = intval($ordering['ordering']);

    $jsonString = '';
    $catArray   = array();

    $param              = new stdClass();
    $param->serial      = $data->Serial;
    $param->Producer    = ucfirst($data->Producer);
    $param->ProductLine = $data->ProductLine;
    $param->Complexity  = $data->Complexity;
    $param->Bounds      = $data->Bounds;
    $param->User        = $data->User;
    $param->Year        = $data->Year;
    $param->private     = $data->Private == 'true';

    $jsonString = json_encode($param, JSON_UNESCAPED_UNICODE);

    if (empty($type)) {
        $alias  = strtolower(str_replace(" ", "-", $data->Type));
        $order  += 1;

        $rootCatID = Database::getInstance()->insert(
            JMLADATBAZIS . '.jml_phocadownload_categories',
            array(
                "title"     => ucfirst($data->Type),
                "parent_id" => 41,
                "alias"     => $alias,
                "ordering"  => $order,
                "access"    => 1,
                "date"      => date('Y-m-d H:i:s'),
                "language"  => "*",
                "published" => 1,
                "section"   => 41
            ),
            'sisiissii'
        );
    } else {
        $rootCatID = $type['id'];
    }

    array_push($catArray, $rootCatID);

    if ($data->SubType != '') {
        $query = "SELECT id FROM `" . JMLADATBAZIS . "`.`jml_phocadownload_categories` WHERE parent_id = ? AND title = ?";
        Database::getInstance()->query($query, array('is', $rootCatID, $data->SubType));
        $subType = Database::getInstance()->fetchNext();

        $subTypeID = $rootCatID;

        if (empty($subType)) {
            $subAlias   = strtolower(str_replace(" ", "-", $data->SubType));
            $order      += 1;

            $rootCatID = Database::getInstance()->insert(
                JMLADATBAZIS . '.jml_phocadownload_categories',
                array(
                    "title"     => $data->SubType,
                    "parent_id" => $subTypeID,
                    "alias"     => $subAlias,
                    "ordering"  => $order,
                    "access"    => 1,
                    "date"      => date('Y-m-d H:i:s'),
                    "language"  => "*",
                    "published" => 1,
                    "section"   => 41
                ),
                'sisiissii'
            );
        } else {
            $rootCatID = $subType['id'];
        }

        array_push($catArray, $rootCatID);
    }

    $query = "SELECT id FROM `" . JMLADATBAZIS . "`.`jml_phocadownload_categories` WHERE parent_id = ? AND title = ?";
    Database::getInstance()->query($query, array('is', $rootCatID, $data->Category));
    $category = Database::getInstance()->fetchNext();

    if (empty($category)) {
        $alias  = strtolower(str_replace(" ", "-", $data->Category));
        $order  += 1;
        $metakey = $data->SubCategory != '' ? $subTypeID : '';

        $catID = Database::getInstance()->insert(
            JMLADATBAZIS . '.jml_phocadownload_categories',
            array(
                "title"     => $data->Category,
                "parent_id" => $rootCatID,
                "alias"     => $alias,
                "ordering"  => $order,
                "access"    => 1,
                "date"      => date('Y-m-d H:i:s'),
                "language"  => "*",
                "published" => 1,
                "section"   => 41,
                "metakey"   => $metakey
            ),
            'sisiissiis'
        );
    } else {
        $catID = $category['id'];
    }

    array_push($catArray, $catID);

    if ($data->SubCategory != '') {
        $query = "SELECT id FROM `" . JMLADATBAZIS . "`.`jml_phocadownload_categories` WHERE parent_id = ? AND title = ?";
        Database::getInstance()->query($query, array('is', $catID, $data->SubCategory));
        $subCategory = Database::getInstance()->fetchNext();

        if (empty($subCategory)) {
            $subAlias   = strtolower(str_replace(" ", "-", $data->SubCategory));
            $order      += 1;

            $metaKey = $data->SubType != '' ? $subTypeID . ';' . $rootCatID : $rootCatID;

            $subCatID = Database::getInstance()->insert(
                JMLADATBAZIS . '.jml_phocadownload_categories',
                array(
                    "title"     => $data->SubCategory,
                    "parent_id" => $catID,
                    "alias"     => $subAlias,
                    "ordering"  => $order,
                    "access"    => 1,
                    "date"      => date('Y-m-d H:i:s'),
                    "language"  => "*",
                    "published" => 1,
                    "section"   => 41,
                    "metakey"   => $metaKey
                ),
                'sisiissiis'
            );
        } else {
            $subCatID = $subCategory['id'];
        }
    } else {
        $subCatID = $catID;
    }

    $query = "SELECT * FROM local_crm.cloud_library lib WHERE lib.serial = ?";
    Database::getInstance()->query($query, array('s', $data->Serial));
    $cloudLibrary = Database::getInstance()->fetchNext();

    if (empty($cloudLibrary)) {
        Database::getInstance()->insert(
            'local_crm.cloud_library',
            array(
                "serial"    => $data->Serial,
                "byte"      => $data->FileSize
            ),
            'si'
        );
    } else {
        $byte = $data->FileSize + intval($cloudLibrary['byte']);
        Database::getInstance()->update(
            'local_crm.cloud_library',
            array(
                'byte' => $byte
            ),
            array('serial' => $data->Serial),
            'is'
        );
    }

    $itemAlias = strtolower(str_replace(" ", "-", $data->Name));
    $catString = '';

    for ($i = 0; $i < count($catArray); $i++) {
        if ($i == (count($catArray) - 1))
            $catString .= $catArray[$i];
        else
            $catString .= $catArray[$i] . ';';
    }
}

$fileArray = glob($fileName . ".*");

$session    = '';
$nUserID    = '';
$needLogin  = '';

if (property_exists($data, 'Token') && $data->Token != '') {
    $nUserID = crm_hardlock::GetUserIdFromToken($data->Token);

    for ($i = 0; $i < count($fileArray); $i++) {
        $extension = pathinfo($fileArray[$i])['extension'];
        $copied = copy($fileArray[$i], $_SERVER['DOCUMENT_ROOT'] . '/public/cloud_library/' . $getFile . '.' . $extension);

        if ($copied) {
            unlink($fileArray[$i]);
            unlink($_SERVER['DOCUMENT_ROOT'] . '/public/cloud_library/' . $getFile . '.json');
        }

        $published = 1;
    }
} else {
    $session    = $data->SessionID;
    $needLogin  = '&token=' . $session;
    $published  = 0;
}

if ($needUpload) {
    $itemID = crm_database::getInstance()->insert(
        JMLADATBAZIS . '.jml_phocadownload',
        array(
            "catid"             => $subCatID,
            "title"             => $data->Name,
            "alias"             => $itemAlias,
            "filename"          => 'cloud_library/' . $getFile . '.environment',
            "mirror1target"     => '_self',
            "mirror2target"     => '_self',
            "date"              => date('Y-m-d H:i:s'),
            "language"          => '*',
            "access"            => 1,
            "published"         => 1,
            "approved"          => 1,
            "directlink"        => 1,
            "link_external"     => '',
            "image_download"    => '/public/cloud_library/' . $getFile . '.png',
            "description"       => $data->Description,
            "author"            => $data->User,
            "license"           => $nUserID,
            "filesize"          => (int)$data->FileSize,
            "params"            => $jsonString,
            "tags_string"       => $catString,
            "published"         => $published,
            "token"             => $session
        )
    );
}

$pageID = $lang == 'hun' ? 729 : 744;
$domain = $lang == 'hun' ? 'www.archline.hu' : 'www.archlinexp.com';

$url = 'https://' . $domain . '/index.php?option=com_phocadownload&view=file&id=' . $itemID . '&Itemid=' . $pageID . $needLogin;

header('Location: ' . $url);
die();
