<?php
include_once("c_events_meeting_card_edit_step2.php");
class c_page_cab_events_meeting_card_edit_step3 extends c_page_cab_events_meeting_card_edit_step2
{
  public $h1='Редактирование параметров собрания - темы занятий' ;
  public $rec_doc=array();

  function select_obj_info()
  {  parent::select_obj_info();
       if ($this->rec_event['pkey'])
       { $this->h1=$this->obj_event->name.' '.$this->rec_event['obj_name'].' - темы занятий' ;
         $this->after_save_url=$this->rec_event['__href'].'edit/step3/' ;
         if ($this->filter['theme_id'])
         { $this->rec_theme=execSQL_van('select * from obj_site_events_themes where parent='.$this->rec_event['pkey'].' and clss=225 and pkey='.$this->filter['theme_id']) ;
           $this->h1=$this->obj_event->name.' '.$this->rec_event['obj_name'].' - тема: '.$this->rec_theme['obj_name'] ;
           if ($this->filter['doc_id'])
           { $this->rec_doc=execSQL_van('select * from obj_site_events_themes_files where parent='.$this->rec_theme['pkey'].' and clss=5 and pkey='.$this->filter['doc_id']) ;
           }

         }
       }
  }

  function CMD_save_event()
  { EVENTS()->save_events($this->rec_event['pkey'],$_POST['filter']) ;
    if (!$this->rec_event['enabled']) redirect_301_to($this->rec_event['__href'].'/personals/free/') ;
    else $this->rec_event=EVENTS()->get_event_by_id($this->rec_event['pkey']) ;
  }

  function block_main()
  { $this->page_title() ;
    if ($this->rec_theme['pkey'] and $this->rec_doc['pkey']) $this->panel_edit_theme_doc() ;
    elseif ($this->rec_theme['pkey']) $this->panel_edit_theme() ;
    else $this->panel_select_themes() ;
  }

  function panel_select_themes()
   {   //$this->obj_event->panel_params_edit() ;   // вызываем панель настроек из класса

       $recs_themes=execSQL('select * from obj_site_events_themes where parent='.$this->rec_event['pkey'].' and clss=225 order by indx') ;
       if (_sizeof($recs_themes) and !$this->rec_event['enabled'])
       { EVENTS()->save_events($this->rec_event['pkey'],array('enabled'=>1)) ;
         $this->rec_event=EVENTS()->get_event_by_id($this->rec_event['pkey']) ;
       }
       if (_sizeof($recs_themes))
       {
         $recs_docs=execSQL('select pkey,parent,obj_name,file_name from obj_site_events_themes_files where parent in ('.implode(',',array_keys($recs_themes)).')',0,1) ;
         $recs_docs_by_themes=group_by_field('parent',$recs_docs) ;
         //damp_array($recs_docs_by_themes,1,-1) ;
       }

       $members=ACCOUNTS()->get_list_members() ;
       ?><div id="panel_filter"><form id="sky-form" class="sky-form"><input type="hidden" name="filter[enabled]" value="1"><?
          ?><table class="basic fz_small full auto"><tr class="head"><th>Выбор</th><th>№</th><th>Наименование</th><th>Автор</th><th>Дата добавления</th><th>Методические материалы</th></tr><?
           if (_sizeof($recs_themes)) foreach($recs_themes as $rec)
           { ?><tr>
                 <td style="width:10%;"><input type="checkbox" name="_check[]" value="<?echo $rec['pkey']?>"></td>
                 <td style="width:10%;" class="indx"><i class="fa fa-chevron-circle-up v2" aria-hidden="true" event_id="<?echo $this->rec_event['pkey']?>" theme_id="<?echo $rec['pkey']?>" cmd="events_meeting/event_theme_up"></i>&nbsp;
                                                     <span id="theme_<?echo $rec['pkey']?>"><?echo $rec['indx']?></span>&nbsp;
                                                     <i class="fa fa-chevron-circle-down v2" aria-hidden="true" event_id="<?echo $this->rec_event['pkey']?>" theme_id="<?echo $rec['pkey']?>" cmd="events_meeting/event_theme_down"></i>
                 </td>
                 <td style="width:40%;" class="left"><input type="text" style="width:100%;" name="theme_name[<?echo $rec['pkey']?>]" value="<?echo $rec['obj_name']?>"></td>
                 <td style="width:20%;"><?echo $members[$rec['account_id']]['obj_name']?></td>
                 <td style="width:10%;"><?echo date('d.m.Y H:i',$rec['c_data'])?></td>
                 <td style="width:20%;text-align:left;"><?
                 if (_sizeof($recs_docs_by_themes[$rec['pkey']]))
                 {  ?><ul><?
                    foreach($recs_docs_by_themes[$rec['pkey']] as $rec_doc) {?><li><a href="<?echo _CUR_PAGE_DIR?>[theme_id=<?echo $rec['pkey']?>,doc_id=<?echo $rec_doc['pkey']?>]/"><?echo $rec_doc['obj_name']?></a></li><?}
                    ?></ul><?
                 }
                 if ($this->rec_event['status']!=5){?><button class="button v1" href="<?echo _CUR_PAGE_DIR?>[theme_id=<?echo $rec['pkey']?>]/">Загрузить</button><?}?></td>
               </tr>
             <?
           }
           ?>
            <tr><td colspan="2">Новая тема</td><td><input type="text" style="width:100%;" name="new_theme_name" value=""></td><td colspan="3"></td></tr>
            </table><br>
           <div id="panel_buttons">
              <?if ($this->rec_event['status']!=5){?>
               <button class="button v2" event_id="<?echo $this->rec_event['pkey']?>" cmd="events_meeting/event_theme_save">Сохранить</button><?
               if (_sizeof($recs_themes)){?><button class="button v2" event_id="<?echo $this->rec_event['pkey']?>" cmd="events_meeting/event_theme_delete">Удалить отмеченные темы</button><?}
               if (_sizeof($recs_themes) and $this->rec_event['enabled']){?><button class="button v1" event_id=<?echo $this->rec_event['pkey']?> href="<?echo $this->rec_event['__href']?>">Перейти к карточке собрания</button><?}
              }else echo '<div class=alert>Мероприятие в архиве, изменение тем невозможно</div>'?>
           </div><br>
           </form></div>

            <style type="text/css">
               td.indx i{display:none;}
               td.indx:hover i{display:inline;cursor:pointer;}
               table.basic ul{margin:0 0 0 20px;;padding:0;}
               table.basic ul li{padding:0;margin:0;}
            </style>
            <script type="text/javascript">
                $j('i.fa-chevron-circle-up').click(function()
                 { if (!$j(this).closest('tr').prev().hasClass('head')) $j(this).closest('tr').prev().before($j(this).closest('tr')) ;
                 }) ;
                $j('i.fa-chevron-circle-down').click(function()
                 {  $j(this).closest('tr').next().after($j(this).closest('tr')) ;
                 }) ;
            </script>
           <?
      }

   function panel_edit_theme()
   {
     $this->panel_file_upload() ;
   }

   function panel_edit_theme_doc()
   {
     ?><h2>Методические материалы: <?echo $this->rec_doc['obj_name']?></h2>
       <p>Загрузил: <strong><?echo ACCOUNTS()->get_member_name_by_id($this->rec_doc['account_id'])?></strong></p>
       <p>Дата загрузки: <strong><?echo date('d.m.Y H:i',$this->rec_doc['c_data'])?></strong></p>
       <p>Размер файла: <strong><?echo show_size($this->rec_doc['size'])?></strong></p>
       <p>Тип файла: <strong><?echo $this->rec_doc['type']?></strong></p>
     <?
     switch($this->rec_doc['type'])
     { case 'application/pdf':  ?><iframe src="<?echo _MAIN_PROTOCOL._MAIN_DOMAIN?>/public/instruktions_docs/<?echo $this->rec_doc['file_name']?>" style="width:100%; height:700px;" frameborder="0" /></iframe><br><br><? break ;
       default: ?><img src="<?echo _MAIN_PROTOCOL._MAIN_DOMAIN?>/public/instruktions_docs/<?echo $this->rec_doc['file_name']?>" style="max-width:90%;margin:0 auto;display:block;"><?
     }
     ?><div id=panel_buttons class="sky-form no_box_shadow">
            <button class=button id="print_doc_over_window" href="<?echo _MAIN_PROTOCOL._MAIN_DOMAIN?>/public/instruktions_docs/<?echo $this->rec_doc['file_name']?>">Печать</button>&nbsp;&nbsp;
            <button class="button v1" href="/window/events_meeting/card/<?echo $this->rec_event['pkey']?>/edit/step3/">Закрыть</button>&nbsp;&nbsp;
            <button class="button v2" cmd="events_meeting/delete_theme_docs" doc_id="<?echo $this->rec_doc['pkey']?>" after_delete_go_url="/window/events_meeting/card/<?echo $this->rec_event['pkey']?>/edit/step3/">Удалить документ</button>
       </div><?
       //echo _CUR_CAB_DIR  ;
   }

   function panel_file_upload()
     {   ?><script type="text/javascript" src="/AddOns/uploader-master/src/dmuploader.min.js"></script>
           <link rel="stylesheet" href="/<?echo _CLASS_?>/ext/esmo_magnit/style_uploader.css" rel="stylesheet" />
           <div id="panel_file_upload">
               <!-- D&D Markup -->
               <div id="drag-and-drop-zone" class="uploader">
                 <div>Перетяните и отпустите сюда<br><br>методические материалы для инструктажа</div>
                 <div class="or">- или -</div>
                 <div class="browser">
                   <label>
                     <span>&nbsp;&nbsp;&nbsp;Кликните для выбора файла<br>на вашем ПК&nbsp;&nbsp;&nbsp;</span>
                     <input type="file" name="files[]" multiple="multiple" title='Click to add Files'>
                   </label>
                 </div>
               </div>
             <div id="fileList"></div>
           </div>
           <div id="report"></div>
           <div id="debug"><h2>Лог работы</h2><div><ul></ul></div></div>
           <br>
           <br>


           <script type="text/javascript">

             //-- Some functions to work with our UI
             function add_log(message)
             { var template = '<li>[' + new Date().getTime() + '] - ' + message + '</li>';
               $j('#debug').find('ul').prepend(template);
             }

             function add_file(id, file)
             { var template = '' +
                 '<div class="file" id="uploadFile' + id + '">' +
                   '<div class="info">' +
                     '#1 - <span class="filename" title="Size: ' + file.size + 'bytes - Mimetype: ' + file.type + '">' + file.name + '</span><br /><small>Status: <span class="status">Waiting</span></small>' +
                   '</div>' +
                   '<div class="bar">' +
                     '<div class="progress" style="width:0%"></div>' +
                   '</div>' +
                 '</div>';

                 $j('#fileList').prepend(template);
             }

             function update_file_status(id, status, message)
             {
               $j('#uploadFile' + id).find('span.status').html(message).addClass(status);
             }

             function update_file_progress(id, percent)
             {
               $j('#uploadFile' + id).find('div.progress').width(percent);
             }

             // Upload Plugin itself
             $j('#drag-and-drop-zone').dmUploader({
               url: '/cab/events_meeting/upload/json/',
               dataType: 'json',
               extraData: {theme_id:'<?echo $this->rec_theme['pkey']?>',theme_reffer:'<?echo $this->rec_theme['_reffer']?>'},  // будет передано через POST
               //allowedTypes: 'application/*',
               //extFilter: 'jpg',
               //allowedTypes: 'image/*',
               //extFilter: 'jpg;png;gif',
               extFilter: 'jpg;pdf;png;gif',

               onInit: function()
               { add_log('Загрузщик готов к работе');
               },
               onBeforeUpload: function(id)
               { add_log('Начало загрузки файла #' + id);
                 update_file_status(id, 'uploading', 'Загрузка...');
               },
               onNewFile: function(id, file)
               { add_log('Файл поставлен в очередь загрузки #' + id);
                 add_file(id, file);
               },
               onComplete: function()
               { add_log('Все загрузки завершены');
               },
               onUploadProgress: function(id, percent)
               { var percentStr = percent + '%';
                 update_file_progress(id, percentStr);
               },
               onUploadSuccess: function(id, data)
               { add_log('Загрузка файла #' + id + ' завершена');
                 //add_log('Ответ сервера по файлу #' + id + ': ' + JSON.stringify(data));
                 add_log('Ответ сервера по файлу #' + id + ': ' + data.status);
                 update_file_status(id, 'success', 'Загрузка завершена');
                 update_file_progress(id, '100%');
                 $j('div#report').html(data.report) ;
                 // если документ загружен не Техником ПДД на АТП - перейти к обработке документа
                 //if (data.account_rol_id!=12) document.window.location='/cab/esmo_magnit/pdd/scan/'+data.scan_id+'/' ;
               },
               onUploadError: function(id, message)
               { add_log('Failed to Upload file #' + id + ': ' + message);
                 update_file_status(id, 'error', message);
               },
               onFileTypeError: function(file)
               { add_log('File \'' + file.name + '\' cannot be added: must be an image');
               },
               onFileSizeError: function(file){
                 add_log('File \'' + file.name + '\' cannot be added: size excess limit');
               },
               /*onFileExtError: function(file){
                 $.danidemo.addLog('#demo-debug', 'error', 'File \'' + file.name + '\' has a Not Allowed Extension');
               },*/
               onFallbackMode: function(message)
               { alert('Browser not supported(do something else here!): ' + message);
               }
             });
           </script>
           <style type="text/css">
               #panel_file_upload{width:800px;}
           </style>


       <?


        }
}
?>
