<?php
include_once(_DIR_EXT.'/rmt/i_mrt.php') ;

$__functions['init'][]='_to_site_vars' ;
$__functions['boot_site'][]='_to_site_boot' ;

function TO() {return($_SESSION['to_system']);$_SESSION['to_system']=new c_to_system();return($_SESSION['to_system']);} ;


function _to_site_vars()
{
}

function _to_site_boot($options)
{
  create_system_modul_obj('to',$options) ;

}


class c_to_system
{
    public $table_bill ;
    public $to_list ;
    public $table_car ;
    public $table_to ;
    public $table_relation ;
    public $view_relation ;

    function __construct($create_options=array())
    {
        $this->table_car = 'obj_site_personals_cars';
        $this->table_relation = 'personal_car_relations';
        $this->view_relation = 'view_relationcars';
        $this->table_to = 'obj_site_cars_to' ;
    }

    function declare_menu_items_2($page)
    {
        $page->menu['/cab/rmt/'] = array('title' => 'РМТ',
            'class' => 'fa fa-user-md',
            'items' => array('/cab/rmt/' => 'Новое ТО',
                '/cab/rmt/check/tablet/' => 'Планшет',
//                '/cab/rmt/to/' => 'История ТО',
                //'/cab/rmt/upload_rosinfoteh/'=>'Импорт Росинфотех',
                //'/cab/rmt/park/'=>'Автопарки',
//                '/cab/rmt/report/' => 'Отчет'
            )
        );
    }

    function declare_menu_items_4($page)
    {   $page->menu['/cab/setting/']['items']['/cab/rmt/setting/']['title']='Тех. осмотры' ;

    }


    function car_create($form_data, $options = array())
    {
        ob_start();
        $data = array('parent' => 0, 'clss' => 363, 'indx' => 1); // damp_array($form_data,1,-1) ;
        if (isset($form_data['uid'])) $data['uid'] = $form_data['uid'];
        else                           $data['uid'] = 'esmo_car_' . ENGINE()->generate_UID();
        if (isset($form_data['obj_name'])) $data['obj_name'] = $form_data['obj_name'];
        if (isset($form_data['model'])) $data['model'] = $form_data['model'];
        if (isset($form_data['type'])) $data['type'] = $form_data['type'];

        if ($form_data['org_name']) $form_data['org_id'] = PERSONAL()->get_org_id_by_name($form_data['org_name'], array('create_if_not_exists' => 1));
        if ($form_data['org_id']) $data['parent'] = $form_data['org_id'];

        if (isset($form_data['s_medspravka'])) {
            $data['s_medspravka'] = strtotime($form_data['s_medspravka']);
            // в $form_data['s_medspravka'] может быть передано уже готовое число
            if (!$data['s_medspravka'] and $form_data['s_medspravka']) $data['s_medspravka'] = $form_data['s_medspravka'];
            if (!$data['s_medspravka']) $data['s_medspravka'] = 0;
        }

        if ($options['use_multiinsert']) multiSQL_insert($this->table_car)->append($data);
        else $car_reffer = adding_rec_to_table($this->table_car, $data, array('return_reffer' => 1, 'debug' => 0));

        list($car_id, $car_tkey) = explode('.', $car_reffer);
        $event_title = ($options['event_title']) ? $options['event_title'] : 'Создание АВТО';
        $text = ob_get_clean();
        if ($options['source_fname']) $text .= '<div><a href="' . $options['source_fname'] . '" target="_blank">Источник</a></div>';
        LOGS()->reg_log($event_title, $text, array('_data' => $data, 'car_id' => $car_id, 'reffers' => array($car_reffer)));
        return ($car_reffer);
    }

    function car_save($reffer, $form_data, $options = array())
    { //damp_array($form_data,1,-1) ;
        $result = array();
        $rec = PERSONAL()->get_car_by_id($reffer);
        $res = array(); // damp_array($rec,1,-1) ;
        if ($rec['pkey'] and _sizeof($form_data)) {  // определяем, какие поля были изменены
            ob_start();
            $arr_changes = array();
            $data = array();
            $data_so = array();
            $res_update = array();

            if (isset($form_data['uid']) and $form_data['uid'] != $rec['uid']) {
                $data['uid'] = $form_data['uid'];
                $arr_changes['UID'] = $rec['uid'] . ' => ' . $form_data['uid'];
            }
            if (isset($form_data['obj_name']) and $form_data['obj_name'] != $rec['obj_name']) {
                $data['obj_name'] = $form_data['obj_name'];
                $arr_changes['Гос. номер'] = $rec['obj_name'] . ' => ' . $form_data['obj_name'];
            }
            if (isset($form_data['model']) and $form_data['model'] != $rec['model']) {
                $data['model'] = $form_data['model'];
                $arr_changes['Модель'] = $rec['model'] . ' => ' . $form_data['model'];
            }
            if (isset($form_data['type']) and $form_data['type'] != $rec['type']) {
                $data['type'] = $form_data['type'];
                $arr_changes['Тип авто'] = $rec['type'] . ' => ' . $form_data['type'];
            }

            $parent = 0;
            if (isset($form_data['parent']) and $form_data['parent'] > 0) $parent = $form_data['parent'];
            if (isset($form_data['org_id']) and $form_data['org_id'] > 0) $parent = $form_data['org_id'];

            if (isset($form_data['e_osago']) and $form_data['e_osago'] != $rec['e_osago']) {
                $data['e_osago'] = $form_data['e_osago'];
                $arr_changes['ОСАГО до'] = date('d.m.Y', $rec['e_osago']) . ' => ' . date('d.m.Y', $form_data['e_osago']);
            }

            if (isset($form_data['e_sts']) and $form_data['e_sts'] != $rec['e_sts']) {
                $data['e_sts'] = $form_data['e_sts'];
                $arr_changes['СТС до'] = date('d.m.Y', $rec['e_sts']) . ' => ' . date('d.m.Y', $form_data['e_sts']);
            }

            if (isset($form_data['e_gto']) and $form_data['e_gto'] != $rec['e_gto']) {
                $data['e_gto'] = $form_data['e_gto'];
                $arr_changes['ГТО до'] = date('d.m.Y', $rec['e_gto']) . ' => ' . date('d.m.Y', $form_data['e_gto']);
            }

            if (isset($form_data['enabled']) and $form_data['enabled'] != $rec['enabled']) {
                $data['enabled'] = $form_data['enabled'];
                $arr_changes['Активен'] = ($data['enabled'])?'Нет => Да':'Да => Нет';
            }

            if (_sizeof($data) and !$options['read_only']) {
                $res_update = update_rec_in_table($this->table_car, $data, 'pkey=' . $rec['pkey'], array('debug' => 0));
            }

            $event_title = ($options['event_title']) ? $options['event_title'] : 'Измение авто';

            $text = ob_get_clean();
            echo $text;
            if (_sizeof($arr_changes) and !$options['read_only']) {
                if ($options['source_fname']) $text .= '<div><a href="' . $options['source_fname'] . '" target="_blank">Источник</a></div>';
                LOGS()->reg_log($event_title, $text, array('data' => $arr_changes, 'car_id' => $rec['pkey'], 'reffers' => array($rec['_reffer'])));
//                $GLOBALS['personals_changes'][$rec['pkey']]['name']='<a href="/window/personal/person/'.$rec['pkey'].'/" class="new_window">'.$rec['obj_name'].'</a>' ;
                $GLOBALS['cars_changes'][$rec['pkey']]['changes']['Автомобиль'] = $arr_changes;

            }

            $result = ($options['return_changes']) ? $arr_changes : $res_update;
        }
        return ($result);
    }

    function disable_relation()
    {
        $cnt = execSQL_update('update ' . TO()->table_relation . ' set active=0 where active=1 and time_to<' . time());
        echo 'Выключено ' . $cnt . ' связей водитель-автомобиль';
    }

    function to_params_create($data,$group_TO)
    {
        $data['clss'] = 361;
        $data['parent'] = 1;
        if ($group_TO!='null') $data['car_type'] = $group_TO;
        if ($data['car_type']) {
            $data['indx'] = execSQL_value('select max(indx) from obj_site_to_params where clss=361 and access=' . $data['access'].' and car_type="'.$data['car_type'].'"', 2);
        } else {
            $data['indx'] = execSQL_value('select max(indx) from obj_site_to_params where clss=361 and access=' . $data['access'].' and car_type is null', 2);
        }
        $data['indx']++;
        $id = adding_rec_to_table('obj_site_to_params', $data, array('debug' => 2));
        return ($id);
    }

    function to_params_save($theme_id, $data)
    {
        update_rec_in_table('obj_site_to_params', $data, 'pkey=' . $theme_id, array('debug' => 2));
    }

    function to_params_delete($arr_theme_ids)
    {
        execSQL_update('delete from obj_site_to_params where pkey in (' . implode(',', $arr_theme_ids) . ') and clss=361');
    }

    function upload_TO_image($img_info,$options=array())
    {
        include_once(_DIR_TO_ENGINE.'/admin/i_img_working.php')  ;
        include_once(_DIR_TO_ENGINE.'/admin/i_admin_system.php')  ;

        // загружаем оригинал фото в папку source
//        $tkey=_DOT('obj_site_personals_image')->pkey ;
//        //damp_array(_DOT('obj_site_personals_image')) ;
//        $fname=($options['fname'])? $options['fname']:basename($img_dir) ;
        $new_fname=$img_info['name'] ;
        $new_fdir=_DIR_TO_ROOT.'/public/to_photo/' ;

//        if (file_exists($new_fdir.$new_fname)) $new_fname=$personal_id.'_'.ENGINE()->generate_UID().'_'.$fname ;
//        $result['from']=$img_dir ;
//        $result['to']=$new_fdir.$new_fname ;
//        $result['fname']=basename($img_dir) ;
//        $result['personal_id']=$personal_id ;

        if (copy($img_info['upl_name'],$new_fdir.$new_fname))
        {
//            // оригинал скопирован, создаем клоны
//            create_clone_image($tkey,$new_fname,array('view_upload'=>1)) ;
//            // сдвигаем все текущие фото сотрудника на одну вверх
//            execSQL_update('update obj_site_personals_image set indx=indx+1 where parent='.$personal_id) ;
//            // добавляем новое фото
//
//            list($size_info,$file_type)=get_small_file_info($new_fdir.$new_fname,array('view_upload'=>1)) ;
//            adding_rec_to_table('obj_site_personals_image',array('parent'=>$personal_id,'indx'=>1,'obj_name'=>basename($img_dir),'file_name'=>$new_fname,'type'=>$file_type,'size'=>$size_info)) ;
//            // обновляем в записи по сотруднику название главного фото
//            update_rec_in_table('obj_site_personals',array('_image_name'=>$new_fname),'pkey='.$personal_id) ;
//            // регистрируем событие в журнале
//            PERSONAL()->log_personal_change($personal_id,'faceid','','Обновлено фото, источник: '.$options['source']) ;
//            // генерим событие смены фото
//            ENGINE()->on_event('personal_change_photo',array('personal_id'=>$personal_id,'source'=>$options['source'])) ;
        }
        else $result['error']='Не удалось скопировать файл в место назначения' ;
        return($result) ;
    }

    function get_active_person_relation($personal_id)
    {
        $_usl=[];
        $_usl[]='personal_id='.$personal_id;
        $activeRelation = $this->get_relation($_usl);
        return $activeRelation;
    }

    function get_active_car_relation($car_id)
    {
        $_usl=[];
        $_usl[]='car_id='.$car_id;
        $activeRelation = $this->get_relation($_usl);
        return $activeRelation;
    }

    function get_active_relation($personal_id,$car_id)
    {
        $_usl=[];
        $_usl[]='personal_id='.$personal_id;
        $_usl[]='car_id='.$car_id;
        $activeRelation = $this->get_relation($_usl);
        return $activeRelation;
    }

    function get_relation($_usl)
    {
        $activeRelation=[];
        if (_sizeof($_usl)) {
            $time_now=time();
            $_usl[]='active=1';
            if ($GLOBALS['LS_TO_time_before_active_relation']) {
                $time_start = $time_now + (int) $GLOBALS['LS_TO_time_before_active_relation'] * 60;
                $_usl[]='time_from<='.$time_start;
            } else {
                $_usl[]='time_from<='.$time_now;
            }
            $_usl[]='time_to>='.$time_now;
            $activeRelation = execSQL_van('select * from '.$this->view_relation.' where '.implode(' and ',$_usl).' order by pkey desc');
        }
        return $activeRelation;
    }

    function get_relation_by_id($id)
    {
        $relation = execSQL_van('select * from '.$this->view_relation.' where pkey='.$id);
        return $relation;
    }

    function get_TO_by_id($id, $options = array())
    {
        $rec = execSQL_van('select * from ' . $this->table_to . ' 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_to . ' 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 on_event_examination_result($options=array())
    {
        $rec_mo=ESMO()->get_mo_by_id($options['mo_id']) ;

        if (!$GLOBALS['LS_TO_require_aftershift_ME_for_entry'] and $rec_mo['tk']==1) {
            //если выключена настройка требующая послесменного МО для ТО на выезд и МО - послерейсовый
            if ($rec_mo['personal_id'] and $rec_mo['dopusk']==1)  {
                $activeRelation = TO()->get_active_person_relation($rec_mo['personal_id']);
                if (_sizeof($activeRelation) and $activeRelation['car_id']) {
                    $rec_to = execSQL_van('select pkey,mo_id from ' . $this->table_to . ' where car_id=' . $activeRelation['car_id'] . ' and personal_id=' . $rec_mo['personal_id'].' order by pkey desc');
                    if (_sizeof($rec_to) and $rec_to['mo_id']==0) {
                        $data=[];

                        $data['mo_id'] = $rec_mo['pkey'];
                        $data['mo_status'] = $rec_mo['dopusk'];

                        if ($rec_mo['doctor_id'])          $data['doctor_id']=$rec_mo['doctor_id'] ;
                        elseif ($rec_mo['dopusk_user_id'])     $data['doctor_id']=$rec_mo['dopusk_user_id'] ;
                        elseif ($rec_mo['hand_check_user_id']) $data['doctor_id']=$rec_mo['hand_check_user_id'] ;

                        CAR_TO()->save_car_TO($rec_to['pkey'],[],['data'=>$data]);
                    }
                }
            }
        }

    }
}



?>
