<?php
error_reporting(E_ERROR | E_PARSE);

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

if (crm_hardlock::isEmergencyServer($_GET['secondary'])) {
    die();
}

$session        = isset($_GET['session']) ? $_GET['session'] : '';
$product        = isset($_GET['prod']) ? $_GET['prod'] : '';
$version        = isset($_GET['ver']) ? $_GET['ver'] : '';
$authCode       = isset($_GET['authCode']) ? $_GET['authCode'] : '';
$decodedSession = base64_decode($session);
$verID          = crm_hardlock::getVerIDFrom8and9($version);

$auth = new Authenticate();
$auth->setAuthCode($authCode);
$auth->setAuthSession($session);
$auth->auth();

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

$resource = new Resource($ctrID);

$privatekey     = Webform::GetWebformPrivateKey();
$decoded_param  = Webform::decode($privatekey, $decodedSession, $param); // Adat decode-olása
$decoded_param  = "?{$decoded_param}";
$ex             = Webform::get_valueFromStringUrl($decoded_param, "ex");
$trial          = Webform::get_valueFromStringUrl($decoded_param, "trial");
$seatID         = Webform::get_valueFromStringUrl($decoded_param, "seatID");
$specEdition    = Webform::get_valueFromStringUrl($decoded_param, "se");
$custom_login   = Webform::get_valueFromStringUrl($decoded_param, "custom");
$npid           = Webform::get_valueFromStringUrl($decoded_param, "npid");
$isid           = Webform::get_valueFromStringUrl($decoded_param, "isid");
$comp_name      = Webform::get_valueFromStringUrl($decoded_param, "name");
$build          = Webform::get_valueFromStringUrl($decoded_param, "build");
$type           = Webform::get_valueFromStringUrl($decoded_param, "type");
$serial         = Webform::get_valueFromStringUrl($decoded_param, "serial");
$tokenID        = Webform::get_valueFromStringUrl($decoded_param, "tokenid");
$userID         = crm_hardlock::GetUserIdFromToken($tokenID);
$computer       = crm_hardlock::GetComputerInfoByNpid($npid);
$compName       = $computer['custom_name'] != '' ? $computer['custom_name'] : $computer['computer_name'];

if ($compName == '') {
    $compName = $resource->getDlgString(11812);
}

$notAvailables  = array();
$programs       = crm_hardlock::GetAllProgramsFromUser($userID, $product, $verID, $specEdition, $serial);
$programYear    = crm_hardlock::GetLaunchYearFromVer8And9($version);

if (!crm_hardlock::isEmergencyServer($_GET['secondary']) && $custom_login != '') {
    $query = "SELECT * FROM cl_hlusers.custom_login_urls urls WHERE urls.id = ? AND urls.enabled = ? AND process = ?";
    Database::getInstance()->query($query, array('sis', $custom_login, 1, 'login'));
    $urls = Database::getInstance()->fetchNext();

    if (!empty($urls)) {
        $custom_url = base64_encode('https://www.archlinexp.com/maintenance/webform/progress.php');

        $customUser = crm_hardlock::GetCustomUser(abs($userID));

        $data           = new stdClass();
        $data->ver      = (int)$_GET['ver'];
        $data->id       = $param;
        $data->session  = $session;
        $data->url      = $custom_url;
        $data->customID = $customUser['custom_id'];
        $data->se       = strval($specEdition);
        $data->serial   = $serial;
        $dataJson       = json_encode($data);
        $encoded_data   = base64_encode($dataJson);
        $url            = $urls['custom_serial_manager'] . "?param={$encoded_data}";

        header("Location: {$url}");
        exit();
    }
}

$currentLicButton   = $resource->getDlgString(11801);
$licButton          = $resource->getDlgString(11803);
$cantSelectBtn      = $resource->getDlgString(11802);

$query = "SELECT * FROM `" . JMLADATBAZIS . "`.`jml_users` WHERE nUserID = ?";
Database::getInstance()->query($query, array('i', $userID));
$user = Database::getInstance()->fetchNext();

$extUrl = $ex != 'true' ? 'extern::' : '';

$logo       = $ctrID == '36' ? 'https://www.archline.hu/public/img/icons/ARCHLineXP_logo_yellow_gray_web_2.png' : 'https://www.archlinexp.com/maintenance/webform/images/logo_eng.png';
$bgColor    = $ctrID == '36' ? '#e67e22' : '#3d8fff';
$siteUrl    = $ctrID == '36' ? $extUrl . 'https://www.archline.hu/felhasznalo' : $extUrl . 'https://www.archlinexp.com/user';

// type: 0 a general, az 1 pedig selectprogram
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <title>Select Program Dialog</title>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="https://archlinexp.com/iskolak/public/css/bootstrap.min.css" type="text/css" />

    <script src="https://archlinexp.com/iskolak/public/js/jquery.min.js"></script>
    <script src="https://archlinexp.com/iskolak/public/js/bootstrap.min.js"></script>

    <style>
        .disabled {
            cursor: no-drop !important;
        }

        #alLogo {
            margin-bottom: 2%;
        }

        #programDialogDiv {
            margin-top: 1%;
            margin-left: 1%;
        }

        .table-wrap {
            width: 98.5%;
            overflow-y: auto;
            border: 2px solid #646965 !important;
        }

        .customTableHeight {
            height: 369px;
        }

        #trHeader {
            position: sticky;
            top: 0;
            background: #646965;
            color: white;
            z-index: 2;
            padding-top: 10px;
        }

        body {
            width: 100%;
            background-size: cover;
            background-position: center center;
            background-attachment: fixed;
            background-image: url(https://www.archline.hu/images/2022/01/28/archline_dialog_backg_2022_1500_1000px_01.png);
        }

        .currentSerialRow {
            background-color: <?= $bgColor ?> !important;
        }

        #programTable {
            margin-bottom: 0px !important;
        }

        .custom-btn {
            width: 156px !important;
        }

        #prgText {
            font-size: 16px;
            margin-bottom: 10px;
        }

        .errorDiv {
            color: red;
            display: none;
        }

        #noPrograms {
            text-align: center;
        }
    </style>
</head>

<body>
    <div id="programDialogDiv">
        <img id="alLogo" src="<?= $logo ?>">

        <h5 id="userName">Hello, <?= $user['name'] ?></h5>
        <div id="prgText">
            <?= str_replace('$(PROGRAM_VERSION)', $programYear, $resource->getDlgString(11813)) ?>
            <a id="changeLink" href="#" data-toggle="modal" data-target="#computerModal" data-placement="top" title="<?= $resource->getDlgString(11818) ?>"><?= $compName ?></a>
        </div>

        <?php if (!empty($programs)) : ?>
            <div class="table-wrap <?= !empty($programs) && count($programs) > 5 ? 'customTableHeight' : '' ?>">
                <table id="programTable" class="table table-striped table-bordered">
                    <tr id="trHeader">
                        <th><?= $resource->getDlgString(11808) ?></th>
                        <th><?= $resource->getDlgString(11800) ?></th>
                        <th><?= $resource->getDlgString(5171) ?></th>
                        <th>Lan</th>
                        <th><?= $resource->getDlgString(5086) ?></th>
                    </tr>

                    <?php foreach ($programs as $program) : ?>
                        <?php
                        $availabelProgram   = '';
                        $freeLic            = '';
                        $program['dlgInfo'] = '';
                        $currentSerial      = $serial == $program['prPass'];

                        $available = crm_hardlock::isProgramAvailable($serial, $program['prPass'], $program['prFizetve'], $isid, $program['hlLan'], $program['prActCode'], $availabelProgram, $freeLic, $ctrID, $program['isFloating']);

                        if (!$available || $freeLic != '') {
                            $program['dlgInfo'] = crm_hardlock::getInfoForProgramDialog($program['prFizetve'], $availabelProgram, $freeLic, $ctrID);
                        }

                        if (!$available && !$currentSerial) {
                            array_push($notAvailables, $program);
                            continue;
                        }
                        ?>

                        <tr <?= $serial == $program['prPass'] ? 'class="currentSerialRow"' : '' ?>>
                            <td>
                                <?php if (!$currentSerial) : ?>
                                    <form action="progress.php" method="post">
                                        <input type="hidden" name="action" value="selectProgramDialog" />
                                        <input type="hidden" name="session" value="<?= $session ?>" />
                                        <input type="hidden" name="prPass" value="<?= $program['prPass'] ?>" />

                                        <input type="submit" class="btn btn-primary custom-btn" value="<?= $licButton ?>" name="result_ok" />
                                    </form>
                                <?php else : ?>
                                    <button type="button" class="btn btn-secondary disabled custom-btn"><?= $currentLicButton ?></button>
                                <?php endif; ?>
                            </td>
                            <td><?= substr($program['prPass'], 0, 6) ?></td>
                            <td><?= crm_hardlock::getProgramType($program['prPass'], $program['prTypeID'], $ctrID, $program['isFloating']) ?></td>
                            <td><?= crm_hardlock::getLanName($program['hlLan'], $ctrID) ?></td>
                            <td><?= $program['dlgInfo'] ?></td>
                        </tr>
                    <?php endforeach; ?>

                    <?php foreach ($notAvailables as $program) : ?>
                        <tr>
                            <td><button type="button" class="btn btn-secondary disabled custom-btn"><?= $cantSelectBtn ?></button></td>
                            <td><?= substr($program['prPass'], 0, 6) ?></td>
                            <td><?= crm_hardlock::getProgramType($program['prPass'], $program['prTypeID'], $ctrID, $program['isFloating']) ?></td>
                            <td><?= crm_hardlock::getLanName($program['hlLan'], $ctrID) ?></td>
                            <td><?= $program['dlgInfo'] ?></td>
                        </tr>
                    <?php endforeach; ?>

                </table>
            </div>
        <?php else : ?>
            <h1 id="noPrograms"><?= $resource->getDlgString(11820) ?></h1>
        <?php endif; ?>
        <br>

        <p><?= sprintf($resource->getDlgString(11814), $siteUrl) ?></p>

        <div class="modal fade" id="computerModal" tabindex="-1" role="dialog" aria-labelledby="computerModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="computerModalLabel"><?= $resource->getDlgString(11818) ?></h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="<?= $resource->getDlgString(6111) ?>">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <form id="changeComputerNameForm" action="progress.php" method="post">
                        <input type="hidden" name="action" value="changeComputerName">
                        <input type="hidden" id="computerID" name="computerID" value="<?= $computer['id'] ?>">
                        <input type="hidden" id="hiddenCompName" value="<?= $computer['custom_name'] != '' ? $computer['custom_name'] : '' ?>">

                        <div class="modal-body">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label for="computerName"><?= $resource->getDlgString(11493) ?></label>
                                    <input type="text" class="form-control" id="computerName" name="computerName" value="<?= $computer['custom_name'] != '' ? $computer['custom_name'] : '' ?>" placeholder="<?= $resource->getDlgString(11817) ?>" required>
                                    <div class="errorDiv"><?= $resource->getDlgString(11819) ?></div>
                                    <small id="computerNameHelp" class="form-text text-muted"><?= $resource->getDlgString(11816) ?></small>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <input type="submit" name="saveComputerName" class="btn btn-primary" value="<?= $resource->getDlgString(1655) ?>">
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script>
        $(document).ready(function() {
            $('#computerModal').on('shown.bs.modal', function() {
                var num = $('#computerName').val();
                $('#computerName').focus().val('').val(num);
            });

            $('#computerModal').on('hidden.bs.modal', function() {
                $('.errorDiv').hide();
                $('#computerName').val($('#hiddenCompName').val());
            });

            $('#changeComputerNameForm').submit(function() {
                let computerName = $('#computerName').val();
                if (computerName.trim() == '') {
                    $('.errorDiv').show();
                    return false;
                }
            });

            $(function() {
                $('#changeLink').tooltip()
            });
        });
    </script>
</body>

</html>