<?php
include_once("c_setting_member.php");
include_once(_DIR_EXT.'/cryptopro/panel_cert_info.php');
class c_page_cab_setting_member_sert extends c_page_cab_setting_member
{

    public $h1 = 'Настройки ЭЦП сотрудника';
    public $tabs = ['cert_info'=>['title'=>'Выбранный ЭЦП','method'=>'panel_cert_info','default'=>1],
                    'select_cert'=>['title'=>'Выбор ЭЦП сотрудника','method'=>'panel_select_user_certificate'],
                    'emu_mode'=>['title'=>'Режим эмуляции ЭЦП','method'=>'panel_emulate'],
                    'mhd'=>['title'=>'МЧД','method'=>'panel_mhd'],
                   ];

    var $use_cryptopro=1 ;
	  public $show_panel_cryptopro_status=1;

    function block_main()
    {
        $this->page_title();
        $this->panel_ecp_info() ;
        $this->panel_tabs() ;
        //ACCOUNTS()->member_save($this->rec_member['pkey'],['ext_info'=>['mhd'=>'']]) ;
    }

    // сводная инфа по ЭЦП
    function panel_ecp_info()
    {
        ?><table class="basic fz_small full fixed" style="margin-bottom:20px;">
            <tr>
                <th>ЭЦП</th>
                <th>МЧД</th>
                <th>Режим эмуляции</th>
            </tr>
            <tr>
                <td><?if (_sizeof($this->rec_member['certificate'])) echo '<i class="fa fa-check-circle size18 green" aria-hidden="true"></i>'?></td>
                <td><?if ($this->rec_member['_ext_info']['mhd']) echo '<i class="fa fa-check-circle size18 green" aria-hidden="true"></i>'?></td>
                <td><?if ($this->rec_member['evulate_ECP']) echo '<i class="fa fa-check-circle size18 green" aria-hidden="true"></i>'?></td>
            </tr>
          </table>
        <?
    }

    function panel_cert_info()
    {
        ?>
        <div class="container_setting_block" id="container_setting_block_1" style="display: block;">
            <div class="setting_title_cnt"><h2>Выбранный ЭЦП</h2></div>
            <div class="settings_padding">
                <?
                if ($this->rec_member['evulate_ECP']) $this->text_banner('Включен режим эмуляции ЭЦП');
                panel_cert_info($this->rec_member['certificate']);
                ?>
            </div>
        </div>
        <?
    }


    function text_banner($text)
    {
        echo '<div class="green" style="background: #f6100d3b !important;padding: 7px 15px;font-size: 11px;font-weight: 600;color: #e10808;">'.$text.'</div>';
    }

  function panel_select_user_certificate()
	{
        ?><div class="container_setting_block" id="container_setting_block_2" style="display: block;">
						<div class="setting_title_cnt"><h2>Выбор ЭЦП сотрудника</h2></div>
						<div class="settings_padding" style="padding-bottom: 10px;"><? if ($this->rec_member['evulate_ECP'] )$this->text_banner('Включен режим эмуляции ЭЦП'); ?></div>
						<div class="edge">
								<div id="csp_msg" style="text-align:left;">
										<p><span class="dot red" id="ExtensionEnabledImg"></span><span class="text-test-info" id="ExtensionEnabledTxt">Расширение не загружено</span><span id="ExtensionSolution"></span></p>
										<p><span class="dot" id="PluginEnabledImg"></span><span class="text-test-info" id="PluginEnabledTxt">Плагин: ожидание загрузки расширения</span><span id="PluginSolution"></span></p>
										<p><span class="dot" id="CspEnabledImg"></span><span class="text-test-info" id="CspEnabledTxt">КриптоПро CSP: ожидание загрузки плагина</span><span id="CspSolution"></span></p>
										<p><span class="dot" id="ObjectsLoadedImg"></span><span class="text-test-info" id="ObjectsLoadedTxt">Объекты плагина: ожидание загрузки провайдера</span><span id="ObjectsSolution"></span></p>
										<div class="edge"></div>
								</div>
								<div id="boxdiv" style="display:none"><span id="errorarea">У вас отсутствуют личные сертификаты.</span></div>
						</div>
						<div style="margin: 15px 15px;">
								<div id="panel_select_sert" class="select_cert"><select size="4" name="CertListBox" id="CertListBox" style="height: fit-content !important;margin: 0px 0 5px 0;"></select></div>
								<button id="apply_sert" style="float: inherit;" class="button select_cert" disabled="disabled">Выбрать сертификат</button>
						</div>
						<div id="cert_info" class="edge" name="CertInfo" style="display:none;margin-bottom: 15px;padding: 10px 0px;background: #f3f3f3;border-radius: 8px;margin-bottom: 45px;">
								<h4>Информация о выбранном сертификате</h4>
								<p class="info_field" id="subject"></p>
								<p class="info_field" id="issuer"></p>
								<p class="info_field" id="from"></p>
								<p class="info_field" id="till"></p>
								<p class="info_field" id="provname"></p>
								<p class="info_field" id="privateKeyLink"></p>
								<p class="info_field" id="algorithm"></p>
								<p class="info_field" id="status"></p>
								<p class="info_field" id="location"></p>
						</div>
						<div class="plugin_info">
								<div id="ExtVersionTxt" lang="ru"></div>
								<div id="ExtStoreTxt" lang="ru"></div>
								<div id="PlugInVersionTxt" lang="ru"></div>
								<div id="CSPVersionTxt" lang="ru"></div>
								<div id="CSPNameTxt" lang="ru"></div>
								<div id="Platform"></div>
								<div id="UserAgent"></div>
						</div>
				</div>
        <script>
            function get_info_select_sert(data)
            {
                console.log(data);
                document.getElementById('apply_sert').setAttribute('data-selecthash', data['hash']);
                $j('#apply_sert').removeAttr('disabled');
            }
            function list_box_size()
            {
                let select = document.getElementById('CertListBox');
                if (select.length > 0) {
                    select.size = select.length; // Устанавливаем высоту по количеству сертификатов
                }
                setTimeout(() => {list_box_size()}, 100);
            }
						$j(document).ready(function() {
						    list_box_size();
						    // Загрузка списка сертификатов после инициализации CryptoPro
						    $j('body').on('cadesplugin_cp_versions', function(event, cp_params) {
						        console.log('panel_select_user_certificate: cadesplugin_cp_versions');
						        FillCertList_Async('CertListBox');
						    });
						});
            $j('button#apply_sert').click(function() {
                // отправляем по ajax информацию по выбранному сертификат для сохранения в профиле пользователя
                // далее страница будет перезагружена
                let hash = document.getElementById('apply_sert').getAttribute('data-selecthash');
                send_ajax_request({cmd:'cryptopro/save_sert_to_account_prepare'});
                ESMO_save_cur_certificate_params(hash,{cmd:'cryptopro/save_sert_to_account',account_id:<?echo $this->rec_member['pkey']?>});
            });
        </script>
        <?
    }




    function panel_emulate(){
        // Фиксим баг с Эмуляцией сертификата
        //update_site_setting('LS_evulate_ECP', $this->rec_member['evulate_ECP']);

        ?>
        <form id="sky-form" enctype="multipart/form-data">
            <div class="setting_title_cnt"><h2>Режим эмуляции ЭЦП</h2></div>
            <?
            if ($this->rec_member['evulate_ECP'] and !($this->rec_member['certificate']['SerialNumber'] and $this->rec_member['certificate']['Thumbprint'] and $this->rec_member['certificate']['SubjectName'] and $this->rec_member['certificate']['ValidFromDate'])) {

                $cert=$this->rec_member['certificate'] ;
                if (!$this->rec_member['certificate']['SerialNumber']) $cert['SerialNumber']=md5(rand(1,100));
                if (!$this->rec_member['certificate']['Thumbprint']) $cert['Thumbprint']=md5(rand(1,100));
                if (!$this->rec_member['certificate']['IssuerName'])   $cert['IssuerName']='Эмуляция ЭЦП';
                if (!$this->rec_member['certificate']['SubjectName'])  $cert['SubjectName']=$this->rec_member['obj_name'];
                $now=getdate() ;
                if (!$this->rec_member['certificate']['ValidFromDate'])   $cert['ValidFromDate']=date('d.m.Y H:i:s');
                $t=mktime($now['hours'],$now['minutes'],$now['seconds'],$now['mon'],$now['mday'],$now['year']+1);
                if (!$this->rec_member['certificate']['ValidToDate'])   $cert['ValidToDate']=date('d.m.Y H:i:s',$t);
                ACCOUNTS()->account_save($this->rec_member['pkey'],array('ext_info'=>array('certificate'=>$cert))) ;
                if ($this->rec_member['pkey']==MEMBER()->id) ACCOUNTS()->update_member_info(MEMBER()) ;
                $this->rec_member=ACCOUNTS()->get_member_by_id($this->rec_member['pkey'])  ;
            }
            ?>
            <div class="settings_padding">
                <p style="font-size: 12px !important;color: #01a2a2 !important;font-weight: 600;margin: 0px;float: left;">Режим эмуляции ЭЦП:</p>
                <input type="hidden" name="member_edit[evulate_ECP]" value=0>
                <input type="checkbox" name="member_edit[evulate_ECP]" style="margin: 5px 0px 0px 10px;" value=1 <?if ($this->rec_member['evulate_ECP']) echo 'checked'?>>
            </div>
            <?
            if ($this->rec_member['evulate_ECP'])
            {
                echo '<div class="search_block">';
                $this->filter_section_input_text('member_edit[ext_info][certificate][SerialNumber]','Серийный номер (SerialNumber)',12, ['value' => $this->rec_member['certificate']['SerialNumber'], 'placeholder'=> 'Серийный номер (SerialNumber)']);
                echo '</div>';
                echo '<div class="search_block">';
                $this->filter_section_input_text('member_edit[ext_info][certificate][Thumbprint]','Отпечаток (Thumbprint)',12, ['value' => $this->rec_member['certificate']['Thumbprint'], 'placeholder'=> 'Отпечаток (Thumbprint)']);
                echo '</div>';
                echo '<div class="search_block">';
                $this->filter_section_input_text('member_edit[ext_info][certificate][IssuerName]','Имя эмитента (IssuerName)',12, ['value' => $this->rec_member['certificate']['IssuerName'], 'placeholder'=> 'Имя эмитента (IssuerName)']);
                echo '</div>';
                echo '<div class="search_block">';
                $this->filter_section_input_text('member_edit[ext_info][certificate][SubjectName]','Имя субъекта (SubjectName)',12, ['value' => $this->rec_member['certificate']['SubjectName'], 'placeholder'=> 'Имя субъекта (SubjectName)']);
                echo '</div>';
                echo '<div class="search_block">';
                $this->filter_section_input_text('member_edit[ext_info][certificate][ValidFromDate]','Действителен с даты (ValidFromDate)',12, ['value' => $this->rec_member['certificate']['ValidFromDate'], 'placeholder'=> 'Действителен с даты (ValidFromDate)']);
                echo '</div>';
                echo '<div class="search_block">';
                $this->filter_section_input_text('member_edit[ext_info][certificate][ValidToDate]','Действителен до даты (ValidToDate)',12, ['value' => $this->rec_member['certificate']['ValidToDate'], 'placeholder'=> 'Действителен до даты (ValidToDate)']);
                echo '</div>';
            }
            ?>
            <input type="submit" class=v1 cmd="save_member" value="Сохранить" style="margin-bottom: 17px;margin-left: 16px;" validate="form">
        </form>
        <?
    }




    function CMD_save_member()
    {
        //damp_array($_POST['member_edit']);
        $res = ACCOUNTS()->member_save($this->rec_member['pkey'],$_POST['member_edit']);
        if (_sizeof($_FILES))
        {
            // загрузка сертификата
            $recs_files = conver_FILES_to_recs($_FILES['upload_CRT']) ; // damp_array($recs_files);
            if (_sizeof($recs_files[0]))
            {
                if ($recs_files[0]['type']=='application/x-x509-ca-cert'){
                    ?><h2>Загружаем сертификат из файла "<?echo $recs_files[0]['name']?>"</h2><?
                    include_once(_DIR_TO_ENGINE.'/admin/i_admin_system.php') ;
                    execSQL_update('delete from obj_site_account_files where parent='.$this->rec_member['pkey'].' and obj_name="root_sertificat"');
                    obj_upload_file($this->rec_member['_reffer'], $recs_files[0], array('view_upload'=>1, 'new_obj_rec'=>array('obj_name'=>'root_sertificat')));
                    //damp_array($res_upload) ;
                    $res_upload = array('type'=>'success', 'no_default_panel'=>1);
                    $res = 'ok';
                }else $res_upload = array('type'=>'error', 'code'=>'failed_type', 'text'=>'Выбранный Вами файл не является сертификатом');
            }
            // else $res_upload=array('type'=>'error','code'=>'not_uploaded_file','text'=>'Не был выбран файл');
            if ($res_upload['type'] == 'error') echo '<div class="alert">'.$res_upload['text'].'</div>';
        }
        // else $res_upload=array('type'=>'error','code'=>'not_uploaded_file','text'=>'Не был выбран файл');
        // damp_array($_FILES);
        ACCOUNTS()->update_member_info(MEMBER()) ;
        if (!$res)
        {
            echo '<div class="red" style="background: #ae23233b !important;padding: 7px 15px;font-size: 11px;font-weight: 600;">Изменений не обнаружено</div>';
        }
        else
        {
            echo '<div class="green" style="background: #37ae233b !important;padding: 7px 15px;font-size: 11px;font-weight: 600;">Данные сохранены</div>';
            $this->rec_member=ACCOUNTS()->get_member_by_id($this->rec_member['pkey']);
        }
    }

    function panel_mhd()
    {
        if ($this->rec_member['_ext_info']['mhd']) echo '<p>МЧД загруженна, <a href="/public/ecp_mhd/'.$this->rec_member['_ext_info']['mhd'].'" target="_blank">скачать</a></p>' ;
        $this->panel_file_upload();
        if ($_POST['upload_files'][0]) { $this->upload_file(); }
    }

    function panel_file_upload()
    {   ?><div class="sky-form no_box_shadow" id="panel_upload_promt"><form method="POST"><?
       include(_DIR_EXT . '/upload_files/panel_upload_files.php');
       panel_upload_files(array('text' => 'Перетяните и отпустите сюда<br>архив c МЧД',
           //'upload_url' => '/cab/rml/upload_persons_device/',
           'file_filter' => 'zip',
           //'style_panel'=>'margin:0;',
           'SendFormOnUploadSuccess' => 1,
           'view_debug_panel' => 0,
           'style_panel' => 'width:600px;margin:20px auto;',
       ));
       ?></form></div><?
    }

    function upload_file()
    {

        //damp_array($_POST);
       // damp_array($_FILES);
       $fname=$_POST['upload_files'][0] ;
       $save_fname=$this->rec_member['pkey'].'_'.$fname ;
       $file_dir=_TEMP_DIR.'/'.$fname ;
       if (file_exists($file_dir))
       {
           echo 'Загружен архив МЧД <strong>"'.$fname.'"</strong> '.show_size(filesize($file_dir)).'<br>' ;
           if (rename($file_dir,_DIR_TO_ROOT.'/public/ecp_mhd/'.$save_fname))
           {
               echo '<div class=green>Архив МЧД размещен в директории МЧД</div><br>' ;
               ACCOUNTS()->member_save($this->rec_member['pkey'],['ext_info'=>['mhd'=>$save_fname]],array('save_log'=>1)) ;
               ?><script type="text/javascript">document.location="<?echo _CUR_PAGE_DIR?>";</script><?

           }
           else echo '<div class=alert>Не удалось разместить архив МЧД в директории МЧД</div><br>' ;
       }



    }


}
?>
