<?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 ;

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

    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 (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)
    {
        $activeRelation = execSQL_van('select * from '.TO()->view_relation.' where active=1 and personal_id='.$personal_id.' and time_from<='.time().' and time_to>='.time().' order by pkey desc');
        return $activeRelation;
    }

    function get_active_car_relation($car_id)
    {
        $activeRelation = execSQL_van('select * from '.TO()->view_relation.' where active=1 and car_id='.$car_id.' and time_from<='.time().' and time_to>='.time().' order by pkey desc');
        return $activeRelation;
    }

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



?>