<?php
include_once(_DIR_EXT.'/HTML/c_page_TXT.php') ;
include_once('i_client.php') ;
class c_page_client_XML extends c_page_txt
{ public $rec_member  ;
  public $client ;

  function c_page_XML()
  {
    //damp_array(PERSONAL()) ;
    //damp_array(ESMO()) ;
  }


  function body()
  { set_time_point('start SERVER POST IN') ;  //return ;
    $time_rec=time() ;
    ob_start() ;
    $XML_cont = file_get_contents("php://input");
    if (!$XML_cont) $XML_cont=file_get_contents(_DIR_EXT.'/aspmo_client/docs/'.$_GET['check_file']) ;
    $error='' ; $result=array() ;
    if ($_GET['client_id'])
    {   $this->rec_member=ACCOUNTS()->get_member_by_id($_GET['client_id']) ;
        if (!$this->rec_member['pkey']) $error='member_not_found' ;
        else if($this->rec_member['rol']!=6) $error='member_is_not_client' ;
        else if(!$this->rec_member['enabled']) $error='client_disabled' ;

    }
    if (!$error)
    {  $this->client = new c_client($this->rec_member['pkey']) ;

       switch($_GET['mode'])
       { case 'upload_cars': $result=$this->upload_cars($XML_cont) ; break ;
         case 'upload_drivers': $result=$this->upload_drivers($XML_cont) ; break ;
         case 'upload_persons': $result=$this->upload_persons($XML_cont) ; break ;

       }
       adding_rec_to_table('obj_site_post_log',array('obj_name'=>$_GET['mode'],'IP'=>$_SERVER['REMOTE_ADDR'],'result'=>$result,'clss'=>362,'client_id'=>$_GET['client_id']),array('debug'=>0)) ;

       if (_sizeof($result)) foreach($result as $key=>$value) echo $key.'='.$value."\n" ;
    }
    if ($error) echo 'ERROR: '.$error ;
    $debug=ob_get_clean() ; echo $debug  ;
    LOGS()->reg_log($_GET['mode'],nl2br($debug),array('member_id'=>$this->client->id)) ;
  }


  function upload_cars($XML_source)
     { include_once(_DIR_TO_ENGINE.'/admin/i_admin_system.php') ;
       $cnt_add=0 ; $cnt_update=0 ;  $org_add=0 ; $org_exsist=0 ;   $cnt_img_to_upload=0 ; $cnt_img_to_delete=0 ; $cnt_img_exist=0 ; $cars_coflict=0 ;
       //$arr_org=execSQL_row('select pkey,obj_name from obj_site_personals where clss=208') ;
       //$cnt_disabled=execSQL_value('select count(pkey) from obj_site_personals where clss=211 and enabled=0') ;
       execSQL_update('update obj_site_personals_cars set temp=1 where clss=361 and parent="'.$this->client->main_org_id.'"') ;
         ob_start() ;
         $XML = new SimpleXMLElement($XML_source);
         if(is_object($XML))
         {  $i=0 ;
            foreach ($XML->Car as $Car)
            {  $rec=array() ; $arr_img_names=array() ;//$arr_img_names[]='' ;
               //$rec['client_id']=$this->client->id ;
               $rec['uid']=(string)$Car->Uuid ;
               $rec['obj_name']=str_replace(' ','',(string)$Car->CarNumber) ;
               $car_number=(string)$Car->CarNumber ;
               $car_number=str_replace(array("'",'"','(',')',' ',"\n"),'',$car_number) ;
               $rec['obj_name']=ENGINE()->translit2($car_number) ;
               if (!$rec['uid']) $rec['uid']=$rec['obj_name'] ;
               $rec['model']=(string)$Car->Marka.' '.(string)$Car->Model ;
               $rec['permit']=(string)$Car->License ;
               $rec['year']=(string)$Car->Year ;
               $rec['e_osago']=strtotime((string)$Car->OSAGO) ;
               $rec['e_sts']=strtotime((string)$Car->STS) ;
               $rec['e_to']=strtotime((string)$Car->TO) ;
               $rec['enabled']=1 ;
               $rec['temp']=0 ;
               if (_sizeof($Car->Ext_info) and _sizeof($Car->Ext_info->children())) foreach($Car->Ext_info->children() as $name=>$value) $rec['ext_info'][$name]=(string)$value  ;
               if (_sizeof($Car->Images_url) and _sizeof($Car->Images_url->children())) foreach($Car->Images_url->children() as $name=>$value)
               { $rec['upl_img']['url'][]=(string)$value  ;
                 $arr_img_names[]=basename((string)$value) ;
               }

               $exist_rec=execSQL_van('select pkey,parent,ext_info from obj_site_personals_cars where obj_name="'.$rec['obj_name'].'" and enabled=1') ;
               if (!$exist_rec['pkey'])
               {  $rec['clss']=361 ;
                  $rec['parent']=$this->client->main_org_id ;
                  adding_rec_to_table('obj_site_personals_cars',$rec) ;
                  $cnt_add++ ;
                  $cnt_img_to_upload+=_sizeof($rec['upl_img']['url']) ;
               }
               else if ($exist_rec['parent']!=$this->client->main_org_id)
               { echo 'notife: car "'.$rec['obj_name'].'" is upload to "'.PERSONAL()->get_name_by_id($exist_rec['parent']).'"<br>' ;
                 $cars_coflict++ ;
               }
               else
               {  // надо проверить уже закачанные фото
                  // фото, которые уже закачаны - удаляет с заказчки
                  // фото, которые уже закачаны и нет в XML - удаляем с объекта
                  $arr_images=execSQL('select pkey,indx,obj_name,file_name from obj_site_personals_cars_image where parent="'.$exist_rec['pkey'].'"') ;
                  if (_sizeof($arr_images)) foreach($arr_images as $rec_image)
                  {   $key=array_search($rec_image['obj_name'],$arr_img_names) ;
                      if ($key!==false)
                      { unset($rec['upl_img']['url'][$key]) ; // фото есть в объекте и в XML - удаляем фото из массива загрузки
                        $cnt_img_exist++ ;
                      }
                      else // фото надо удалить из объекта, его нет в XML
                      {  execSQL_update('delete from obj_site_personals_cars_image where pkey='.$rec_image['pkey']) ;
                         clear_obj_img($rec_image['tkey'],$rec_image['file_name']) ;
                         //damp_array($rec_image,1,-1) ;
                         $cnt_img_to_delete++ ;
                      }
                  }
                  if (!_sizeof($rec['upl_img']['url'])) unset($rec['upl_img']['url']) ;
                  if (!_sizeof($rec['upl_img'])) unset($rec['upl_img']) ;

                  if ($exist_rec['e_osago'] and !$rec['e_osago']) $rec['e_osago']=$exist_rec['e_osago'] ;
                  if ($exist_rec['e_sts'] and !$rec['e_sts']) $rec['e_sts']=$exist_rec['e_sts'] ;
                  if ($exist_rec['e_to'] and !$rec['e_to']) $rec['e_to']=$exist_rec['e_to'] ;

                  update_rec_in_table('obj_site_personals_cars',$rec,'pkey='.$exist_rec['pkey']) ;
                  $cnt_update++ ;
                  $cnt_img_to_upload+=_sizeof($rec['upl_img']['url']) ;
               }
               //damp_array($rec,1,-1) ;
               $i++ ;

            }
         execSQL_update('update obj_site_personals_cars set enabled=0 where clss=361 and parent="'.$this->client->main_org_id.'" and temp=1') ;
         execSQL_update('update obj_site_personals_cars set enabled=1 where clss=361 and parent="'.$this->client->main_org_id.'" and temp=0') ;
         $stats=execSQL_row('select enabled,count(pkey) from obj_site_personals_cars where clss=361 and parent="'.$this->client->main_org_id.'" group by enabled') ;
         //$cnt_disabled2=execSQL_value('select count(pkey) from obj_site_personals where clss=211 and enabled=0') ;
         //$log=ob_get_clean() ;
         //$log_url=LOGS()->reg_file_log('import_rosinfoteh',$log) ;
         //ob_start() ;
         $res['personal_count']=$i ;
         $res['personal_update']=$cnt_update ;
         $res['personal_adding']=$cnt_add ;
         $res['personal_enabled']=($stats[1])? $stats[1]:0 ;
         $res['personal_disabled']=($stats[0])? $stats[0]:0 ;
         $res['img_exist']=$cnt_img_exist ;
         $res['img_to_upload']=$cnt_img_to_upload ;
         $res['img_to_delete']=$cnt_img_to_delete ;
         //$res['cars_delete']=;
         //if ($stats[2]) echo '<strong>Необходимо обновить фото у '.$stats[2].' сотрудников</strong><br>' ;
         //echo 'Лог: <a href="'.$log_url.'" target=_blank>Скачать</a><br>'  ;
         //$report=ob_get_clean() ;
         //echo $report ;
         //damp_array($res,1,-1) ;
         }
         else $res=array('error'=>'not_valid_XML_source') ;
         $text=ob_get_clean() ;

         LOGS()->reg_log('XML_import_personal',$text,array('data'=>$res,'member_id'=>$this->client->id)) ;
         return($res) ;


       // print_2x_arr($recs) ;


     }


  function upload_drivers($XML_source)
     { include_once(_DIR_TO_ENGINE.'/admin/i_admin_system.php') ;
       $cnt_add=0 ; $cnt_update=0 ;  $org_add=0 ; $org_exsist=0 ;   $cnt_img_to_upload=0 ; $cnt_img_to_delete=0 ; $cnt_img_exist=0 ; $cars_coflict=0 ;
       //$arr_org=execSQL_row('select pkey,obj_name from obj_site_personals where clss=208') ;
       //$cnt_disabled=execSQL_value('select count(pkey) from obj_site_personals where clss=211 and enabled=0') ;
       $parents_ids=PERSONAL()->tree[$this->client->main_org_id]->get_list_child() ;
       $arr_org=execSQL_row('select pkey,obj_name from obj_site_personals where clss=208 and parent='.$this->client->main_org_id) ;
       //echo 'main_org_id='.$this->client->main_org_id.'<br>' ; echo '$parents_ids='.$parents_ids.'<br>' ;
       execSQL_update('update obj_site_personals set temp=1 where clss=211 and parent in ('.$parents_ids.')') ; // включаем временный флаг на организациях
         //ob_start() ;
         $XML = new SimpleXMLElement($XML_source);
         if(is_object($XML))
         {  $i=0 ;
            foreach ($XML->Driver as $item)
            {  $rec=array() ; $arr_img_names=array() ;//$arr_img_names[]='' ;
               $rec['client_id']=$this->client->id ;
               $rec['uid']=(string)$item->Uuid ;
               $rec['obj_name']=(string)$item->Name ;
               $rec['phone']=(string)$item->Phone ;
               $rec['dr']=(string)$item->Dr ;
               list($rec['dr'],$rec['age'])=$this->get_dr_age((string)$item->Dr) ;

               $rec['permit']=str_replace(' ','',(string)$item->Permit) ;
               $driving=(string)$item->DriverLicense ;
               $driving=str_replace(' ','',$driving) ;
               $rec['driving']=$driving ;
               $rec['s_medspravka']=strtotime((string)$item->DateMedSpravka) ;
               $rec['pol']=((string)$item->Pol=='М' or (string)$item->Pol=='М')? 0:1 ;
               $otdel=(string)$item->Structure ;
               $rec['enabled']=1 ;
               $rec['temp']=0 ;
               $rec['clss']=211 ;
               if ($item->Images_url and _sizeof($item->Images_url->children())) foreach($item->Images_url->children() as $name=>$value)
               { $rec['upl_img']['url'][]=(string)$value  ;
                 $arr_img_names[]=basename((string)$value) ;
               }

               // проверяем автопарк  - если новая - добавляем в Базу как подразделение, в корень
               if ($otdel)
               {   if (!$org_id=array_search($otdel,$arr_org))
                   {  $org_id=adding_rec_to_table('obj_site_personals',array('read_only'=>1,'obj_name'=>addslashes(trim($otdel)),'clss'=>208,'parent'=>$this->client->main_org_id)) ;
                      $arr_org[$org_id]=$otdel ;
                      $org_add++ ;
                      echo '<div class=green>Добавлен новый автопарк "<strong>'.$otdel.'</strong>"</div>' ;
                   }
                   else
                   {  update_rec_in_table('obj_site_personals',array('temp'=>0,'enabled'=>1,'read_only'=>1),'pkey='.$org_id) ;

                   }
                   $rec['parent']=$org_id ;
               }  else $rec['parent']=$this->client->main_org_id ;

               $exist_rec=execSQL_van('select pkey,parent,ext_info from obj_site_personals where uid="'.$rec['uid'].'" and parent in ('.$parents_ids.')') ;
               if (!$exist_rec['pkey'])
               {  $new_id=adding_rec_to_table('obj_site_personals',$rec) ;
                  update_rec_in_table('obj_site_personals',array('propusk'=>$new_id),'pkey='.$new_id) ;
                  $cnt_add++ ;
                  $cnt_img_to_upload+=_sizeof($rec['upl_img']['url']) ;
               }
               else
               {  // надо проверить уже закачанные фото
                  // фото, которые уже закачаны - удаляет с заказчки
                  // фото, которые уже закачаны и нет в XML - удаляем с объекта
                  $arr_images=execSQL('select pkey,indx,obj_name,file_name from obj_site_personals_image where parent="'.$exist_rec['pkey'].'"') ;
                  if (_sizeof($arr_images)) foreach($arr_images as $rec_image)
                  {   $key=array_search($rec_image['obj_name'],$arr_img_names) ;
                      if ($key!==false)
                      { unset($rec['upl_img']['url'][$key]) ; // фото есть в объекте и в XML - удаляем фото из массива загрузки
                        $cnt_img_exist++ ;
                      }
                      else // фото надо удалить из объекта, его нет в XML
                      {  execSQL_update('delete from obj_site_personals_image where pkey='.$rec_image['pkey']) ;
                         clear_obj_img($rec_image['tkey'],$rec_image['file_name']) ;
                         damp_array($rec_image,1,-1) ;
                         $cnt_img_to_delete++ ;
                      }
                  }
                  if (!_sizeof($rec['upl_img']['url'])) unset($rec['upl_img']['url']) ;
                  if (!_sizeof($rec['upl_img'])) unset($rec['upl_img']) ;

                  if ($exist_rec['s_medspravka'] and !$rec['s_medspravka']) $rec['s_medspravka']=$exist_rec['s_medspravka'] ;

                  update_rec_in_table('obj_site_personals',$rec,'pkey='.$exist_rec['pkey']) ;
                  $cnt_update++ ;
                  $cnt_img_to_upload+=_sizeof($rec['upl_img']['url']) ;
               }
               //damp_array($rec,1,-1) ;
               $i++ ;

            }
         // выключаем тех водителей, которых не было в списке. Включаем всех, кто был в списке
         execSQL_update('update obj_site_personals set enabled=0 where clss=211 and parent in ('.$parents_ids.') and temp=1') ;
         execSQL_update('update obj_site_personals set enabled=1 where clss=211 and parent in ('.$parents_ids.') and temp=0') ;
         $stats=execSQL_row('select enabled,count(pkey) from obj_site_personals where clss=211 and parent in ('.$parents_ids.') group by enabled') ;
         //$cnt_disabled2=execSQL_value('select count(pkey) from obj_site_personals where clss=211 and enabled=0') ;
         //$log=ob_get_clean() ;
         //$log_url=LOGS()->reg_file_log('import_rosinfoteh',$log) ;
         //ob_start() ;
         $res['driver_count']=$i ;
         $res['driver_update']=$cnt_update ;
         $res['driver_adding']=$cnt_add ;
         $res['driver_enabled']=($stats[1])? $stats[1]:0 ;
         $res['driver_disabled']=($stats[0])? $stats[0]:0 ;
         $res['strusture_add']=$org_add ;
         $res['img_exist']=$cnt_img_exist ;
         $res['img_to_upload']=$cnt_img_to_upload ;
         $res['img_to_delete']=$cnt_img_to_delete ;
         //$res['cars_delete']=;
         //if ($stats[2]) echo '<strong>Необходимо обновить фото у '.$stats[2].' сотрудников</strong><br>' ;
         //echo 'Лог: <a href="'.$log_url.'" target=_blank>Скачать</a><br>'  ;
         //$report=ob_get_clean() ;
         //echo $report ;

         }
         else $res=array('error'=>'not_valid_XML_source') ;


         //LOGS()->reg_log('import_rosinfoteh',$report,array('data'=>$res)) ;
         return($res) ;


       // print_2x_arr($recs) ;


     }

  function upload_persons($XML_source)
     { include_once(_DIR_TO_ENGINE.'/admin/i_admin_system.php') ;
       ob_start() ;
       $cnt_add=0 ; $cnt_update=0 ;  $org_add=0 ; $org_exsist=0 ;   $cnt_img_to_upload=0 ; $cnt_img_to_delete=0 ; $cnt_img_exist=0 ; $members=array() ;
       //$arr_org=execSQL_row('select pkey,obj_name from obj_site_personals where clss=208') ;
       //$cnt_disabled=execSQL_value('select count(pkey) from obj_site_personals where clss=211 and enabled=0') ;

       $orgs_ids=execSQL_line('select pkey from obj_site_personals where clss=207 and client_id='.$this->client->id) ;
       $otdel_ids=execSQL_line('select pkey from obj_site_personals where clss=208 and parent in ('.implode(',',$orgs_ids).')') ;
       $arr_parent_ids=array_merge($orgs_ids,$otdel_ids) ;
       execSQL_update('update obj_site_personals set temp=1 where clss=211 and parent in ('.implode(',',$arr_parent_ids).')') ;
         //ob_start() ;
         $XML = new SimpleXMLElement($XML_source);
         if(is_object($XML))
         {  $i=0 ;
            foreach ($XML->Person as $item)
            {  $rec=array() ; $arr_img_names=array() ;//$arr_img_names[]='' ;
               $rec['client_id']=$this->client->id ;
               $rec['uid']=(string)$item->Uuid ;
               $rec['obj_name']=(string)$item->Name ;
               $rec['phone']=(string)$item->Phone ;
               $rec['dr']=(string)$item->Dr ;
               $rec['age']=ENGINE()->get_age_by_dr($rec['dr']) ;
               $rec['propusk']=(string)$item->Propusk ;
               $rec['tab_number']=(string)$item->TabNumber ;
               $rec['permit']=str_replace(' ','',(string)$item->Permit) ;
               $rec['driving']=str_replace(' ','',(string)$item->DriverLicense) ; // надо удалить все пробелы из строки  $driving=str_replace(' ','',$driving) ;
               $rec['s_medspravka']=strtotime((string)$item->DateMedSpravka) ;
               $rec['pol']=((string)$item->Pol=='М' or (string)$item->Pol=='М')? 0:1 ;
               $rec['adres']=(string)$item->Adres ;

               $rec['full_access']=(string)$item->FullAccess ;

               $rec['_org_name']=(string)$item->Org ;
               if (!$rec['_org_name']) $rec['_org_id']=$this->client->main_org_id;
               $rec['_otdel_name']=(string)$item->Structure ;
               $rec['_working_name']=trim((string)$item->Working) ;


               $rec['enabled']=1 ;
               $rec['temp']=0 ;
               $rec['clss']=211 ;
               if ($item->Images_url and _sizeof($item->Images_url->children())) foreach($item->Images_url->children() as $name=>$value)
               { $rec['upl_img']['url'][]=(string)$value  ;
                 $arr_img_names[]=basename((string)$value) ;
               }


                $members[]=$rec ;
                $i++ ;
            }
            //print_2x_arr($members) ;
            $result=PERSONAL()->append_personal_from_array($members,array('key_fields'=>'uid,client_id','client_id'=>$this->client->id)) ;

            //$recs=execSQL('select * from obj_site_personals where client_id='.$this->client->id) ;
            /*
               $exist_rec=execSQL_van('select pkey,parent,ext_info from obj_site_personals where uid="'.$rec['uid'].'"') ;
               if (!$result[1])
               {  //$new_id=adding_rec_to_table('obj_site_personals',$rec) ;
                  //update_rec_in_table('obj_site_personals',array('propusk'=>$new_id),'pkey='.$new_id) ;
                  $cnt_add++ ;
                  $cnt_img_to_upload+=_sizeof($rec['upl_img']['url']) ;
               }
               else
               {  // надо проверить уже закачанные фото
                  // фото, которые уже закачаны - удаляет с заказчки
                  // фото, которые уже закачаны и нет в XML - удаляем с объекта
                  $arr_images=execSQL('select pkey,indx,obj_name,file_name from obj_site_personals_image where parent="'.$exist_rec['pkey'].'"') ;
                  if (_sizeof($arr_images)) foreach($arr_images as $rec_image)
                  {   $key=array_search($rec_image['obj_name'],$arr_img_names) ;
                      if ($key!==false)
                      { unset($rec['upl_img']['url'][$key]) ; // фото есть в объекте и в XML - удаляем фото из массива загрузки
                        $cnt_img_exist++ ;
                      }
                      else // фото надо удалить из объекта, его нет в XML
                      {  execSQL_update('delete from obj_site_personals_image where pkey='.$rec_image['pkey']) ;
                         clear_obj_img($rec_image['tkey'],$rec_image['file_name']) ;
                         damp_array($rec_image,1,-1) ;
                         $cnt_img_to_delete++ ;
                      }
                  }
                  if (!_sizeof($rec['upl_img']['url'])) unset($rec['upl_img']['url']) ;
                  if (!_sizeof($rec['upl_img'])) unset($rec['upl_img']) ;

                  update_rec_in_table('obj_site_personals',$rec,'pkey='.$exist_rec['pkey']) ;
                  $cnt_update++ ;
                  $cnt_img_to_upload+=_sizeof($rec['upl_img']['url']) ;
               }
               //damp_array($rec,1,-1) ;
               $i++ ;
             */


         execSQL_update('update obj_site_personals set enabled=0 where clss=211 and parent in ('.implode(',',$arr_parent_ids).') and temp=1') ;
         execSQL_update('update obj_site_personals set enabled=1 where clss=211 and parent in ('.implode(',',$arr_parent_ids).') and temp=0') ;
         $stats=execSQL_row('select enabled,count(pkey) from obj_site_personals where clss=211 and parent in ('.implode(',',$arr_parent_ids).') group by enabled') ;
         //$cnt_disabled2=execSQL_value('select count(pkey) from obj_site_personals where clss=211 and enabled=0') ;
         //$log=ob_get_clean() ;
         //$log_url=LOGS()->reg_file_log('import_rosinfoteh',$log) ;
         //ob_start() ;
         $res['person_count']=_sizeof($members) ;
         $res['person_update']=$result[0] ;
         $res['person_adding']=$result[1] ;
         $res['person_enabled']=($stats[1])? $stats[1]:0 ;
         $res['person_disabled']=($stats[0])? $stats[0]:0 ;
         $res['strusture_add']=$org_add ;
         $res['img_exist']=$cnt_img_exist ;
         $res['img_to_upload']=$cnt_img_to_upload ;
         $res['img_to_delete']=$cnt_img_to_delete ;
         //$res['cars_delete']=;
         //if ($stats[2]) echo '<strong>Необходимо обновить фото у '.$stats[2].' сотрудников</strong><br>' ;
         //echo 'Лог: <a href="'.$log_url.'" target=_blank>Скачать</a><br>'  ;
         //$report=ob_get_clean() ;
         //echo $report ;
         //damp_array($res,1,-1) ;
         }
         else $res=array('error'=>'not_valid_XML_source') ;

         $text=ob_get_clean() ;
         LOGS()->reg_log('import_XML',$text,array('data'=>$res)) ;
         //damp_array($res,1,-1) ;
         return($res) ;


     }

   // дата идет в формате 01/01/10, переводим в формат обычной даты
   function get_dr_age($str_data)
   {  $str_data=str_replace(array('/','-'),'.',$str_data) ;
      $arr=explode('.',$str_data) ;
      $dr='' ; $age=0 ;
      if (_sizeof($arr)==3)
       { $now_year=(int)date('y') ;
         $_y=(int)$arr[2] ;
         if (strlen($arr[2])==4)  $yaer=$_y ;
         else if ($now_year>$_y)  $yaer=(int)'20'.$arr[2] ;
         else                     $yaer=(int)'19'.$arr[2] ;
         $month=(int)$arr[1] ;
         $day=(int)$arr[0] ;
         $dr=sprintf("%02d.%02d.%04d", $day, $month, $yaer);
         $tt = mktime(0,0,0,$month,$day,date('Y'));   // дата день рождения в этом году
         $now_year=(int)date('Y') ;
         $age=$now_year-$yaer ;
         if (time()<$tt) $age=$age-1 ;
       }
      return(array($dr,$age)) ;
   }



}



?>
