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

$session        = isset($_GET['session']) ? $_GET['session'] : '';
$authCode       = isset($_GET['authCode']) ? $_GET['authCode'] : '';
$decodedSession = base64_decode($session);
$renderImage    = array();
$methodResponse = array();
$imgPath        = '';

if (!crm_hardlock::isEmergencyServer($_GET['secondary'])) {
    $auth = new Authenticate();
    $auth->setAuthCode($authCode);
    $auth->setAuthSession($session);
    $auth->auth();
}

$ctrID = isset($_GET['cnt']) ? $_GET['cnt'] : '';
$param = isset($_GET['param']) ? $_GET['param'] : '';

if ($param == '') {
    die();
}

$btnClass       = 'custom-btn';
$bodyClass      = 'default-body';
$logo           = 'airender/ARCHLineXP_2025_AI_render_logo_600px.png';
$actual_link    = (empty($_SERVER['HTTPS']) ? 'http' : 'https') . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$ext            = '';
$filter         = '*';
$title          = '*';

if (!crm_hardlock::isEmergencyServer($_GET['secondary']))
    $resource = new Resource($ctrID);

if ($ctrID == 36) {
    $error = CRM_Error::serverDownHun;
} else {
    $error = CRM_Error::serverDownEng;
}

$privatekey     = Webform::GetWebformPrivateKey();
$decoded_param  = Webform::decode($privatekey, $decodedSession, $param); // Adat decode-olása
$decoded_param  = "?{$decoded_param}";
$tokenid        = Webform::get_valueFromStringUrl($decoded_param, "tokenid");
$serial         = Webform::get_valueFromStringUrl($decoded_param, "serial");
$fileName       = Webform::get_valueFromStringUrl($decoded_param, "fileName");
$bBrowsed       = Webform::get_valueFromStringUrl($decoded_param, "bBrowsed");
$build          = (int)$_GET['build'];
$videoAllowed   = $_GET['ver'] == 42 && $build <= 511 ? false : true;

$viewerUrl      = 'https://mobileview.archlinexp.com';
$authorization  = 'Authorization: al-jHfdBNh458754bnfgjhsdfj834j54bndFjSFsdb348hN98jngUnjngRTbjngjn4x';

$curl = curl_init($viewerUrl . '/api/render/methods/' . $ctrID . '/' . $bBrowsed);

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');
curl_setopt($curl, CURLOPT_TIMEOUT, 60);

$json_method_response = curl_exec($curl);

curl_close($curl);

if ($json_method_response) {
    $methodResponse = json_decode($json_method_response);
}

if ($tokenid == '') {
    die();
}

$nUserID = crm_hardlock::GetUserIdFromToken($tokenid);
if ($nUserID < 0) {
    $crmUserId = crm_hardlock::checkJoomlaAccount($serial);
    if (!$crmUserId) {
        echo '<style>
            h1 {
                text-align: center;
                margin-top: 45vh;
                font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
                font-weight: 500;
            }
        </style>';

        echo '<h1>' . $resource->getDlgString('12519') . '</h1>';
        die();
    }

    $nUserID = $crmUserId;
}

$remainingCredits   = crm_hardlock::getRemainingCredits($nUserID);
$userData           = crm_hardlock::getUserData($nUserID);

if (substr($serial, 0, 2) == '99') {
    $query = "SELECT * FROM mobileview.ai_render_credit_history WHERE nUserID = ?;";
    Database::getInstance()->query($query, array('i', $nUserID));
    $res = Database::getInstance()->fetchNext();

    if (empty($res)) {
        $remainingCredits = 0;
    }
}

$promptArray    = array();
$promptUrl      = $viewerUrl . '/aiRender/' . $nUserID . '/prompt.txt';
$promptTxt      = file_get_contents($promptUrl);
if ($promptTxt) {
    $promptArray = explode("\n", $promptTxt);
}

if ($se == 'LT') {
    $btnClass   = 'lt-blue';
    $bodyClass  = 'lt-body';
}

$fileUrl                    = '';
$imageResult                = array();
$imageResult['fileName']    = $fileName;
$imageJsonContent           = json_encode($imageResult);

$curl = curl_init($viewerUrl . '/api/render/getRenderImage');
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, 'POST');
curl_setopt($curl, CURLOPT_POSTFIELDS, $imageJsonContent);

$json_image_response = curl_exec($curl);
curl_close($curl);

if ($json_image_response) {
    $imageResponse = json_decode($json_image_response);
    if (isset($imageResponse->fileUrl) && $imageResponse->fileUrl != '') {
        $fileUrl = $imageResponse->fileUrl;

        if ($bBrowsed == 'true') {
            $imgPath = $imageResponse->fileUrl;
        }
    }
}

if (isset($_GET['render']) && $_GET['render'] != '') {
    $query = "SELECT * FROM mobileview.ai_render WHERE id = ? LIMIT 1;";
    Database::getInstance()->query($query, array('s', $_GET['render']));
    $renderImage = Database::getInstance()->fetchNext();

    $renderData = json_decode($renderImage['render_data']);
    $imgPath    = $renderImage['path'] . '/' . $renderImage['nUserID'] . '/' . $renderImage['id'] . '.' . $renderImage['ext'];

    switch ($renderImage['ext']) {
        case 'mp4':
            $filter = 'MP4 Video|*.mp4';
            $title  = 'Save a Video File Ricsi';
            break;

        default:
            $filter = strtoupper($renderImage['ext']) . ' Image|*.' . $renderImage['ext'];
            $title  = 'Save an Image File';
            break;
    }
}

if (isset($_POST['downloadImg'])) {
    $file_url = $_POST['imgPath'];
    header('Content-Type: application/octet-stream');
    header("Content-Transfer-Encoding: Binary");
    header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
    readfile($file_url);
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI Render Upload</title>

    <link href="/public/DIAMOND_YELLOW.png" rel="shortcut icon" type="image/vnd.microsoft.icon" />
    <link rel="stylesheet" href="public/css/style.css" />
    <link rel="stylesheet" href="public/css/airender.css?ver=2" />
    <link rel="stylesheet" href="../css/bootstrap.min.css" />
</head>

<body class="<?= $bodyClass ?>">
    <div class="row">
        <div class="col-md-6">
            <img src="<?= $logo ?>" style="margin-top: 0% !important; width: 370px;" />
        </div>

        <div class="col-md-6">
            <p id="userData"><?= $userData['name'] ?></p>
        </div>
    </div>

    <div class="container-fluid">
        <?php if (crm_hardlock::isEmergencyServer($_GET['secondary'])) : ?>
            <h1 id="al_error"><?= $error ?></h1>
        <?php else : ?>
            <input type="hidden" id="needSession" value="<?= empty($renderImage) == false ? 'true' : 'false' ?>">
            <input type="hidden" id="bBrowsed" name="bBrowsed" value="<?= $bBrowsed ?>">
            <input type="hidden" id="defaultPromptPlaceholder" name="defaultPromptPlaceholder" value="<?= $resource->getDlgString('12423') ?>">
            <input type="hidden" id="videoPromptPlaceholder" name="videoPromptPlaceholder" value="<?= $resource->getDlgString('12554') ?>">

            <?php if (empty($renderImage) == false): ?>
                <?php foreach ($renderData as $key => $value): ?>
                    <input type="hidden" id="session_<?= $key ?>" value="<?= $value ?>">
                <?php endforeach; ?>
            <?php endif; ?>

            <img src="airender/loading.gif" id="loading_gif">

            <div class="row">
                <div class="col-md-6">
                    <h1><?= $resource->getDlgString('12412') ?></h1>
                </div>

                <div class="col-md-6">
                    <h1 id="remainingCredits"><?= $resource->getDlgString('12463') ?>: <?= $remainingCredits ?></h1>
                </div>
            </div>
            <br>

            <div class="row">
                <div class="col-md-5 scrollable-col">
                    <form id="renderSettingsForm" action="progress.php" method="post">
                        <input type="hidden" name="action" value="aiRender" />
                        <input type="hidden" name="session" value="<?= $session ?>" />
                        <input type="hidden" name="param" value="<?= $param ?>" />
                        <input type="hidden" name="cnt" value="<?= $ctrID ?>">
                        <input type="hidden" name="fileUrl" value="<?= $fileUrl ?>">

                        <div id="al-parameters">
                            <div id="main-parameters">
                                <p id="curType"><?= $resource->getDlgString('6143') ?></p>
                                <div>
                                    <?php foreach ($methodResponse->renderTypes as $renderType): ?>
                                        <?php
                                        if (($renderType->enabled == false) || ($renderType->bBrowsed == true && $bBrowsed == 'false') || ($renderType->value == 'video' && !$videoAllowed)) {
                                            continue;
                                        }
                                        ?>

                                        <label class="checkboxgroup">
                                            <input id="typeRadio_<?= $renderType->value ?>" type="radio" name="type" value="<?= $renderType->value ?>" data-label="<?= $renderType->name ?>" class="renderInput renderTypeChkbox" onchange="changeType(this)" <?= $renderType->id == 1 ? 'checked' : '' ?>>
                                            <img src="airender/icon-<?= $renderType->value ?>-ai.png" class="radio-img">
                                            <label for="typeRadio_<?= $renderType->value ?>"><?= $renderType->name ?></label>
                                        </label>
                                    <?php endforeach ?>
                                </div>

                                <hr>
                                <label for="prompt"><?= $resource->getDlgString('12411') ?>:</label>
                                <textarea name="prompt" id="prompt" class="form-control renderInput" placeholder="<?= $resource->getDlgString('12423') ?>" rows="6"></textarea>

                                <?php if (!empty($promptArray)): ?>
                                    <button id="openPrompt" type="button" class="btn btn-block <?= $btnClass ?>" data-toggle="modal" data-target="#promptModal"><?= $resource->getDlgString('12484') ?></button>
                                <?php endif; ?>
                            </div>

                            <div id="optional-parameters">
                                <hr>

                                <label for="scenario"><?= $resource->getDlgString('1144') ?>:</label>
                                <select name="scenario" id="scenario" class="form-control optional-parameter renderInput" required>
                                    <?php foreach ($methodResponse->renderScenarios as $renderScenario): ?>
                                        <option value="<?= $renderScenario->value ?>"><?= $renderScenario->name ?></option>
                                    <?php endforeach ?>
                                </select>
                                <hr>

                                <label for="imgTypeDiv"><?= $resource->getDlgString('12415') ?>:</label>
                                <div id="imgTypeDiv" class="ui-radio ui-radio-styles">
                                    <?php foreach ($methodResponse->renderImageTypes as $renderImageType): ?>
                                        <label for="imgTypeRadio_r<?= $renderImageType->id ?>">
                                            <input type="radio" id="imgTypeRadio_r<?= $renderImageType->id ?>" name="imgType" class="imgTypeRadio" value="<?= $renderImageType->value ?>" <?= $renderImageType->id == 1 ? 'checked' : '' ?>>
                                            <span class="radio-text radio-plain">
                                                <img src="airender/<?= $renderImageType->value ?>.png"><br><?= $renderImageType->name ?>
                                            </span>
                                        </label>
                                    <?php endforeach ?>
                                </div>
                                <hr>

                                <label for="stylesDiv"><?= $resource->getDlgString('1572') ?>:</label>
                                <div id="stylesDiv" class="ui-radio ui-radio-styles">
                                    <?php foreach ($methodResponse->renderStyles as $renderStyle): ?>
                                        <label for="styleRadio_r<?= $renderStyle->id ?>">
                                            <input type="radio" id="styleRadio_r<?= $renderStyle->id ?>" name="style" class="styleRadio" value="<?= $renderStyle->value ?>" <?= $renderStyle->value == 'cgi' ? 'checked' : '' ?>>
                                            <span class="radio-text radio-plain">
                                                <img src="airender/<?= $renderStyle->value ?>.png"><br><?= $renderStyle->name ?>
                                            </span>
                                        </label>
                                    <?php endforeach ?>
                                </div>
                            </div>

                            <div id="living-room-parameters">
                                <hr>

                                <label for="roomTypeCombo"><?= $resource->getDlgString('3998') ?>:</label>
                                <select name="roomType" id="roomTypeCombo" class="form-control living-room-parameter" size="5">
                                    <?php foreach ($methodResponse->renderRoomTypes as $renderRoomTypes): ?>
                                        <option value="<?= $renderRoomTypes->value ?>" <?= $renderRoomTypes->id == 1 ? 'checked' : '' ?>><?= $renderRoomTypes->name ?></option>
                                    <?php endforeach ?>
                                </select>
                                <hr>

                                <label for="roomStyleCombo"><?= $resource->getDlgString('1739') ?>:</label>
                                <select name="roomStyle" id="roomStyleCombo" class="form-control living-room-parameter" size="5">
                                    <?php foreach ($methodResponse->renderRoomStyles as $renderRoomStyle): ?>
                                        <option value="<?= $renderRoomStyle->value ?>" <?= $renderRoomStyle->id == 1 ? 'checked' : '' ?>><?= $renderRoomStyle->name ?></option>
                                    <?php endforeach ?>
                                </select>
                                <br>
                            </div>

                            <?php if ($bBrowsed == 'true'): ?>
                                <div id="video-parameters">
                                    <hr>

                                    <label for="movementTypeCombo"><?= $resource->getDlgString('1160') ?>:</label>
                                    <select name="movementType" id="movementTypeCombo" class="form-control living-room-parameter" size="5">
                                        <?php foreach ($methodResponse->renderMovementTypes as $renderMovementType): ?>
                                            <option value="<?= $renderMovementType->value ?>" <?= $renderMovementType->id == 1 ? 'checked' : '' ?>><?= $renderMovementType->name ?></option>
                                        <?php endforeach ?>
                                    </select>
                                    <hr>

                                    <label for="directionCombo"><?= $resource->getDlgString('4053') ?>:</label>
                                    <select name="direction" id="directionCombo" class="form-control living-room-parameter" size="4">
                                        <?php foreach ($methodResponse->renderDirections as $renderDirection): ?>
                                            <option value="<?= $renderDirection->value ?>" <?= $renderDirection->id == 1 ? 'checked' : '' ?>><?= $renderDirection->name ?></option>
                                        <?php endforeach ?>
                                    </select>
                                    <br>
                                </div>
                            <?php endif; ?>
                        </div>

                        <div class="divRenderBtn">
                            <?php if ($remainingCredits < 1): ?>
                                <button id="disabled-render-btn" type="button" class="btn btn-lg btn-block <?= $btnClass ?> disabled" disabled><?= $resource->getDlgString('6307') ?></button>
                            <?php else: ?>
                                <input id="render-btn" type="submit" value="<?= $resource->getDlgString('6307') ?>" onclick="onRenderButton(event)" class="btn btn-lg btn-block <?= $btnClass ?>">
                            <?php endif; ?>
                        </div>
                    </form>
                </div>

                <div class="col-md-7">
                    <div class="right-side-div">
                        <?php if ($remainingCredits < 1 && empty($renderImage)): ?>
                            <h1 id="empty_credit"><?= $resource->getDlgString('12482') ?></h1>
                        <?php else: ?>
                            <div id="right-side-info-renderimage" class="<?= $imgPath == '' ? 'hidden' : '' ?>">
                                <?php if ($imgPath != ''): ?>
                                    <img id="renderedImage" src="<?= $imgPath ?>" alt="" srcset="">
                                    <br>

                                    <form action="<?= $actual_link ?>&filter=<?= $filter ?>&title=<?= $title ?>" method="post">
                                        <input type="hidden" name="imgPath" value="<?= $imgPath ?>">

                                        <?php if (!empty($renderImage)): ?>
                                            <div class="row">
                                                <div class="col-md-2"></div>

                                                <div class="col-md-4">
                                                    <?php if (!empty($renderImage) && $renderImage['ext'] == 'mp4'): ?>
                                                        <a id="openVideo" type="button" class="btn custom-btn" href="?OPENAIVIDEO=<?= $imgPath ?>">Open AI Video</a>
                                                    <?php else: ?>
                                                        <a id="copyToClipboard" type="button" class="btn custom-btn" href="?COPYTOCLIPBOARD=<?= $imgPath ?>"><?= $resource->getDlgString('12486') ?></a>
                                                    <?php endif; ?>
                                                </div>

                                                <div class="col-md-4">
                                                    <input id="downloadFile" class="btn custom-btn" type="submit" name="downloadImg" value="<?= $resource->getDlgString('9561') ?>">
                                                </div>

                                                <div class="col-md-2"></div>
                                            </div>
                                        <?php endif; ?>
                                    </form>

                                    <?php if (!empty($renderImage) && $renderImage['ext'] == 'mp4'): ?>
                                        <h1><?= $resource->getDlgString('12557') ?></h1>
                                    <?php endif; ?>
                                <?php endif; ?>
                            </div>
                            <div id="right-side-info-exterior" class="right-side-info <?= $imgPath != '' ? 'hidden' : '' ?>">
                                <h2><?= $resource->getDlgString('6143') ?></h2>
                                <p><?= nl2br($resource->getDlgString('12421')) ?></p>
                                <div>
                                    <video autoplay="true" loop="" muted="" playsinline="" poster="">
                                        <source src="airender/AL_Ai_exterior_render_slider.webm" type="video/webm">
                                        Your browser does not support the video tag.
                                    </video>
                                </div>
                            </div>
                            <div id="right-side-info-interior" class="right-side-info">
                                <h2><?= $resource->getDlgString('6141') ?></h2>
                                <p><?= nl2br($resource->getDlgString('12422')) ?></p>
                                <div>
                                    <video autoplay="true" loop="" muted="" playsinline="" poster="">
                                        <source src="airender/AL_Ai_interior_render_slider.webm" type="video/webm">
                                        Your browser does not support the video tag.
                                    </video>
                                </div>
                            </div>
                            <div id="right-side-info-virtual-staging" class="right-side-info">
                                <h2><?= $resource->getDlgString('2788') ?></h2>
                                <p><?= nl2br($resource->getDlgString('12545')) ?></p>
                                <div>
                                    <video autoplay="true" loop="" muted="" playsinline="" poster="">
                                        <source src="airender/AL_Ai_virtual_stageing_slider.webm" type="video/webm">
                                        Your browser does not support the video tag.
                                    </video>
                                </div>
                            </div>
                            <div id="right-side-info-video" class="right-side-info"></div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <?php if (!empty($promptArray)): ?>
        <div id="promptModal" class="modal fade" role="dialog">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h4 class="modal-title"><?= $resource->getDlgString('12484') ?></h4>
                    </div>
                    <div class="modal-body">
                        <?php for ($i = 0; $i < count($promptArray); $i++): ?>
                            <p class="getPromptText" onclick="getPromptText(this)"><?= $promptArray[$i] ?></p>

                            <?php if ($i != count($promptArray) - 1): ?>
                                <hr>
                            <?php endif; ?>
                        <?php endfor; ?>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    </div>
                </div>

            </div>
        </div>
    <?php endif; ?>

    <script src="https://www.archlinexp.com/media/jui/js/jquery.min.js"></script>
    <script src="/templates/shaper_helix3/js/bootstrap.min.js" type="text/javascript"></script>
    <script>
        window.onload = function() {
            if ($("#needSession").val() == 'true' && $('#session_renderType').length) {
                $('.renderTypeChkbox').each(function() {
                    if ($('#session_renderType').val() == $(this).val()) {
                        r = $("#typeRadio_" + $(this).val())[0];
                        needRightMenu = false;
                    }
                });
            } else {
                var r = $("#typeRadio_exterior")[0];
                var needRightMenu = true;
            }

            changeType(r, true, needRightMenu);

            if ($("#needSession").val() == 'true') {
                populateInputFromSession();
            }
        };

        function populateInputFromSession() {
            if ($('#session_renderType').length) {
                $('.renderTypeChkbox').each(function() {
                    if ($('#session_renderType').val() == $(this).val()) {
                        $('#typeRadio_' + $(this).val()).attr('checked', true);
                    } else {
                        $('#typeRadio_' + $(this).val()).attr('checked', false);
                    }
                });
            }

            if ($('#session_prompt').length && $('#session_prompt').val() != 'Modern') {
                $('#prompt').val($('#session_prompt').val());
            }

            if ($('#session_scenario').length) {
                $('#scenario').val($('#session_scenario').val());
            }

            if ($('#session_imageType').length && $('#session_imageType').val() != '3dmass') {
                let imgTypeId = $(".imgTypeRadio[value=" + $('#session_imageType').val() + "]").attr('id');

                $('#imgTypeRadio_r1').attr('checked', false);
                $('#' + imgTypeId).attr('checked', true);

            }

            if ($('#session_style').length && $('#session_style').val() != 'none') {
                let styleId = $(".styleRadio[value=" + $('#session_style').val() + "]").attr('id');

                $('#styleRadio_r1').attr('checked', false);
                $('#' + styleId).attr('checked', true);
            }

            if ($('#session_roomType').length) {
                $('#roomTypeCombo').val($('#session_roomType').val());
            }

            if ($('#session_movementType').length) {
                $('#movementTypeCombo').val($('#session_movementType').val());
            }

            if ($('#session_direction').length) {
                $('#directionCombo').val($('#session_direction').val());
            }
        }

        function changeType(newType, init = false, needRightMenu) {
            $("#curType").html(newType.getAttribute('data-label'));

            const elementArray = document.getElementsByClassName("optional-parameter");

            $('#prompt').attr('placeholder', $('#defaultPromptPlaceholder').val());

            document.getElementById('optional-parameters').style.display = 'none';
            document.getElementById('living-room-parameters').style.display = 'none';

            if ($('#bBrowsed').val() == 'true') {
                document.getElementById('video-parameters').style.display = 'none';
            }

            switch (newType.value) {
                case 'exterior':
                    document.getElementById('optional-parameters').style.display = 'block';

                    for (let i = 0; i < elementArray.length; i++) {
                        elementArray[i].required = true;
                    }
                    break;

                case 'interior':
                    document.getElementById('living-room-parameters').style.display = 'block';
                    document.getElementById('optional-parameters').style.display = 'block';

                    for (let i = 0; i < elementArray.length; i++) {
                        elementArray[i].required = false;
                    }
                    break;

                case 'virtual-staging':
                    document.getElementById('living-room-parameters').style.display = 'block';
                    break;

                case 'video':
                    document.getElementById('video-parameters').style.display = 'block';

                    $('#prompt').attr('placeholder', $('#videoPromptPlaceholder').val());
                    break;

                default:
                    break;
            }

            if ($("#renderedImage").length == 0 || init == true) {
                changeRightSide(newType.value, needRightMenu);
            }
        }

        function changeRightSide(newPanel, needRightMenu) {
            $('.right-side-info').hide();
            if (needRightMenu || $("#needSession").val() == 'false') {
                $("#right-side-info-" + newPanel).show();
            }
        }

        function onRenderButton() {
            $('.renderInput').each(function() {
                $(this).attr('readonly', true);
                $(this).addClass('disabled');
            });

            $('#render-btn').attr('disabled', true);
            $('#loading_gif').show();
            $("#renderSettingsForm").submit();
        }

        function getPromptText(elem) {
            document.getElementById('prompt').value = elem.innerHTML;
            $('#promptModal').modal('hide');
        }
    </script>
</body>

</html>