<?php
include_once("c_rmt.php");
class c_page_cab_rmt_upload_rosinfoteh extends c_page_cab_rmt
{

 public $h1='Загрузка списка сотрудников' ;

 function block_main()
 { $this->page_title() ;
   if (!$this->cmd_exec_result['no_default_panel']) $this->panel_upload_promt() ;
 }

 function panel_upload_promt()
 { ?><div id="panel_upload_promt"><form action="" method="POST"><input type="hidden" name="cmd" value="upload_personal">
      <p>Загрузка сотрудников Росинфотех<p>
      <div class=buttons><input type="submit" value="Импорт сотрудников" class=button_green></div>
     </form>
     <form action="" method="POST"><input type="hidden" name="cmd" value="upload_image">
      <p>Загрузка изображений Росинфотех<p>
      <div class=buttons><input type="submit" value="Импорт фото" class=button_green></div>
     </form>
     <!--<form action="" method="POST"><input type="hidden" name="cmd" value="delete_dubl">
      <p>Удалить дубликаты<p>
      <div class=buttons><input type="submit" value="Удалить дубликаты" class=button_green></div>
     </form>-->

    </div><?
 }

 function CMD_delete_dubl()
 { $recs=execSQL('select distinct(obj_name),count(pkey) as cnt,pkey as id from obj_site_personals where clss=208 group by obj_name') ;
   if (_sizeof($recs)) foreach($recs as $name=>$rec) if ($rec['cnt']>1)
   {   ?><h2><?echo $name?></h2><?
       $org_ids=execSQL_line('select pkey from obj_site_personals where clss=208 and obj_name="'.addslashes($name).'" and pkey!='.$rec['id']) ;
       // переводим всех сотрудников в одно подразделение
       if (_sizeof($org_ids))
       { execSQL_update('update obj_site_personals set parent='.$rec['id'].' where clss=211 and parent in ('.implode(',',$org_ids).')') ;
         echo 'Переносим сотрудников из дубликатов<br>' ;
         // проверяем сколько сотрудников осталось в дубликатах
         $cnt=execSQL_value('select count(pkey) from obj_site_personals where clss=211 and parent in ('.implode(',',$org_ids).')') ;
         echo 'В дубликатах осталось '.$cnt.' сотрудников<br>' ;
         if (!$cnt)
         { execSQL_update('delete from obj_site_personals where clss=208 and pkey in ('.implode(',',$org_ids).')') ;
           echo 'Дубликаты удалены<br>' ;
         }
       }

   }


 }


 function upload_image()
 {  include_once(_DIR_TO_ENGINE.'/admin/i_admin_system.php') ;
    $cnt=execSQL_value('select count(pkey) from obj_site_personals where clss=211 and temp=2') ;
    ?><h2>В очереди на загрузку фото <?echo $cnt?> записей по сотрудникам</h2><?
    $recs=execSQL('select pkey,obj_name,ext_info from obj_site_personals where clss=211 and temp=2 order by pkey limit 50') ;
    if (_sizeof($recs))
    { $recs_images=execSQL('select pkey as id,parent,obj_name from obj_site_personals_image where parent in ('.implode(',',array_keys($recs)).') and obj_name!=""') ;
      $recs_images_parent=group_by_field('parent',$recs_images,'obj_name') ;
      //damp_array($recs_images_parent) ;
        foreach($recs as $rec)
        { $info=array() ;
          ?><h2><?echo $rec['obj_name']?></h2><?
          if ($rec['ext_info']) $info=unserialize($rec['ext_info']) ;
          if (_sizeof($info))
          { if ($info['UlrPhoto']       and !isset($recs_images_parent[$rec['pkey']][basename($info['UlrPhoto'])]))        obj_upload_image_by_href($rec['_reffer'],$info['UlrPhoto'],array('view_upload'=>1,'finfo'=>array('alt'=>'Photo'))) ;
            if ($info['UlrPhotoDriver'] and !isset($recs_images_parent[$rec['pkey']][basename($info['UlrPhotoDriver'])]))  obj_upload_image_by_href($rec['_reffer'],$info['UlrPhotoDriver'],array('view_upload'=>1,'finfo'=>array('alt'=>'PhotoDriver'))) ;
            if ($info['UlrPhotoCar1']   and !isset($recs_images_parent[$rec['pkey']][basename($info['UlrPhotoCar1'])]))    obj_upload_image_by_href($rec['_reffer'],$info['UlrPhotoCar1'],array('view_upload'=>1,'finfo'=>array('alt'=>'PhotoCar1'))) ;
            if ($info['UlrPhotoCar2']   and !isset($recs_images_parent[$rec['pkey']][basename($info['UlrPhotoCar2'])]))    obj_upload_image_by_href($rec['_reffer'],$info['UlrPhotoCar2'],array('view_upload'=>1,'finfo'=>array('alt'=>'PhotoCar2'))) ;
            if ($info['UlrPhotoCar3']   and !isset($recs_images_parent[$rec['pkey']][basename($info['UlrPhotoCar3'])]))    obj_upload_image_by_href($rec['_reffer'],$info['UlrPhotoCar3'],array('view_upload'=>1,'finfo'=>array('alt'=>'PhotoCar3'))) ;
          }
          execSQL_update('update obj_site_personals set temp=0 where pkey='.$rec['pkey']) ;
        }

    }
    $cnt=execSQL_value('select count(pkey) from obj_site_personals where clss=211 and temp=2') ;
    ?><h2>В очереди на загрузку фото <?echo $cnt?> записей по сотрудникам</h2><?

 }


 function upload_personal()
  { $cnt_add=0 ; $cnt_update=0 ;  $org_add=0 ; $org_exsist=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 set temp=1 where clss in (211,208)') ;
    ?><h2>Импорт списка сотрудников</h2><?
      ob_start() ;
      $XML_source=file_get_contents(_DIR_TO_ROOT.'/import/drivers.xml') ;
      $XML = new SimpleXMLElement($XML_source);
      //svar_dump($XML) ;
         $i=0 ;
         foreach ($XML->Car as $Car)
         {  $rec=array() ;
            $rec['uuid']=(string)$Car->Uuid ;
            $rec['RealClid']=(string)$Car->RealClid ;
            $rec['RealName']=(string)$Car->RealName ;

            if (_sizeof($Car->Tariff)) foreach($Car->Tariff as $Tariff) $rec['tarifs'][]=(string)$Tariff  ;

            $rec['UlrPhotoDriver']=(string)$Car->UlrPhotoDriver ;
            $rec['UlrPhotoCar1']=(string)$Car->UlrPhotoCar1 ;
            $rec['UlrPhotoCar2']=(string)$Car->UlrPhotoCar2 ;
            $rec['UlrPhotoCar3']=(string)$Car->UlrPhotoCar3 ;

            if (_sizeof($Car->DriverDetails->children())) foreach($Car->DriverDetails->children() as $name=>$value) $rec['DriverDetails'][$name]=(string)$value  ;
            if (_sizeof($Car->CarDetails->children())) foreach($Car->CarDetails->children() as $name=>$value) if ($name!='Require') $rec['CarDetails'][$name]=(string)$value  ;
            if (_sizeof($Car->CarDetails->Require)) foreach($Car->CarDetails->Require as $Require) foreach($Require->attributes() as $name => $value) $rec['CarDetails']['Require'][(string)$value]=(string)$Require  ;
            if ($Car->Rating and _sizeof($Car->Rating->children())) foreach($Car->Rating->children() as $name=>$value) $rec['Rating'][$name]=(string)$value  ;

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

            // преобразовываем массив для записи в БД
            $data=array() ;
            $data['obj_name']=$rec['DriverDetails']['DisplayName'] ;
            $data['phone']=$rec['DriverDetails']['Phone'] ;
            $data['age']=$rec['DriverDetails']['Age'] ;
            $data['permit']=$rec['DriverDetails']['Permit'] ;
            $data['driving']=$rec['DriverDetails']['DriverLicense'] ;
            $data['uid']=$rec['uuid'] ;


            $data['ext_info']=$rec ;
             /*
            //$data['ext_info']['car']['uuid']=$rec['uuid'] ;
            $data['ext_info']['car']['RealClid']=$rec['RealClid'] ;
            //$data['ext_info']['car']['RealName']=$rec['RealName'] ;
            $data['ext_info']['car']['tarifs']=$rec['tarifs'] ;
            $data['ext_info']['CarDetails']=$rec['CarDetails'] ;
            $data['ext_info']['Rating']=$rec['Rating'] ;
            $data['ext_info']['UlrPhoto']=$rec['UlrPhoto'] ;
            $data['ext_info']['UlrPhotoDriver']=$rec['UlrPhotoDriver'] ;
            $data['ext_info']['UlrPhotoCar1']=$rec['UlrPhotoCar1'] ;
            $data['ext_info']['UlrPhotoCar2']=$rec['UlrPhotoCar2'] ;
            $data['ext_info']['UlrPhotoCar3']=$rec['UlrPhotoCar3'] ;
            */

            $exist_rec=execSQL_van('select pkey,ext_info from obj_site_personals where uid="'.$rec['uuid'].'"') ;
            if (!$exist_rec['pkey'])
            {  $data['clss']=211 ;
               $data['parent']=$org_id ;
               $data['temp']=2 ;    // запись будет поставлена на докачку фото
               $id=adding_rec_to_table('obj_site_personals',$data) ;
               update_rec_in_table('obj_site_personals',array('tab_number'=>'tn'.$id,'propusk'=>'pi'.$id),'pkey='.$id) ;
               echo '<div class=green>Добавлена запись по '.$data['obj_name'].'</div>' ;
               $cnt_add++ ;
            }
            else
            {  $info=unserialize($exist_rec['ext_info']) ;
               // если изменились записи по фото - ставим флаг для фоновой загрузки
               $data['temp']=0 ;
               if ($info['UlrPhoto']!=$data['ext_info']['UlrPhoto'])              $data['temp']=2 ;
               if ($info['UlrPhotoDriver']!=$data['ext_info']['UlrPhotoDriver'])  $data['temp']=2 ;
               if ($info['UlrPhotoCar1']!=$data['ext_info']['UlrPhotoCar1'])      $data['temp']=2 ;
               if ($info['UlrPhotoCar2']!=$data['ext_info']['UlrPhotoCar2'])      $data['temp']=2 ;
               if ($info['UlrPhotoCar3']!=$data['ext_info']['UlrPhotoCar3'])      $data['temp']=2 ;
               update_rec_in_table('obj_site_personals',$data,'pkey='.$exist_rec['pkey']) ;
               echo 'Обновлена запись по '.$data['obj_name'].'<br>' ;
               $cnt_update++ ;

            }


             $i++ ; //if ($i==20) break ;

         }
      $stats=execSQL_row('select temp,count(pkey) from obj_site_personals where clss=211 group by temp') ;
      execSQL_update('update obj_site_personals set enabled=0 where clss in (211,208) and temp=1') ;
      execSQL_update('update obj_site_personals set enabled=1 where clss in (211,208) and temp in (0,2)') ;
      $cnt_disabled2=execSQL_value('select count(pkey) from obj_site_personals where clss=211 and enabled=0') ;
      $log=ob_get_clean() ;
      $log_url=ESMO()->reg_file_log('import_rosinfoteh',$log) ;
      ob_start() ;
      $res['Загружено из файла XLS']=$i ;
      $res['Обновлено автопарков в базе']=$org_exsist ;
      $res['Добавлено автопарков в базу']=$org_add ;
      $res['Обновлено сотрудников в базе']=$cnt_update ;
      $res['Добавлено сотрудников в базу']=$cnt_add ;
      $res['Выбыло сотрудников']=($cnt_disabled2-$cnt_disabled) ;
      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) ;

      ESMO()->reg_log('import_rosinfoteh',$report,array('data'=>$res)) ;



    // print_2x_arr($recs) ;


  }

}



?>
