<?
function CAR_TO()
{
  $car_to=new c_car_TO() ;
  return($car_to) ;
}

class c_car_TO
{
  public $table_name='obj_site_cars_to' ;
  private $clss_TO=360 ;

  function start_TO($personal_id,$mo_id,$car_id,$access_type)
  {   //echo '$personal_id='.$personal_id.'<br>' ;
      $rec_mo=ESMO()->get_mo_by_id($mo_id) ;
      $rec_personal=PERSONAL()->get_personal_by_id($personal_id) ;
      $rec_car=PERSONAL()->get_car_by_id($car_id) ;

      $data = array('clss' => $this->clss_TO,
          'obj_name' => $rec_personal['obj_name'],
          'member_id' => MEMBER()->id,
          'personal_id' => $rec_personal['pkey'],
          'personal_uuid' => $rec_personal['uid'],
          'driving' => $rec_personal['driving'],
          'permit' => $rec_personal['permit'],
          'car_number' => $rec_car['obj_name'],
          'car_uuid' => $rec_car['uid'],
          'car_id' => $rec_car['pkey'],
          'car_model' => $rec_car['model'],
          'mo_id' => $rec_mo['pkey'],
          'mo_status' => $rec_mo['dopusk'],
          'access_type' => $access_type,
          'enabled' => 1
      );
      if ($rec_mo['doctor_id'])          $data['doctor_id']=$rec_mo['doctor_id'] ;
      if ($rec_mo['dopusk_user_id'])     $data['doctor_id']=$rec_mo['dopusk_user_id'] ;
      if ($rec_mo['hand_check_user_id']) $data['doctor_id']=$rec_mo['hand_check_user_id'] ;

      $id_to=adding_rec_to_table($this->table_name,$data) ;
      $data['id_TO']=$id_to ;
      LOGS()->reg_log('ТО','Начало ТО авто',array('member_id'=>$rec_personal['pkey'],'data'=>$data)) ;
      return($id_to) ;
  }

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

      $data=array('clss'=>$this->clss_TO,
          'obj_name'=>$rec_personal['obj_name'],
          'member_id'=>MEMBER()->id,
          'personal_id'=>$rec_personal['pkey'],
          'personal_uuid'=>$rec_personal['uid'],
          'driving'=>$rec_personal['driving'],
          'permit'=>$rec_personal['permit'],
          'car_number'=>$rec_car['obj_name'],
          'car_uuid'=>$rec_car['uid'],
          'car_id'=>$rec_car['pkey'],
          'car_model'=>$rec_car['model'],
//          'mo_id'=>$rec_mo['pkey'],
//          'mo_status'=>$rec_mo['dopusk'],
          'access_type'=>$access_type,
          'enabled'=>1
      ) ;

      $id_to=adding_rec_to_table($this->table_name,$data) ;
      $data['id_TO']=$id_to ;
      LOGS()->reg_log('ТО','Начало ТО авто без водителя',array('member_id'=>$rec_personal['pkey'],'data'=>$data)) ;
      return($id_to) ;
  }


  function save_car_TO($id_TO,$params,$options=[])
  {
     $data=[];

     if (_sizeof($options['data'])) $data=$options['data'];
     if ($params['odometr']) $data['probeg']=$params['odometr'];
     if ($options['encode_params']) $data['result']=json_encode($params);

     update_rec_in_table($this->table_name,$data,'pkey='.$id_TO) ;
  }

  function get_TO_by_id($id,$options=array())
  { $rec=execSQL_van('select * from '.$this->table_name.' where pkey='.$id) ;
    if ($rec['pkey']) $this->prepare_public_info_to_TO($rec) ;
    return($rec) ;
  }

  function get_TO_by_mo($id,$options=array())
  { $rec=array() ;
    $debug=$options['debug'] ;
    if ($id)
    { $rec=execSQL_van('select * from '.$this->table_name.' where mo_id='.$id) ;
      if ($rec['pkey']) $this->prepare_public_info_to_TO($rec) ;
    }
    return($rec) ;
  }

  function prepare_public_info_to_TO(&$rec,$options=array())
  {  $rec['__href']='/cab/rmt/check/'.$rec['pkey'].'/' ;
     $cnt1=0 ; $cnt2=0 ;
     for($i=1;$i<=19;$i++) { if ($rec['i'.$i]==1) $cnt1++ ; else { $rec['i'.$i]=0 ; $cnt2++ ;} }
     $rec['_check_status']=$cnt1.' / '.$cnt2 ;
     $rec['_status']=($rec['status']==1)? 'Разрешен':'Запрещен';
     if (!$rec['_member_name']) $rec['_member_name']=ACCOUNTS()->get_member_name_by_id($rec['member_id']) ;
  }

  function get_TO_recs($options=array())
  { $_usl[]='t1.clss=360' ;
    if ($options['member_id']) $_usl[]='t1.member_id='.$options['member_id'] ;
    if ($options['doctor_id']) $_usl[]='t1.doctor_id='.$options['doctor_id'] ;
    if ($options['time_from'])     $_usl[]='t1.c_data>='.$options['time_from'] ;
    if ($options['time_to'])       $_usl[]='t1.c_data<='.$options['time_to'] ;
    if ($options['terminal_id'])       $_usl[]='t1.terminal_id in ('.$options['terminal_id'].')' ;
    if ($options['park_id'])       $_usl[]='t2.parent in ('.$options['park_id'].')' ;
    //damp_array($options,1,-1) ;
    //damp_array($_usl,1,-1) ;
    $limit=($options['limit'])? ' limit '.$options['limit']:'' ;

    //if ($options['status']) $_usl[]='clss=300' ;
    $usl=implode(' and ',$_usl) ;
    $recs=execSQL('select t1.*,t2.parent as park_id from '.$this->table_name.' t1
                   left join obj_site_personals t2 on t2.pkey=t1.personal_id
                   where '.$usl.'
                   order by t1.pkey desc'.$limit) ;

    // для оптимизации запросов собираем всю необходимуб информацию напрямую, не используя функции  get_member_by_id,get_personal_by_id,get_car_by_id,get_mo_by_id - их информация избыточна для текущего отчета
    $arr_mo=array() ;  $recs_signatures=array() ;
    $arr_personal=array() ;  $recs_drivings=array() ;
    $arr_member=array() ;  $recs_members=array() ;
    $arr_car=array() ;  $recs_cars=array() ;
    if (_sizeof($recs)) foreach($recs as $rec)
    {  if ($rec['member_id']) $arr_member[$rec['member_id']]=1 ;
       if ($rec['doctor_id']) $arr_member[$rec['doctor_id']]=1 ;
       $arr_personal[$rec['personal_id']]=1 ;
       $arr_car[$rec['car_id']]=1 ;
       if ($rec['mo_id']) $arr_mo[$rec['mo_id']]=1 ;
    }
    //$debug=_IS_SYSTEM_IP ;
    $debug=0 ;
    if (_sizeof($arr_mo)) $recs_signatures=execSQL_row('select parent,pkey from obj_site_mo_session_DTW where parent in ('.implode(',',array_keys($arr_mo)).')',array('debug'=>$debug)) ;
    if (_sizeof($arr_personal)) $recs_drivings=execSQL_row('select pkey,driving from '.PERSONAL()->table_personal.' where pkey in ('.implode(',',array_keys($arr_personal)).')',array('debug'=>$debug)) ;
    if (_sizeof($arr_member))   $recs_members=execSQL_row('select pkey,obj_name from '.ACCOUNTS()->table_account.' where pkey in ('.implode(',',array_keys($arr_member)).')',array('debug'=>$debug)) ;
    //if (_sizeof($arr_car))   $recs_cars=execSQL_row('select pkey,model from obj_site_personals_cars where pkey in ('.implode(',',array_keys($arr_car)).')',array('debug'=>$debug)) ;

    if (_sizeof($recs)) foreach($recs as $i=>$rec)
    { if ($rec['mo_id'] and isset($recs_signatures[$rec['mo_id']])) $recs[$i]['_personal_mo_signature']=_PATH_TO_SITE.'/services/esmo_signature/graf_signature/?mo_id='.$rec['mo_id'] ;
      if ($rec['member_id'] and isset($recs_members[$rec['member_id']])) $recs[$i]['_member_name']=$recs_members[$rec['member_id']] ;
      if ($rec['doctor_id'] and isset($recs_members[$rec['doctor_id']])) $recs[$i]['_doctor_name']=$recs_members[$rec['doctor_id']] ;
      if ($rec['personal_id'] and isset($recs_drivings[$rec['personal_id']])) $recs[$i]['_personal_driving']=$recs_drivings[$rec['personal_id']] ;
      if ($rec['car_id'] and isset($recs_cars[$rec['car_id']])) $recs[$i]['_car_model']=$recs_cars[$rec['car_id']] ;
      $this->prepare_public_info_to_TO($recs[$i]) ;
    }
    //if (_IS_SYSTEM_IP) print_2x_arr($recs) ;
    return($recs) ;
  }

  function create_put_list($to_id,$options=array())
  {
      $filter=['to_id'=>$to_id];

      $options['pdf_options']='-T 0 -B 0';

      $res=DOCS()->doc_create('rmt/doc_put_list',$filter,$options) ;

      damp_array($res['result_convert']);

      echo $res['result_convert']['PDF_file_name_link'].'<br>';

      return;
      set_time_point('get_TO_by_id') ;
      //if (!$rec_TO['e_data'])
      if ($options['set_e_data'])
      {  $s_data=getdate($rec_TO['c_data']) ;
         $rec_TO['e_data']=mktime($s_data['hours'],$s_data['minutes'],0,$s_data['mon'],$s_data['mday']+$options['set_e_data'],$s_data['year']);
         update_rec_in_table($this->table_name,array('e_data'=>$rec_TO['e_data']),'pkey='.$to_id) ;
      }
      set_time_point('set_e_data') ;
      $rec_member=ACCOUNTS()->get_member_by_id($rec_TO['member_id']) ;
      set_time_point('get_member_by_id') ;
      $doc_id=ESMO_REPORTS()->reg_doc(array('obj_name'=>'Путевой лист '.$rec_member['_ext_info']['seria_PL'],
                                    'obj_reffer'=>$rec_TO['_reffer'],
                                    'member_id'=>$rec_TO['member_id'],
                                    'personal_id'=>$rec_TO['personal_id']
                                    ),
                              'PL',
                              $rec_member['_ext_info']['seria_PL']
                         ) ;
      set_time_point('reg_doc') ;

     $doc_number=ESMO_REPORTS()->get_doc_number($doc_id) ;
      set_time_point('get_doc_number') ;
     update_rec_in_table($this->table_name,array('doc_number'=>$doc_number),'pkey='.$to_id) ; // обновляем номер документа в записи по ТО, так как он будет проставлен на документе
      set_time_point('set_doc_number') ;

     include_once(_DIR_TO_ROOT."/AddOns/MPDF57/mpdf.php");
      set_time_point('include_MPDF57') ;
     $mpdf = new mPDF('utf-8', 'A5', '8', '', 0, 0, 0, 0, 0, 0); /*задаем формат, отступы и.т.д.*/
      set_time_point('create mPDF') ;
     $mpdf->charset_in = 'UTF-8'; /*не забываем про русский*/

     //$stylesheet = file_get_contents(_DIR_TO_CLASS.'/style.css'); /*подключаем css*/
     $stylesheet = file_get_contents(_DIR_TO_ROOT.'/style_pdf.css'); /*подключаем css*/
     //$mpdf->WriteHTML($stylesheet, 1);

      $mpdf->list_indent_first_level = 0;
      //$mpdf->WriteHTML($html, 2); /*формируем pdf*/

     //$mpdf->WriteHTML('<p>This should print on an A4 (portrait) sheet</p>');
     //$mpdf->WriteHTML('<tocpagebreak sheet-size="A4-L" toc-sheet-size="A5" toc-preHTML="This ToC should print on an A5 sheet" />');

     // внедряем в PDF шаблоны путеового листа, которые заполняем через скрипт
     $mpdf->WriteHTML('<img src="/cab/rmt/print/put_list_n1.jpg?to_id='.$to_id.'"/>');
     $mpdf->WriteHTML('<img src="/cab/rmt/print/put_list_n2.jpg?to_id='.$to_id.'"/>');

     //$mpdf->WriteHTML('<tocentry content="A4 landscape" /><p>This page appears just after the ToC and should print on an A4 (landscape) sheet</p>');
     //$mpdf->WriteHTML('<tocentry content="A4 landscape" /><p>This page appears just after the ToC and should print on an A4 (landscape) sheet</p>');
     //$mpdf->WriteHTML('<pagebreak sheet-size="A5-L" />');
     //$mpdf->WriteHTML($html);

      //$mpdf->Output($name.'.pdf', 'I');
      $doc_name='PL_'.$rec_member['_ext_info']['seria_PL'].'_'.$doc_number.'.pdf' ;
      $doc_dir=_DIR_TO_ROOT.'/docs/'.$doc_name ;
      $doc_url='http://'._MAIN_DOMAIN.'/docs/'.$doc_name ;
      $mode=($options['mode'])? $options['mode']:'F' ;
      $mpdf->Output($doc_dir,$mode);
      set_time_point('Output') ;
      ESMO_REPORTS()->update_doc($doc_id,
                      array('obj_name'=>'Путевой лист '.$rec_member['_ext_info']['seria_PL'].' № '.$doc_number,
                            'doc_name'=>$doc_name,
                            )
                       ) ;
      set_time_point('update_doc') ;
      update_rec_in_table($this->table_name,array('doc_name'=>$doc_name,'doc_id'=>$doc_id,'doc_number'=>$doc_number),'pkey='.$to_id) ;
      set_time_point('set doc name') ;
      return($doc_url) ;
  }

}

?>
