<?
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
{

    function start_check_car()
    {
        $additional_param='';

        ob_start();

        //  эти данные будут получены со шлюза - при запросе по пропуску возвращается номер путевого листа
        $rec_personal = PERSONAL()->get_personal(array('propusk' => $_POST['propusk_driver']), array('only_enabled' => 1, 'dop_usl' => 'enabled=1'));
        if ($rec_personal['pkey']) {
            $time_mo = getdate(time());
            $time_from = mktime($time_mo['hours'] - 8, $time_mo['minutes'], $time_mo['seconds'], $time_mo['mon'], $time_mo['mday'], $time_mo['year']);
            $rec_mo = ESMO()->get_last_mo_rec_to_personal($rec_personal['pkey'], array('only_model' => 'all', 'time_from' => $time_from));
            if (!$_POST['access_type'] or ($_POST['access_type'] and $rec_mo['pkey'] and $rec_mo['dopusk'] == 1 and $rec_mo['dopusk_time_end'] > time())) {

                $activeRelation = execSQL_van('select * from '.TO()->view_relation.' where active=1 and personal_id='.$rec_personal['pkey'].' order by pkey desc');

                if (sizeof($activeRelation)) {
                    //проверка ТО
                    $last_TO=execSQL_van('select * from '.CAR_TO()->table_name.' where car_id='.$activeRelation['car_id'].' and personal_id='.$activeRelation['personal_id'].' and c_data>'.(time()-$GLOBALS['LS_TO_time_enable']*60*60).' order by pkey desc');

                    if (($last_TO['status']==1 or $last_TO['status']==2) and !$last_TO['mo_id']) {

                        $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=' . $last_TO['pkey']);

                        $page_url = '/cab/rmt/check/' . $last_TO['pkey'] . '/s5/[set_ME]/';
                        $this->go_url = $page_url;
                    } else {

                        if ($last_TO['pkey'] and !$last_TO['status']) execSQL_update('delete from '.CAR_TO()->table_name.' where pkey='.$last_TO['pkey']);

                        echo 'Найдено авто: '.$activeRelation['_car_number'];
                        $id_TO = CAR_TO()->start_TO($rec_personal['pkey'], $rec_mo['pkey'], $activeRelation['car_id'], $_POST['access_type']);
                        echo 'Начат сеанс ТО № ' . $id_TO . '<br>';
                        ?>
                        <p>Открываем интрерфейс оператора.....</p>
                        <?
                        if ($_POST['mode']) {
                            $additional_param=',mode='.$_POST['mode'];
                        }

                        $page_url = '/cab/rmt/check/' . $id_TO . '/s3/[access_type=' . $_POST['access_type'] . $additional_param . ']/';
                        $this->go_url = $page_url;
                    }
                } else {
                    ?>
                    <div class="alert">
                        Не найдено активных связей водитель-автомобиль
                    </div>
                    <?
                }
            } else {
                ?>
                <div class="alert" style="font-size:16px;margin:20px 0;"><?
                echo $rec_personal['obj_name'] . ' - МО не пройден';
                if ($rec_mo['pkey']) 'Последнее МО было ' . date('d.m.Y H:i', $rec_mo['c_data']) . ', срок действия допуска до ' . date('d.m.Y H:i', $rec_mo['dopusk_time_end']);
                ?></div><?
            }

        }
        $text = ob_get_clean();
        $this->add_element('panel_PL_info.HTML', $text);
    }

    function start_check_car2()
    {
        $rec_personal = PERSONAL()->get_personal(array('propusk' => $_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 {
            $this->setPLInfo('Не найден сотрудник с пропуском: '.$_POST['propusk_driver']);
        }
    }

    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();
//                damp_array($last_TO);
                if($last_TO['status']==1) $TO_result='допуск в рейс разрешен';
                elseif($last_TO['status']==2) $TO_result='допуск в рейс запрещен';
                else $TO_result='ТО не завершен';
                ?>
                <p style="font-size: 16px;line-height: 1.5;">
                    ТО у авто <?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>
                <?
                $modal = ob_get_clean();
//                $this->add_element('TO_start_info.HTML', $text);
                echo $modal;
                $this->add_element('show_modal_window','HTML',array('title'=>'ТО уже пройден')) ;
            } else {
                $this->start_TO($relation,$_POST['mode'],$_POST['access_type']);
            }
//            $this->add_element('show_modal_window','HTML');
        }
    }

    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']);
        switch ($mode) {
            case 'tablet_only_car'  :
                $id_TO = CAR_TO()->start_TO_without_driver($relation,$access_type);
                $page_url = '/cab/rmt/check/' . $id_TO . '/s3/[access_type='.$access_type.']/';
                $this->go_url = $page_url;
                break;
            case 'tablet'   :
            case 'pc'       :
            default         :
                $time_mo = getdate(time());
                $time_from = mktime($time_mo['hours'] - 8, $time_mo['minutes'], $time_mo['seconds'], $time_mo['mon'], $time_mo['mday'], $time_mo['year']);
                $rec_mo = ESMO()->get_last_mo_rec_to_personal($rec_personal['pkey'], array('only_model' => 'all', 'time_from' => $time_from));
                if (!$access_type or ($access_type and $rec_mo['pkey'] and $rec_mo['dopusk'] == 1 and $rec_mo['dopusk_time_end'] > time())) {
                    $last_TO = execSQL_van('select * from '.CAR_TO()->table_name.' where car_id='.$relation['car_id'].' and personal_id='.$relation['personal_id'].' and c_data>'.(time()-$GLOBALS['LS_TO_time_enable']*60*60).' order by pkey desc');

                    if (($last_TO['status']==1 or $last_TO['status']==2) and !$last_TO['mo_id']) {

                        $this->update_last_TO($last_TO,$rec_mo);

                        $page_url = '/cab/rmt/check/' . $last_TO['pkey'] . '/s5/[set_ME]/';
                        $this->go_url = $page_url;
                    } else {
                        $id_TO = CAR_TO()->start_TO($rec_personal['pkey'], $rec_mo['pkey'], $rec_car['pkey'], $_POST['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>МО не пройден';
                    ?>
                    </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 decode_rq_code()
    {
        $show_notife = 0;
        include_once(_DIR_EXT . '/php-qrcode-detector-decoder/lib/QrReader.php');
        $qrcode = new QrReader($this->capture_photo_name);
        if ($qrcode->text()) {
            list($car_number, $driver_number) = explode('_', $qrcode->text());
            if ($car_number and $driver_number) {
                $_POST['car_number'] = $car_number;
                $_POST['driver'] = $driver_number;
                $this->start_check_car();
            } else $show_notife = 1;
        } else $show_notife = 1;
        if ($show_notife) {
            $this->add_element('show_notife', 'Не удалость прочитать QR-код. Попробуйте еще раз.', array('color' => 'red', 'position' => '{x: "center", y: "center"}'));
        }
    }

     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()
     { CAR_TO()->save_car_TO($_POST['to_id'],2,$_POST['param']) ;
       //$this->add_element('JSCODE','<script type="text/javascript">window.close();</script>') ;
	   //$this->go_url='/cab/rmt/' ;
       $this->go_url='/cab/rmt/check/'.$_POST['to_id'].'/s4/' ;
     }

     function check_car_allow()
     {
        CAR_TO()->save_car_TO($_POST['to_id'],1,$_POST['param']) ;
        //$this->add_element('JSCODE','<script type="text/javascript">window.close();</script>') ;
	    //$this->go_url='/cab/rmt/' ;
        $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/' ;
       $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']);

       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_car2();
    }


       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'=>'ТО без водителя']);
       }

       function start_to_car()
       {
           $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('Автомобиль не найден');
           }

       }
}