<?
include_once(_DIR_EXT.'/HTML/c_page_XML_AJAX.php') ;
include_once(_DIR_EXT.'/rmt/i_mrt.php') ;
include_once(_DIR_TO_ENGINE.'/admin/i_admin_system.php') ;
class c_page_ajax extends c_page_XML_AJAX
{

    //Начало ТО после ввода номера пропуска водителя или при считывании qr кода
    function start_check_to()
    {
        $rec_personal = PERSONAL()->get_personal(array('propusk' => $_POST['propusk_driver'], 'tab_number' => $_POST['propusk_driver']), array('only_enabled' => 1, 'dop_usl' => 'enabled=1'));
        if ($rec_personal['pkey']) {
            $activeRelation = TO()->get_active_person_relation($rec_personal['pkey']);
            if (_sizeof($activeRelation)) {
                $this->TO_start_panel($activeRelation,$_POST['mode']);
                $this->add_element('show_modal_window','HTML',['title'=>'Выбор направления движения','width'=>'auto']); //'after_close_update_page'=>1
            } else {
                $this->setPLInfo('<div class="alert">Не найдено активных связей водитель-автомобиль</div>');
            }
        } else {
            if ($_POST['mode']='tablet') {
                $this->start_check_car();
            } else {
                $this->setPLInfo('Сотрудник не найден: '.$_POST['propusk_driver']);
            }
        }
    }

    //Начало ТО при считывании qr после того как не удалось найти водителя
    function start_check_car()
    {
        $rec_car = execSQL_van('select * from '.TO()->table_car.' where obj_name="'.$_POST['propusk_driver'].'" or uid="'.$_POST['propusk_driver'].'"');
        if ($rec_car['pkey']) {
            $activeRelation = TO()->get_active_car_relation($rec_car['pkey']);
            if (_sizeof($activeRelation)) {
                $this->TO_start_panel($activeRelation,$_POST['mode']);
                $this->add_element('show_modal_window','HTML',['title'=>'Выбор направления движения','width'=>'auto']); //'after_close_update_page'=>1
            } else {
                $this->setPLInfo('<div class="alert">Не найдено активных связей водитель-автомобиль</div>');
            }
        } else {
            $this->setPLInfo('Информация не найдена: '.$_POST['propusk_driver']);
        }
    }

    //Начало ТО при вводе номера авто
    function start_to_by_car_number()
    {
       $car_rec = PERSONAL()->get_car_by_number($_POST['filter']['car_number']);
       $_POST['mode']="tablet_only_car";

       if ($car_rec['pkey']) {
           $activeRelation = TO()->get_active_car_relation($car_rec['pkey']);
           if (_sizeof($activeRelation)) {
               $this->TO_start_panel($activeRelation,$_POST['mode']);
               $this->add_element('show_modal_window','HTML',['title'=>'Выбор направления движения','width'=>'auto']);
           } else {
               $this->setPLInfo('<div class="alert">Не найдено активных связей водитель-автомобиль</div>');
           }
       } else {
           $this->setPLInfo('Автомобиль не найден');
       }
    }

    function setPLInfo($str)
    {
        $this->add_element('panel_PL_info.HTML', $str);
    }

    function TO_start_panel($activeRelation,$mode='pc')
    {
        $rec_car = PERSONAL()->get_car_by_id($activeRelation['car_id']);
        $rec_personal = PERSONAL()->get_personal_by_id($activeRelation['personal_id']);
        ?>
        <form>
            <div class="TO_info col-md col-md-auto"><span>Авто: </span><?echo $rec_car['obj_name'].', '.$rec_car['model']?></div>
            <div class="TO_info col-md col-md-auto"><span>Водитель: </span><?echo $rec_personal['obj_name']?></div>
            <div class="TO_button_row">
                <div class="TO_buttons TO_direction disactive" access_type="1">ВЫЕЗД</div>
                <div class="TO_buttons TO_direction disactive" access_type="0">ВЪЕЗД</div>
            </div>
            <div id="TO_start_info"></div>
            <div class="TO_button_row">
                <div class="TO_buttons not_active" id="TO_start_button">Начать ТО</div>
                <div class="TO_buttons cancel" id="cancel">Отмена</div>
            </div>
        </form>
        <script type="text/javascript">
            TO_access_type=2;
            $j('div.TO_direction').on('click',function(){
                $j('div.TO_direction').removeClass('active').addClass('disactive');
                $j(this).removeClass('disactive').addClass('active');
                TO_access_type = $j(this).attr('access_type');
                if ($j('#TO_start_button').hasClass('not_active')) {
                    $j('#TO_start_button').removeClass('not_active').addClass('active');
                }
            });

            $j('#TO_start_button').on('click',function(){
                if ($j('#TO_start_button').hasClass('active')) {
                    send_ajax_request({cmd:'rmt/check_TO_start',relation_id:<?echo $activeRelation['pkey']?>,access_type:TO_access_type,mode:'<?echo $mode?>'});
                }
            });
        </script>
        <?
    }

    function check_TO_start()
    {
        if (!in_array($_POST['access_type'],[0,1])) {
            $this->add_element('TO_start_info.HTML', '<div class="alert">Не выбрано направление</div>');
        } else {
            $relation = TO()->get_relation_by_id($_POST['relation_id']);
            //поиск ТО для связи авто-водитель
            //уведомление в случае если такое ТО есть
            //начало ТО если такого нет
            $last_TO = execSQL_van('select * from '.CAR_TO()->table_name.' where car_id='.$relation['car_id'].' and access_type='.$_POST['access_type'].' and c_data>'.(time()-$GLOBALS['LS_TO_time_enable']*60*60).' order by pkey desc');
            if (is_array($last_TO) && ($last_TO['status']==1 or $last_TO['status']==2) and $last_TO['mo_id']) {
                ob_start();

                if($last_TO['status']==1) {
                    $TO_result='допуск в рейс разрешен';
                } elseif($last_TO['status']==2) {
                    $TO_result='допуск в рейс запрещен';
                } else {
                    $TO_result='ТО не завершен';
                }
                ?>
                <p class="TO_exist_alarm">
                    ТО у авто <?echo $last_TO['car_number'];?> пройдено: <?echo date('d.m.Y H:i:s', $last_TO['c_data']);?> <br>
                    Результат: <?echo $TO_result;?> <br>
                    Начать новое ТО?
                </p>
                <div class="buttons">
                    <div class="TO_buttons v2" cmd="rmt/restart_TO" relation_id="<?echo $_POST['relation_id'];?>" access_type="<?echo $_POST['access_type'];?>" mode="<?echo $_POST['mode'];?>">Да</div>
                    <div class="TO_buttons cancel">Отмена</div>
                </div>
                <?
                $html = ob_get_clean();
                echo $html;
                $this->add_element('show_modal_window','HTML',array('title'=>'ТО уже пройден')) ;
            } else {
                //начало ТО
                $this->start_TO($relation,$_POST['mode'],$_POST['access_type']);
            }
        }
    }

    function close_modal() {
        $this->add_element('close_mBox_window','mBox_check_TO_start');
    }

    function restart_TO() {
        $relation = TO()->get_relation_by_id($_POST['relation_id']);
        $this->start_TO($relation,$_POST['mode'],$_POST['access_type']);
    }

    function start_TO($relation,$mode,$access_type) {
        $rec_car = PERSONAL()->get_car_by_id($relation['car_id']);
        $rec_personal = PERSONAL()->get_personal_by_id($relation['personal_id']);

        //LS_setting_auto_mo_allow_interval
        $time_now=getdate(time());
        $time_mo_from = mktime($time_now['hours'] - $GLOBALS['LS_setting_auto_mo_allow_interval'], $time_now['minutes'], $time_now['seconds'], $time_now['mon'], $time_now['mday'], $time_now['year']);
        //mo_tk
        // tk - 0 - предсменный - передаем mo_tk - 1
        // tk - 1 - послесменный - передаем mo_tk - 2
        // tk - 2 - межсменный - передаем mo_tk - 3
        switch ($access_type) {
            case 0:     $mo_tk=2; break;    //въезд
            case 1:                         //выезд
            default:    $mo_tk=1; break;
        }
        $rec_mo = ESMO()->get_last_mo_rec_to_personal($rec_personal['pkey'], array('only_model' => 'all', 'time_from' => $time_mo_from,'tk'=>$mo_tk));

        // TODO добавить возможность отложенного МО
        // Сначала проводится ТО, а затем МО
        switch ($mode) {
            case 'tablet_only_car'  :
            case 'tablet'   :
            case 'pc'       :
            default:
                if ($rec_mo['pkey'] and $rec_mo['dopusk'] == 1 and $rec_mo['dopusk_time_end'] > time()) {
                    $id_TO = CAR_TO()->start_TO($rec_personal['pkey'], $rec_mo['pkey'], $rec_car['pkey'], $access_type);
                    $page_url = '/cab/rmt/check/' . $id_TO . '/s3/[access_type=' . $access_type . ']/';
                    $this->go_url = $page_url;
                } else {
                    if (!$GLOBALS['LS_TO_require_aftershift_ME_for_entry'] and $access_type==0) {
                        //если выключена настройка требующая послесменного МО для ТО на выезд
                        $id_TO = CAR_TO()->start_TO($rec_personal['pkey'], 0, $rec_car['pkey'], $access_type);
                    $page_url = '/cab/rmt/check/' . $id_TO . '/s3/[access_type=' . $access_type . ']/';
                    $this->go_url = $page_url;
                } else {
                    ob_start();
                    ?>
                    <div class="alert" style="font-size:16px;margin:20px 0;">
                    <?
                        echo $rec_personal['obj_name'] . '<br>не пройден '.$_SESSION['ARR_mo_tk_type'][$mo_tk-1].' МО';
                    ?>
                    </div>
                    <?
                    $text=ob_get_clean();
                    $this->add_element('TO_start_info.HTML', $text);
                }
                }
                break;
        }
    }

    function update_last_TO($TO_key,$rec_mo)
    {
        $to_data = [];
        $to_data['mo_id']=$rec_mo['pkey'] ;
        $to_data['mo_status']=$rec_mo['dopusk'] ;

        if ($rec_mo['doctor_id'])          $to_data['doctor_id']=$rec_mo['doctor_id'] ;
        if ($rec_mo['dopusk_user_id'])     $to_data['doctor_id']=$rec_mo['dopusk_user_id'] ;
        if ($rec_mo['hand_check_user_id']) $to_data['doctor_id']=$rec_mo['hand_check_user_id'] ;

        update_rec_in_table(CAR_TO()->table_name, $to_data, 'pkey=' . $TO_key['pkey']);
    }

    function javascript_unescape($str)
    {
        $str = rawurldecode($str);
        preg_match_all("/(?:%u.{4})|&#x.{4};|&#\d+;|.+/U", $str, $r);
        $ar = $r[0];
        foreach ($ar as $k => $v) {
            if (substr($v, 0, 2) == "%u") $ar[$k] = iconv("UCS-2", "UTF-8", pack("H4", substr($v, -4)));
            elseif (substr($v, 0, 3) == "&#x") $ar[$k] = iconv("UCS-2", "UTF-8", pack("H4", substr($v, 3, -1)));
            elseif (substr($v, 0, 2) == "&#") $ar[$k] = iconv("UCS-2", "UTF-8", pack("n", substr($v, 2, -1)));
        }
        return join("", $ar);
    }

     function save_step_1()
     {  // переходим на страницу фото
        $this->go_url='/cab/rmt/check/'.$_POST['check_id'].'/s3/' ;
     }

     function show_photo_panel()
     {
        ?><div id="panel_photo_capture">
                <div id="div_capture">
                    <div id="capture_area"><video id="video" autoplay=""></video></div>
                    <div id="buttons"><button id="snap" save_cmd="rmt/fixed_photo_capture" to_id="<?echo $_POST['to_id']?>" param_id="<?echo $_POST['param_id']?>"></button></div>
                    <div class="clear"></div>
                    <div id="preview_area" class="hidden">
                        <input type="hidden" id="capture_img_name" name="capture_img_name"><input type="hidden" id="x" name="x"><input type="hidden" id="y" name="y"><input type="hidden" id="w" name="w"><input type="hidden" id="h" name="h">
                        <img id="capture_img" src="" class="hidden">
                        <!--<img id="capture_img2" src="" class="float_left"><div id="crop_info"></div><div class="clear"></div>-->
                        <canvas id="canvas" class="hidden" width="640" height="480"></canvas>
                    <div class="buttons">
                        <button id="repeat"></button>
                        <button id="save" class=v2 cmd="rmt/fixed_photo_capture" to_id="<?echo $_POST['to_id']?> param_id=<?echo $_POST['param_id']?>"></button>
                    </div>
                    </div>
                </div>
                <div class="center sky-form"><button class="button cancel">Закрыть</button></div>
                <script type="text/javascript">
                  $j(document).ready(function (){$j('div#panel_photo_capture').webcamera_capture({zerkalo:false,dir_sounds:"<?echo _PATH_TO_EXT.'/rmt/sounds/'?>"}) ;}) ;
                </script>
           <?
           $this->add_element('show_modal_window','HTML',array('width'=>'650px')) ;
     }

    var $capture_photo_name='' ;

    function fixed_photo_capture()
      {  //damp_array($_POST,1,-1) ;
      //$this->add_element('show_modal_window','HTML',array('width'=>'650px')) ;
      //return ;
        $to_id=$_POST['to_id'] ;
        $param_id=$_POST['param_id'] ;

        $str = file_get_contents("php://input");
        $str = rawurldecode($str);
        $str = explode('base64,', $str);
        $capture_photo_dir=_DIR_TO_ROOT.'/temp/to_'.$to_id.'_'.$param_id.'.jpg' ;
        $x=fopen($capture_photo_dir,"w");
        fwrite($x, base64_decode($str[1]));
        fclose($x);
        $this->add_element('JSCODE','<script type="text/javascript">$j("#video")[0].play();</script>') ;
        $this->add_element('show_notife','Фото сохранено',array('color'=>'green')) ;
        $this->save_photo($to_id,$param_id,$capture_photo_dir) ;
      }


    function save_photo($id_TO, $param_id, $img_dir)
    {
        $rec_TO = CAR_TO()->get_TO_by_id($id_TO, array('only_start' => 1));
        $param_title = execSQL_value('select obj_name from obj_site_to_params where pkey=' . $param_id);
        if ($rec_TO['pkey']) {
            $img_info = array('name' => basename($img_dir), 'upl_name' => $img_dir);
            TO()->upload_TO_image($img_info);
//            $img_reffer = obj_upload_image($rec_TO['_reffer'], $img_info, array('debug' => 0, 'view_upload' => 1));
//            if ($img_reffer) {
//                list($img_pkey, $img_tkey) = explode('.', $img_reffer);
//                update_rec_in_table($img_tkey, array('obj_name' => $param_title), 'pkey=' . $img_pkey);
//            }

        }
    }

     function check_car_denited()
     {
       $data=[];
       $data['status']=2;
       $data['enabled']=1;
       CAR_TO()->save_car_TO($_POST['to_id'],$_POST['param'],['data'=>$data,'encode_params'=>1]) ;

       if ($GLOBALS['LS_TO_comment_after_denied']) $this->go_url='/cab/rmt/check/'.$_POST['to_id'].'/denied_info/' ;
       else $this->go_url='/cab/rmt/check/'.$_POST['to_id'].'/s4/' ;
     }

     function check_car_allow()
     {
        $data=[];
        $data['status']=1;
        $data['enabled']=1;
        CAR_TO()->save_car_TO($_POST['to_id'],$_POST['param'],['data'=>$data,'encode_params'=>1]) ;

        $this->go_url='/cab/rmt/check/'.$_POST['to_id'].'/s4/' ;
     }

     function save_tech_comment()
     {
        $data=[];
        $data['comment']=$_POST['comment'];
        if (_sizeof($data))  CAR_TO()->save_car_TO($_POST['to_id'],[],['data'=>$data]) ;

        $this->go_url='/cab/rmt/check/'.$_POST['to_id'].'/s4/' ;
     }

     function save_send_photo($data,$img_name)
     { $img_string=base64_decode($data) ;  //echo $img_string ;
       $img_dir='/public/to_sign/'.$img_name ;
       if (file_exists(_DIR_TO_ROOT.$img_dir)) unlink(_DIR_TO_ROOT.$img_dir) ;
       file_put_contents(_DIR_TO_ROOT.$img_dir,$img_string) ;
     }

     function driver_sign()
     { $fname='driver_'.$_POST['to_id'].'_pers_'.$_POST['personal_id'].'.png' ;
       $this->save_send_photo($_POST['image'][1],$fname) ;
       update_rec_in_table('obj_site_cars_to',array('sign_driver'=>$fname),'pkey='.$_POST['to_id']) ;
       //$this->go_url='/cab/rmt/check/'.$_POST['to_id'].'/s5/' ;
        ENGINE()->on_event_by_pointer('TO_result',$_POST['to_id']) ;
       $this->go_url='/cab/rmt/' ;
     }

     function tech_sign()
     {
       $fname='tech_'.$_POST['to_id'].'_pers_'.$_POST['personal_id'].'.png' ;
       $this->save_send_photo($_POST['image'][1],$fname) ;
       update_rec_in_table('obj_site_cars_to',array('sign_tech'=>$fname),'pkey='.$_POST['to_id']) ;
       $TO = CAR_TO()->get_TO_by_id($_POST['to_id']);

           $this->go_url='/cab/rmt/check/'.$_POST['to_id'].'/s5/' ;
//       if (!$TO['mo_id']) {
//           $this->go_url='/cab/rmt/' ;
//       } else {
//           $this->go_url='/cab/rmt/check/'.$_POST['to_id'].'/s5/' ;
//       }
     }

    function to_params_delete()
    {   TO()->to_params_delete($_POST['_check']) ;
        $this->update_page=1 ;
    }

    function to_params_save()
    {
//        $this->add_element('show_modal_window','HTML',array('title'=>'Регистрация сотрудника на инструктаж','width'=>'800px')) ;
//        damp_array($_POST,1,-1) ;
//        return ;
        if (_sizeof($_POST['params'])) foreach($_POST['params'] as $id=>$data) TO()->to_params_save($id,$data) ;
        if (_sizeof($_POST['new_param']) and $_POST['new_param']['obj_name']) TO()->to_params_create($_POST['new_param'],$_POST['car_type']) ;
        $this->update_page=1 ;
    }

    function TO_param_up()
    {
        $cur_rec=execSQL_van('select pkey,indx,access from obj_site_to_params where pkey='.$_POST['param_id'].' and clss=361') ;
        $prev_rec=execSQL_van('select pkey,indx from obj_site_to_params where access='.$cur_rec['access'].' and indx<'.$cur_rec['indx'].' and clss=361 order by indx desc limit 1') ;
        if ($prev_rec['pkey'])
        { execSQL_update('update obj_site_to_params set indx='.$prev_rec['indx'].' where pkey='.$cur_rec['pkey']) ;
            execSQL_update('update obj_site_to_params set indx='.$cur_rec['indx'].' where pkey='.$prev_rec['pkey']) ;
            $this->add_element('param_'.$_POST['theme_id'].'.HTML',$prev_rec['indx']) ;
            $this->add_element('param__'.$prev_rec['pkey'].'.HTML',$cur_rec['indx']) ;

        }
    }

    function TO_param_down()
    {
        $cur_rec=execSQL_van('select pkey,indx,access from obj_site_to_params where pkey='.$_POST['param_id'].' and clss=361') ;
        $next_rec=execSQL_van('select pkey,indx from obj_site_to_params where access='.$cur_rec['access'].' and indx>'.$cur_rec['indx'].' and clss=361 order by indx limit 1') ;
        if ($next_rec['pkey'])
        { execSQL_update('update obj_site_to_params set indx='.$next_rec['indx'].' where pkey='.$cur_rec['pkey']) ;
            execSQL_update('update obj_site_to_params set indx='.$cur_rec['indx'].' where pkey='.$next_rec['pkey']) ;
            $this->add_element('theme_'.$_POST['theme_id'].'.HTML',$next_rec['indx']) ;
            $this->add_element('theme_'.$next_rec['pkey'].'.HTML',$cur_rec['indx']) ;
        }
    }

    function create_put_list()
    {
//        $to_id=$_POST['to_id'];
//
//        $doc_url=CAR_TO()->create_put_list($to_id);
//
//        echo $doc_url.'<br>';
//
//        $this->add_element('show_modal_window','HTML');
    }


    function ready_qr_code()
    {
        $code=$this->javascript_unescape($_POST['qr_code1']) ;

        $_POST['propusk_driver']=$_POST['qr_code'];
//        $_POST['access_type']=1;
        $_POST['mode']='tablet';

        $this->start_check_to();
    }


       function rotate_l_image()
       {   $rec_scan=DOCS()->get_scan_by_id($_POST['scan_id']) ;
           $new_name=$this->rotare_img($rec_scan['obj_name'],-90) ;
           update_rec_in_table('obj_site_scan',array('obj_name'=>$new_name),'pkey='.$rec_scan['pkey'],array('debug'=>0)) ;
           //$this->add_element('show_modal_window','HTML',array('title'=>'Регистрация сотрудника на инструктаж','width'=>'800px')) ;
           //$this->add_element('doc_image.SRC',$new_name) ;
           $this->update_page=1 ;
       }


       function rotate_r_image()
       {
           $rec_scan=DOCS()->get_scan_by_id($_POST['scan_id']) ;
           $new_name=$this->rotare_img($rec_scan['obj_name'],90) ;
           update_rec_in_table('obj_site_scan',array('obj_name'=>$new_name),'pkey='.$rec_scan['pkey'],array('debug'=>0)) ;
           //$this->add_element('show_modal_window','HTML',array('title'=>'Регистрация сотрудника на инструктаж','width'=>'800px')) ;
           //$this->add_element('doc_image.SRC',$new_name) ;
           $this->update_page=1 ;
       }



       function rotare_img($file_name,$grad)
       {
           $imagick = new Imagick();
           $imagick->readImage(_DIR_TO_ROOT.$file_name);
           $arr=explode('.',$file_name) ;
           $arr[_sizeof($arr)]=$arr[_sizeof($arr)-1] ;
           $arr[_sizeof($arr)-2]=time() ;
           $file_name=implode('.',$arr) ;
           $imagick->rotateImage(new ImagickPixel('none'),$grad);
           $imagick->writeImage(_DIR_TO_ROOT.$file_name);
           $imagick->clear();
           return($file_name) ;
           $imagick->destroy();
       }

       function panel_only_car_TO()
       {
           ?>
           <form class="sky-form no_box_shadow">
                <div class="row">
                    <?
                    FORM()->filter_section_input_text('car_number','Номер авто:',11,array('auto_complete'=>"autocomplette_car_number_to")) ;
                    ?>
                </div>
           </form>
           <?
           $this->add_element('show_modal_window','HTML',['title'=>'ТО без водителя']);
       }

}
