<?php
include_once("c_setting_update.php");

class c_page_cab_setting_terminal_update_KT extends c_page_cab_setting_update
{
    public $h1='Обновления терминалов КТ' ;

    function block_main()
    {
        $this->page_title() ;?>
        <table class="setting_update">
            <tr>
                <td><?$this->show_upload_form();?></td>
            </tr>
            <tr>
                <td>
                    <?$this->show_terminal_form();?>
                </td>
            </tr>
        </table><?
    }

    function show_upload_form()
    {?>
        <h2>Загрузка обновления</h2><br>
        <form id="upload_form" method="POST" enctype="multipart/form-data" action="/cab/setting/terminal_update/upload/">
            <input id="upload_input" type="file" name="file">
            <input id="upload_submit" type="submit" value="Загрузить">
        </form>
        <div id="progress" class="progress hidden">
            <div id="progress_bar" class="progress_bar"></div>
        </div>

        <? if (isset($_SESSION['upload_success']) && $_SESSION['upload_success']) { ?>
            <? unset($_SESSION['upload_success']); ?>
            <div id="result_exec_cmd">
                <h2>Загрузка обновления</h2>
                Загрузка обновления произведена успешно.<br>
                Для обновления терминалов выберите новую версию и нажмите «Установить»
            </div>
        <? } ?>

        <? if (isset($_SESSION['upload_error'])) { ?>
            <div id="result_exec_cmd">
                <div class="alert"><?=$_SESSION['upload_error']?></div>
            </div>
            <? unset($_SESSION['upload_error']); ?>
        <? } ?>
    <? }

    function show_terminal_form()
    {
        global $member;?>
        <h2>Список терминалов:</h2>
        <?
            $arr_groups=execSQL_row('select pkey,obj_name,clss from obj_site_skd where clss=600');
            $packages = $this->get_update_packages();
        ?>
        <form>
            <input type="hidden" name="filter_dir" value="<?echo _CUR_REPORT_DIR?>">
            <div style="display: inline-block">
                <label class="label">Группа:</label>
                <div>
                    <select style="width: 300px" data-select name="filter[group_id]"><option value="0">Все</option><?
                        if (_sizeof($arr_groups)) foreach($arr_groups as $id=>$name) {?><option value="<?echo $id?>" <?if($this->filter['group_id']==$id) echo 'selected'?>><?echo SKD()->get_full_zone_path($id) ?></option><?}?>
                    </select>
                </div>
            </div>
            <div style="display: inline-block">
                <label class="label">Изменить версию для всех терминалов:</label>
                <div>
                    <select style="width: 250px" data-select name="filter[version]"><option value="-1">Не изменять</option><?
                        foreach($packages as $version => $data) {?><option value="<?=$version?>" <?if($this->filter['version']==$version) echo 'selected'?>><?echo $version?></option><?}?>
                    </select>
                </div>
            </div>
            <div style="display: inline-block">
                <input type="submit" class="button v2" cmd="set_filter" value="Применить" style="position:relative; top: 2px;">
            </div>
        </form>

        <?
            $group_id = $this->filter['group_id'] && $this->filter['group_id'] != '0' ? $this->filter['group_id'] : $member->cur_group_id;
            $parent = SKD()->tree[$group_id]->get_list_child();
            $recs = DEVICE()->get_list_terminals(0,'kt', ' t1.parent in ('.$parent.')') ;
            if (_sizeof($recs) === 0) {
                echo '<div class=alert>В данной рабочей группе терминалы отстутсвуют. Воспользуйтесь конфигуратором системы для добавления терминалов в группу.</div>' ;
                return;
            }
        ?>

        <form>
            <table class="basic fz_small">
                <tr>
                    <th>ID</th>
                    <th>Наименование</th>
                    <th>IP</th>
                    <th>Текущая версия</th>
                    <th>Новая версия</th>
                </tr>
                <? if (_sizeof($recs)) foreach($recs as $rec) {?>
                <tr>
                    <td><?=$rec['id']?></td>
                    <td><?=$rec['obj_name']?></td>
                    <td><?=$rec['ip']?></td>
                    <td class="status"><?=$rec['vers']?></td>
                    <td class="status">
                        <select name="term[<?=$rec['pkey']?>][assigned_version]" data-select style="width: 100px;">
                            <option value="0">Не изменять</option>
                            <? foreach ($packages as $version => $data) {
                                if ($this->filter['version']) {
                                    $rec['assigned_version'] = $this->filter['version'];
                                }
                                if ($rec['assigned_version'] == $version) { ?>
                                    <option value="<?=$version?>" selected><?=$version?></option>
                                <? } else { ?>
                                    <option value="<?=$version?>"><?=$version?></option>
                                <? }
                            } ?>
                        </select>
                    </td>
                </tr>
                <? } ?>
            </table>
            <br>
            <input type="text" class="v2" name="type_term" value="kt" style="display: none;">
            <input type="submit" class="v2" cmd="aspmo_setting/terminal_update" value="Установить">
        </form>

        <script>
            $j(document).ready(function() {
                var form = $j("#upload_form");
                var uploadButton = $j("#upload_submit");
                var uploadInput = $j("#upload_input");
                var progress = $j("#progress");
                var progressBar = $j("#progress_bar");

                uploadInput.on("change", function() {
                    console.log("file selected");
                });

                form.on("submit", function(e) {
                    e && e.preventDefault();
                    if (uploadInput[0].files.length === 0) {
                        console.log("No file selected");
                        return;
                    }

                    form.addClass("hidden");
                    progress.removeClass("hidden");

                    var file = uploadInput[0].files[0];
                    var xhr = new XMLHttpRequest();
                    var data = new FormData();

                    data.append('file', file);

                    xhr.upload.onprogress = function(e) {
                        var percentage = Math.round((e.loaded * 100) / e.total);
                        progressBar.css("width", percentage + "%");
                    };

                    xhr.onload = function() {
                        location.reload();
                    };

                    xhr.onerror = function() {
                        console.log("Upload failed:", this.status);
                    };

                    xhr.open("POST", form[0].action, true);
                    xhr.send(data);
                });
            });
        </script>
    <? }

    function get_update_packages() {
        check_exists_dir('/updates') ;
        $files = scandir(_DIR_TO_ROOT.'/updates/');
        if ($files === false) {
            return [];
        }

        $packages = [];

        foreach ($files as $file) {
            $match = [];
            if (preg_match('/^esmo\-(\d+\.\d+\.\d+([A-Za-z0-9]+)?)\-([A-Za-z0-9]+)?\-?installer$/', $file, $match)) {
                $version = $match[1];
                $arch = isset($match[3]) ? $match[3] : 'x64';
                $path = _DIR_TO_ROOT.'/updates/'.$match[0];
                $url = _PATH_TO_SITE.'/updates/'.$match[0];
                $pkg = isset($packages[$version]) ? $packages[$version] : [];
                $pkg[$arch] = [
                    'path' => $path,
                    'url' => $url
                ];
                $packages[$version] = $pkg;
            }
        }
        return $packages;
    }
}
