<?php
class i_upload_persons2
{ public $rec_member  ;
  public $client ;

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


  function exec()
  { ob_start() ;
    $XML_cont = file_get_contents("php://input");
    if (!$XML_cont) $XML_cont=file_get_contents(_DIR_EXT.'/esmo_gateway/demo/'.$_GET['check_file']) ;

	$result=$this->upload_persons($XML_cont) ;
      
    adding_rec_to_table('obj_site_post_log',array('obj_name'=>'upload_persons','IP'=>$_SERVER['REMOTE_ADDR'],'result'=>$result,'clss'=>362),array('debug'=>0)) ;
	if (_sizeof($result)) foreach($result as $key=>$value) echo $key.'='.$value."\n" ;

    $debug=ob_get_clean() ; echo $debug  ;
    LOGS()->reg_log('upload_persons',nl2br($debug)) ;
  }



  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') ;
       $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) ;
       $usl_parent=(_sizeof($arr_parent_ids))?   ' and parent in ('.implode(',',$arr_parent_ids).')':'' ;
       execSQL_update('update obj_site_personals set temp=1 where clss=211 '.$usl_parent) ;
         //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->uid ;
               if (isset($item->Name)) $rec['obj_name']=(string)$item->Name ;
	           if (isset($item->dr)) { $rec['dr']=(string)$item->Dr ; $rec['age']=ENGINE()->get_age_by_dr($rec['dr']) ; }
	           if (isset($item->propusk)) $rec['propusk']=(string)$item->Propusk ;

	            if (isset($item->tab_number)) $rec['tab_number']=(string)$item->TabNumber ;
	            if (isset($item->permit)) $rec['permit']=str_replace(' ','',(string)$item->Permit) ;
	            if (isset($item->driving)) $rec['driving']=str_replace(' ','',(string)$item->DriverLicense) ; // надо удалить все пробелы из строки  $driving=str_replace(' ','',$driving) ;
	            if (isset($item->s_medspravka)) { $rec['s_medspravka']=strtotime((string)$item->DateMedSpravka) ; if (!$rec['s_medspravka']) $rec['s_medspravka']=0 ;}
	            if (isset($item->pol)) $rec['pol']=((string)$item->Pol=='М' or (string)$item->Pol=='М')? 0:1 ;
               //$rec['adres']=(string)$item->Adres ;

               //$rec['full_access']=(string)$item->FullAccess ;
               //if (!$rec['full_access']) $rec['full_access']=0 ;

	            if (isset($item->Org)) { $rec['_org_name']=(string)$item->Org ; if (!$rec['_org_name']) $rec['_org_id']=$this->client->main_org_id;}
	            if (isset($item->Structure)) { $rec['_otdel_name']=(string)$item->Structure ;        }
	            if (isset($item->Working)) { $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) ;
             //$this->client->id=0 ;
            //$result=PERSONAL()->append_personal_from_array($members,array('key_fields'=>'uid,client_id','client_id'=>$this->client->id)) ;
            $result=PERSONAL()->append_personal_from_array($members,array('key_fields'=>'uid','client_id'=>0)) ;

            //$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 '.$usl_parent.' 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() ;
         //PERSONAL()->update_levels_parents() ;

         $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)) ;
         echo $text ;
         //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)) ;
   }



}



?>
