<?php

class report_count_mo extends c_report
{
    var $title='Отчет по количеству МО для организации' ;
    var $divisions=[];
    var $dates=[];
    var $divisions_data=[];
    var $allow_export_to_csv=1 ;
    var $send_type_only_period = 1; //отправка отчета на email - только период
    var $time_interval=array(1=>'Cутки',3=>'Месяц') ;
    var $month_per_day=0;

    function setting() {
        $now=getdate() ;
        if (!$this->filter['day_from']) $this->filter['day_from']=date('d.m.Y',mktime(0,0,0,$now['mon'],$now['mday']-6,$now['year']));
        if (!$this->filter['day_to']) $this->filter['day_to']=date('d.m.Y',mktime(0,0,0,$now['mon'],$now['mday'],$now['year']));

        $arr_groups=ACCOUNTS()->get_arr_groups_to_cur_account() ;
        list($arr_orgs_ids,$arr_otdel_ids,$arr_works_ids)=PERSONAL()->get_org_otdels_works_to_cur_account($this->filter) ;

        $data_info=execSQL_van('select min(c_data) as min_data,max(c_data) as max_data from obj_site_mo_session') ;
        $arr_from=array() ; $arr_to=array() ;
        if ($data_info['max_data']>$data_info['min_data']) {
            //список по месяцам
            $t=$data_info['min_data'] ;
            while($t<$data_info['max_data']) {
                $ts=getdate($t) ;
                $cur_month=mktime(0,0,0,$ts['mon'],1,$ts['year']) ;
                $arr_from[$cur_month]=get_month_year($cur_month,'month year') ;
                $cur_month=mktime(0,0,0,$ts['mon']+1,1,$ts['year'])-1 ;
                $arr_to[$cur_month]=get_month_year($cur_month,'month year') ;
                $t=mktime(0,0,0,$ts['mon']+1,1,$ts['year']) ;
            }
            krsort($arr_from);
            krsort($arr_to);
        }

        if (!$this->filter['time_interval']) {
            $this->filter['time_interval']=1;
        }

        $day_section_class='2 day_section';
        $month_section_class='2 month_section';

        switch ($this->filter['time_interval']) {
            case 1:
                $month_section_class.=' hidden_element';
                break;
            case 3:
                $day_section_class.=' hidden_element';
                break;
        }

        $tk_array=[];
        if (_sizeof($_SESSION['ARR_mo_tk_type'])) foreach($_SESSION['ARR_mo_tk_type'] as $id=>$name) $tk_array[$id+1]=$name;



        ?><div id="panel_filter">
        <form id="sky-form" class="sky-form"><input type="hidden" name="filter_dir" value="<?echo _CUR_REPORT_DIR?>">
            <fieldset>
                <div class="row">
                    <?
                    $this->filter_section_select('group_id',$GLOBALS['LS_person_group_title'].':',2,$arr_groups) ;
                    $this->filter_section_select_multiple('org_ids','Организация:',2,$arr_orgs_ids) ;
                    $this->filter_section_select_multiple('otdel_ids','Подразделение:',2,$arr_otdel_ids) ;
                    $this->filter_section_select_multiple('working','Должность:',2,$arr_works_ids) ;
                    $this->filter_section_select('time_interval','Временной интервал:',2,$this->time_interval,array('nospace_element'=>1,'select_params'=>'id="selectInterval" onchange="onTimeIntervalChange()"')) ;
                    $this->filter_section_input_text('day_from','От:',$day_section_class,array('class'=>'datepicker')) ;
                    $this->filter_section_input_text('day_to','До:',$day_section_class,array('class'=>'datepicker')) ;
                    $this->filter_section_select('month_from','С, месяц:',$month_section_class,$arr_from) ;
                    $this->filter_section_select('month_to','По, месяц:',$month_section_class,$arr_to) ;
                    ?>
                </div>
                <div class="row">
                    <?
                    $this->filter_section_select_multiple('group_pers','Группа сотрудников:',3,_IL('IL_groups')->recs) ;
                    $this->filter_section_select('tk','Тип контроля:',2,$tk_array) ;
                    ?>
                </div>
                <div class="row">
                    <section class="col col-2">
                        <label class="label">Сортировка:</label>
                        <label class="select">
                            <select name="filter[order]" id="order">
                                <option value="0" <?if (!$this->filter['order']) echo 'selected'?>>По подразделению</option>
                                <option value="1" <?if ($this->filter['order']==1) echo 'selected'?>>По подразделение в обратном порядке</option>
                            </select>
                        </label>
                    </section>
                </div>
                <div class="row">
                    <section class="col col-3">
                        <label class="checkbox">
                            <input type="checkbox" name="filter[abbreviation]" value="1" <?if ($this->filter['abbreviation']) echo 'checked'?>><i></i>Сокращенное наименование организаций
                        </label>
                    </section>
                </div>
                <div class="row">
                    <section class="col col-3">
                        <label class="checkbox">
                            <input type="checkbox" name="filter[only_orgs]" value="1" <?if ($this->filter['only_orgs']) echo 'checked'?>><i></i>Только организации
                        </label>
                    </section>
                </div>
            </fieldset>
            <?$this->panel_buttons();?>
        </form>
        </div>
        <style type="text/css">
            section.hidden_element {display:none;}
        </style>
        <script type="text/javascript">
            function onTimeIntervalChange() {
                var curValue=$j('#selectInterval')[0].value;
                console.log(curValue);
                switch (curValue) {
                    case '1':
                        console.log('day');
                        // console.log($j('section.day_section'));
                        $j('section.day_section').removeClass('hidden_element');
                        $j('section.month_section').removeClass('hidden_element').addClass('hidden_element');
                        break;
                    case '3':
                        console.log('month');
                        $j('section.day_section').removeClass('hidden_element').addClass('hidden_element');
                        $j('section.month_section').removeClass('hidden_element');
                        break;
                }
            }
        </script>
        <?
    }

    function filter_section_select($element_name,$element_title,$col_count,$recs,$options=array())
    {  if (!_sizeof($recs)) return ;
        $cur_value=(isset($options['cur_value']))? $options['cur_value']:$this->filter[$element_name] ;
        ?><section class="col col-<?echo $col_count?>">
        <label class="label"><?echo $element_title?></label>
        <label class="select">
            <select class=filter name="filter[<?echo $element_name?>]" <?if ($options['select_params']) echo $options['select_params'];?>>
                <? if (!$options['nospace_element']){?><option value="0"></option><?}
                if (_sizeof($recs)) foreach($recs as $id=>$value)
                {   $key=(is_array($value) and $options['key_fname'])?  $value[$options['key_fname']]:$id ;
                    $val=(is_array($value))?  $value['obj_name']:$value ;
                    if ($options['use_id_plus_1']) $key++ ;
                    ?><option value="<?echo $key?>" <?if($cur_value==$key) echo 'selected'?>><?echo $val?></option><?
                }
                ?>
            </select><i></i>
        </section>
        <?
    }

    function panel_info_filter()
    { $_str=array() ; $info=array() ; $title='' ;

        if (isset($this->filter['data_from']) and isset($this->filter['data_to'])) {
            if ($this->filter['time_interval'] == 1) {
                $this->filter['day_from'] = $this->filter['data_from'];
                $this->filter['day_to'] = $this->filter['data_to'];
            }
            else if ($this->filter['time_interval'] == 3) {
                $this->filter['month_from'] = strtotime($this->filter['data_from']);
                $this->filter['month_to'] = strtotime($this->filter['data_to']);
            }
        }

        if ($this->filter['time_interval']==1) {
            if ($this->filter['day_from'])                       $info['c']=$this->filter['day_from'] ;
            if ($this->filter['day_to'])                         $info['по']=$this->filter['day_to'] ;
        } elseif ($this->filter['time_interval']==3) {
            if ($this->filter['month_from'])                       $info['c']=get_month_year($this->filter['month_from'],'month year') ;
            if ($this->filter['month_to'])                         $info['по']=get_month_year($this->filter['month_to'],'month year') ;
        }

        if ($this->filter['group_id'])                        $info['Группа']=ACCOUNTS()->get_member_name_by_id($this->filter['group_id'])  ;
        if ($this->filter['org_id'])                          $info['организация']=PERSONAL()->get_name_by_id($this->filter['org_id']) ;
        if ($this->filter['org_ids'])                         $info['Организации']=PERSONAL()->get_org_names_by_ids(array_keys($this->filter['org_ids']))  ;
        if ($this->filter['otdel_ids'])                       $info['Подразделения']=PERSONAL()->get_org_names_by_ids(array_keys($this->filter['otdel_ids']))  ;
        if (_sizeof($this->filter['working']))  foreach($this->filter['working'] as $working_id=>$value) $info['Должность'][]=_IL('IL_works')->recs[$working_id]['obj_name'] ;
        if (_sizeof($this->filter['group_pers']))
        { $arr_group_name=array() ;
            foreach($this->filter['group_pers'] as $group_id=>$flag) $arr_group_name[]=_IL('IL_groups')->recs[$group_id]['obj_name'] ;
            if (_sizeof($arr_group_name)) $info['группа сотрудников']=implode(',',$arr_group_name);
        }
        if ($this->filter['tk'])                              $info['Тип контроля']=$_SESSION['ARR_mo_tk_type'][$this->filter['tk']-1]  ;


        if (_sizeof($info)) foreach($info as $title=>$value)   if (is_array($value)) $_str[]=$title.': <strong>'.implode(', ',$value).'</strong>' ; else $_str[]=$title.': <strong>'.$value.'</strong>' ;
        if (_sizeof($_str)) $title='<p class=center>'.implode(' ',$_str).'</p>' ;
        $this->report_info=$info ;
        return $title ;

    }

    function get_usl($options=array()) {

        $_usl[]='status in (2,3)' ;
        $_usl[]='dopusk in (1,2)';
        $_usl[]='model>0' ;

        if ($this->filter['group_id'] and isset(ACCOUNTS()->tree[$this->filter['group_id']])) $_usl[]=(isset(ACCOUNTS()->tree[$this->filter['group_id']]))?  'group_id in ('.ACCOUNTS()->tree[$this->filter['group_id']]->get_list_child().')':'group_id in ('.$this->filter['group_id'].')' ;
        if ($this->filter['org_id'])        $_usl[]='personal_parent2="'.$this->filter['org_id'].'"' ;
        if ($this->filter['otdel_id'])      $_usl[]='personal_parent3="'.$this->filter['otdel_id'].'"' ;
        if ($this->filter['org_ids']) {
            $org_ids=implode(',',array_keys($this->filter['org_ids']));
            if (is_array($org_ids)) { if (_sizeof($org_ids))   $_usl[]='personal_parent2 in ('.implode(',',$this->check_filter_array($org_ids)).')' ; }
            else                               { $_usl[]='personal_parent2 in ('.$org_ids.')' ; }
        }
        if ($this->filter['otdel_ids']) {
            $otdel_ids=implode(',',array_keys($this->filter['otdel_ids']));
            if (is_array($otdel_ids)) { if (_sizeof($otdel_ids)) $_usl[]='personal_parent3 in ('.implode(',',$this->check_filter_array($otdel_ids)).')' ;}
            else                               $_usl[]='personal_parent3 in ('.$otdel_ids.')' ;
        }
        if (_sizeof($this->filter['working'])) $_usl[]='working in ('.implode(',',array_keys($this->filter['working'])).')' ;
        if ($this->filter['tk']==1)         $_usl[]='tk=0' ;
        if ($this->filter['tk']==2)         $_usl[]='tk=1' ;
        if ($this->filter['tk']==3)         $_usl[]='tk=2' ;

        $usl_gb=[];
        if (_sizeof($this->filter['group_pers'])) foreach($this->filter['group_pers'] as $group_id=>$flag) $usl_gb[]='personal_id in (select pkey from view_personals_group_'.$group_id.')' ;
        if (_sizeof($usl_gb)) $_usl[]='('.implode(' or ',$usl_gb).')' ;

        if (_sizeof($_usl)) $usl_res=implode(' and ',$_usl) ;

        return($usl_res) ;
    }

    function check_filter_array($arr){
        list($id,$value)=each($arr) ;
        if (!$id) return($arr) ;
        else return(array_keys($arr)) ;
    }

    function get_cnt_items($usl,$options=array()) {
        return(0) ;
    }

    function get_next_month_start($time_prev) {
        $time_array=getdate($time_prev);
        return mktime(0,0,0,$time_array['mon']+1,1,$time_array['year']);
    }

    function get_cur_month_end($time_start) {
        $time_array=getdate($time_start);
        return mktime(0,0,0,$time_array['mon']+1,1,$time_array['year'])-1;
    }

    function prepare_data($options=array()) {
        $usl=$this->get_usl();

        $result=[]; $date_array=[]; $groupByParent='';

        if (isset($this->filter['data_from']) and isset($this->filter['data_to'])) {
            if ($this->filter['time_interval'] == 1) {
                $this->filter['day_from'] = $this->filter['data_from'];
                $this->filter['day_to'] = $this->filter['data_to'];
            }
            else if ($this->filter['time_interval'] == 3) {
                $this->filter['month_from'] = strtotime($this->filter['data_from']);
                $this->filter['month_to'] = strtotime($this->filter['data_to']);
            }
        }

        switch ($this->filter['time_interval']) {
            case 1:
                $date_from=strtotime($this->filter['day_from']);
                $date_to=strtotime($this->filter['day_to']);

                for ($time_from=$date_from; $time_from<=$date_to; $time_from+=60*60*24) {
                    $time_to=$time_from+60*60*24-1;
                    $date_array[]=['time_from'=>$time_from,'time_to'=>$time_to];
                }
                break;
            case 3:
                if (($this->filter['month_from'] and !$this->filter['month_to']) or (!$this->filter['month_from'] and $this->filter['month_to'])) {
                    //если выбраны с/по месяц и они равны друг другу или выбран только один месяц
                    //выводим данные по текущему месяцу
                    if ($this->filter['month_from']) {
                        $date_from=$this->filter['month_from'];
                        $temp_date_array=getdate($date_from);
                        $date_to=mktime(0,0,0,$temp_date_array['mon']+1,1,$temp_date_array['year'])-1;
                        $this->month_per_day=1;
                    } else {
                        $date_to=$this->filter['month_to'];
                        $temp_date_array=getdate($date_to);
                        $date_from=mktime(0,0,0,$temp_date_array['mon'],1,$temp_date_array['year']);
                        $this->month_per_day=1;
                    }
                    for ($time_from=$date_from; $time_from<=$date_to; $time_from+=60*60*24) {
                        $time_to=$time_from+60*60*24-1;
                        $date_array[]=['time_from'=>$time_from,'time_to'=>$time_to];
                    }
                } elseif ($this->filter['month_from'] and $this->filter['month_to']) {
                    if ($this->filter['month_from']>$this->filter['month_to']) {
                        echo '<span class="red">Не правильно указан временной интервал</span>';
                        return [];
                    }
                    $date_from=$this->filter['month_from'];
                    $date_to=$this->filter['month_to'];

                    for ($time_from=$date_from; $time_from<=$date_to; $time_from=$this->get_next_month_start($time_from)) {
                        $time_to=$this->get_cur_month_end($time_from);
                        $date_array[]=['time_from'=>$time_from,'time_to'=>$time_to];
                    }
                } else {
                    echo '<span class="red">Не указан временной интервал</span>';
                    return [];
                }
                break;
        }


        if (_sizeof($date_array)) foreach ($date_array as $date_value) {
            $cur_usl=$usl.' and c_data>='.$date_value['time_from'].' and c_data<'.$date_value['time_to'];
            if ($this->filter['only_orgs']) {
                $groupByParent='personal_parent2';
            } else {
                $groupByParent='personal_parent';
            }
            $sql_array[]='(select "'.$date_value['time_from'].'" as date,count(pkey) as cnt,'.$groupByParent.' as groupByParent from '.ESMO()->view_mo_session.' where '.$cur_usl.' group by '.$groupByParent.')';
        }

        $sql=implode(' union ',$sql_array);

        $recs=execSQL($sql,0,1);

        if (_sizeof($recs)) foreach ($recs as $key=>$rec) {
            //если отображаем по организациям
            $this->divisions[$rec['groupByParent']]=1;
            $this->dates[$rec['date']]=1;
            $result[$rec['groupByParent']][$rec['date']]['cnt']=$rec['cnt'];

            unset($recs[$key]);
        }

        $division_recs=execSQL('select pkey,parent,obj_name,level from obj_site_personals where clss in (1,207,208) order by obj_name') ;

        $name_options=[];
        if (_sizeof($this->filter['org_ids'])==1) $name_options['without_orgs']=1;
        if (_sizeof($this->divisions)) foreach ($this->divisions as $division_id=>$value) {
            $this->divisions_data[$division_id]['name']=$this->get_division_full_name('',$division_id,$division_recs,$name_options);

            if ($this->filter['abbreviation']) {
                $this->divisions_data[$division_id]['full_name']=mb_str_replace('<br>',' ',$this->divisions_data[$division_id]['name']);
                $this->divisions_data[$division_id]['name']=$this->abbreviate($this->divisions_data[$division_id]['name']);
            }

            $result[$division_id]['id']=$division_id;
        }

        usort($result, function($a, $b){
            if (!$this->filter['order']) {
                $value_a=mb_str_replace([' ','<br>','/'],'',$this->divisions_data[$a['id']]['name']);
                $value_b=mb_str_replace([' ','<br>','/'],'',$this->divisions_data[$b['id']]['name']);
                return strcasecmp($value_a, $value_b);
            } elseif ($this->filter['order']==1) {
                $value_a=mb_str_replace([' ','<br>','/'],'',$this->divisions_data[$a['id']]['name']);
                $value_b=mb_str_replace([' ','<br>','/'],'',$this->divisions_data[$b['id']]['name']);
                return -1*strcasecmp($value_a, $value_b);
            }
        });

        return $result;
    }

    function abbreviate($string){
        $abbreviation = "";
        $string=mb_str_replace('"','',$string);
        $string=mb_str_replace('<br>',' <br> ',$string);
        $words = explode(" ", $string);
        foreach($words as $word){
            if ($word=='<br>') $abbreviation .= $word;
            else {
                $char=mb_substr(mb_strtoupper($word),0,1);
                if ($char=='№') $abbreviation .= $word;
                else $abbreviation .= $char;
            }
        }
        return $abbreviation;
    }

    function get_division_full_name($name,$id,$recs,$options=array()) {
        if ($options['without_orgs']) $stop_level=2; else $stop_level=1;
        if ($recs[$id]['level']>$stop_level) {
            $cur_id_name=$recs[$id]['obj_name'];
            if ($name) {
                if ($recs[$id]['level']==2) {
                    $name=$cur_id_name.'<br>'.$name;
                } else {
                    $name=$cur_id_name.' / '.$name;
                }
            } else {
                $name=$cur_id_name;
            }
            $name=$this->get_division_full_name($name,$recs[$id]['parent'],$recs,$options);
        }
        return $name;
    }

    function get_cell_url($division_id, $date) {
        $url_array=[];
        $url_array[]='/window/reports/report_mo3/[dopusk=(1;2)';
        if ($this->filter['group_id']) $url_array[]='group_id='.$this->filter['group_id'];
        if ($this->filter['working']) $url_array[]='working=('.implode(';',array_keys($this->filter['working'])).')';
        if ($this->filter['group_pers']) {}
        $url_array[]='data_from='.date('d.m.Y',$date);
        if ($this->filter['time_interval']==1 or ($this->filter['time_interval']==3 and $this->month_per_day==1)) $url_array[]='data_to='.date('d.m.Y',$date).' 23:59:59';
        elseif ($this->filter['time_interval']==3) {
            $ts=getdate($date);
            $url_array[]='data_to='.date('d.m.Y',mktime(0,0,0,$ts['mon']+1,1,$ts['year'])-1).' 23:59:59';
        }
        if ($this->filter['group_pers']) $url_array[]='group_pers=('.implode(';',array_keys($this->filter['group_pers'])).')';
        if (!$this->filter['only_orgs']) $url_array[]='dep_id='.$division_id.']/'; else $url_array[]='org_id='.$division_id.']/';
        return implode(',',$url_array);
    }

    function HTML_report_body($options=array()) {
        $list_recs=$this->prepare_data();

        $sum=[];
        $i=1;

        if (_sizeof($list_recs)) {
            ?>
            <table class="basic full auto">
                <tr>
                    <th style="width:30px;">№</th>
                    <th style="width: <?if ($this->filter['abbreviation']) echo '10'; else echo '20';?>%"><?if ($this->filter['only_orgs']) echo 'Организация'; else echo 'Подразделение';?></th>
                    <?
                    foreach ($this->dates as $date=>$value) {
                        ?>
                        <th>
                            <?
                            if ($this->filter['time_interval']==3 and !$this->month_per_day) echo get_month_year($date,'month year');
                            elseif ($this->filter['time_interval']==1 or ($this->filter['time_interval']==3 and $this->month_per_day==1)) echo date('d.m.Y',$date);
                            ?>
                        </th>
                        <?
                    }
                    ?>
                    <th>Итого</th>
                </tr>
                <?
                foreach ($list_recs as $list_rec) {
                    ?>
                    <tr>
                        <td><?echo $i++;?></td>
                        <td><span <?if ($this->filter['abbreviation']) echo 'title="'.htmlspecialchars($this->divisions_data[$list_rec['id']]['full_name']).'"'?>><?echo $this->divisions_data[$list_rec['id']]['name']?></span></td>
                        <?
                        foreach ($this->dates as $date=>$value){
                            $sum['date'][$date]+=$list_rec[$date]['cnt'];
                            $sum['division'][$list_rec['id']]+=$list_rec[$date]['cnt'];
                            $url=$this->get_cell_url($list_rec['id'],$date);
                            if ($list_rec[$date]['cnt']) {
                                ?>
                                <td><a href="<?echo $url?>" class="new_window"><?echo $list_rec[$date]['cnt']?></a></td>
                                <?
                            } else {
                                ?>
                                <td></td>
                                <?
                            }

                        }
                        ?>
                        <td><?echo $sum['division'][$list_rec['id']]?></td>
                    </tr>
                    <?
                }
                ?>
                <tr class="itog">
                    <td colspan="2">ИТОГО</td>
                    <?
                    foreach ($this->dates as $date=>$value){
                        $sum['all']+=$sum['date'][$date];
                        ?>
                        <td><?echo $sum['date'][$date]?></td>
                        <?
                    }
                    ?>
                    <td><?echo $sum['all']?></td>
                </tr>
            </table>
            <?
        }
    }

    function CSV_report_body($options=array())
    {
        $recs=$this->prepare_data() ;
        $i=0 ;
        $sum=[];
        if (_sizeof($recs)) foreach($recs as $rec) {
            $data=[] ;
            if ($this->filter['only_orgs']) {
                $data['Организация']=mb_str_replace('<br>',' ',$this->divisions_data[$rec['id']]['name']);
            } else {
                $data['Подразделение']=mb_str_replace('<br>',' ',$this->divisions_data[$rec['id']]['name']);
            }
            foreach ($this->dates as $date=>$value) {
                $sum['date'][$date]+=$rec[$date]['cnt'];
                $sum['division'][$rec['id']]+=$rec[$date]['cnt'];
                $data[date('d.m.Y',$date)]=($rec[$date]['cnt'])?$rec[$date]['cnt']:'';
            }
            $data['Итого']=($sum['division'][$rec['id']])?$sum['division'][$rec['id']]:'';
            $this->put_data_to_CSV($data,$i) ;
            $i++ ;
        }
        $data=[] ;
        if ($this->filter['only_orgs']) {
            $data['Организация']='ИТОГО';
        } else {
            $data['Подразделение']='ИТОГО';
        }
        foreach ($this->dates as $date=>$value) {
            $sum['all']+=$sum['date'][$date];
            $data[date('d.m.Y',$date)]=($sum['date'][$date])?$sum['date'][$date]:'';
        }
        $data['Итого']=($sum['all'])?$sum['all']:'';

        $this->put_data_to_CSV($data,$i) ;
    }

}

?>
