<section class="content-header">
    <h1><i class='fa-fw fa fa-clock-o'></i> <?php echo $_translator->_getTranslation('Programacion de horarios');?></small></h1>
    <ol class="breadcrumb">
        <li><a href="<?php echo ROOT_HOST?>/Controller/Home.php"><i class="fa fa-dashboard"></i><?php echo $_translator->_getTranslation('Inicio')?></a></li>
        <li><a href="<?php echo ROOT_HOST?>/Controller/ScheduleEmployee.php?action=list"><?php echo $_translator->_getTranslation('Lista de programacion de horarios')?></a></li>
        <li class="active"><?php echo $_translator->_getTranslation('Programacion de horarios');?></li>
    </ol>
</section>
<section class="content">
<div class="box">
    <div class='flashmessenger'><?php $flashmessenger->showMessage();?></div>
    <div class="box-header with-border">
        <div class="box-tools"></div><!-- /.box-tools -->
    </div><!-- /.box-header -->
    <div class="box-body">     
        <?php 
            echo $_formSchedule->openForm();
            echo $_formSchedule->showActionController();
            echo $_formSchedule->showId();        
            $_formSchedule->showElement('start_period'); 
            $_formSchedule->showElement('end_period'); ?>
        
        <div class="col-xs-12 col-md-6">                  
            <?php $_formSchedule->showElement('store_id'); ?>
            <?php $_formSchedule->showElement('period_id'); ?>
            <?php $_formSchedule->showElement('scheduled_hours'); ?>    
        </div>
        <div class="col-xs-12 col-md-12">       
            <?php
            if($action == 'edit'){
                if($_days_of_period){
                    foreach($_days_of_period as $dayDate =>$dayFormated){
                        $scheduleHours = array();
                        $dayName = new DateTime($dayDate);
                        $dayName = strtolower($dayName->format('l'));  
                        
                        $storeRepo = new StoreRepository();
                        $storeData = $storeRepo->getById($_scheduleData['store_id']);

                        $startHour = $storeData['start_schedule_'.$dayName];
                        $endHour = $storeData['end_schedule_'.$dayName];
                        $startHour2 = $storeData['start_schedule_'.$dayName.'_2'];
                        $endHour2 = $storeData['end_schedule_'.$dayName.'_2'];
                        
                        $startHour = new DateTime($dayDate.' '.$startHour);
                        $endHour = new DateTime($dayDate.' '.$endHour);    
                        
                        $minhour = $startHour->format('G');
                        $maxhour = $endHour->format('G');

                        if($startHour != $endHour){            
                            $scheduleHours[$startHour->format('H:i')] = $startHour->format('H:i');

                            while ($startHour < $endHour){
                                $startHour->add(new DateInterval('PT1H'));
                                $scheduleHours[$startHour->format('H:i')] = $startHour->format('H:i');
                            }
                        }
                        
                        $startHour2 = new DateTime($dayDate.' '.$startHour2);
                        $endHour2 = new DateTime($dayDate.' '.$endHour2);       
                        
                        $minhour2 = $startHour2->format('G');
                        $maxhour2 = $endHour2->format('G');

                        if($startHour2 != $endHour2){            
                            $scheduleHours[$startHour2->format('H:i')] = $startHour2->format('H:i');

                            while ($startHour2 < $endHour2){
                                $startHour2->add(new DateInterval('PT1H'));
                                $scheduleHours[$startHour2->format('H:i')] = $startHour2->format('H:i');
                            }
                        }?>            
                        <table class='table table-condensed table-striped'>
                        <thead>
                            <tr>
                                <th colspan="<?php echo count($scheduleHours) ?>"><?php echo $dayFormated ?></th>
                            </tr>
                            <tr>
                                <th class='text-center' ><?php echo $_translator->_getTranslation('Nombre') ?></th>
                                <th class='text-center'><?php echo $_translator->_getTranslation('TH') ?></th>
                                <th class='text-center'><?php echo $_translator->_getTranslation('Inicio') ?></th>
                                <th class='text-center'><?php echo $_translator->_getTranslation('Fin') ?></th>
                                <th class='text-center'><?php echo $_translator->_getTranslation('Inicio 2') ?></th>
                                <th class='text-center'><?php echo $_translator->_getTranslation('Fin 2') ?></th>                                
                                <?php
                                foreach($scheduleHours as $key => $hour){?>
                                    <th class='text-left' style="border-bottom:solid 1px #000;"><?php echo $hour; ?></th><?php
                                }
                                ?>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            if($_user_list){
                                foreach($_user_list as $key => $user){
                                    $uuid = $dayDate.'_'.$user['id'];
                                    $detail_total = 0;
                                    $detail_start_hour = null;
                                    $detail_end_hour = null;
                                    $detail_start_hour_2 = null;
                                    $detail_end_hour_2 = null;
                                    
                                    if(isset($_details[$dayDate][$user['id']])){
                                        $dataDetail = $_details[$dayDate][$user['id']];
                                        
                                        if(!empty($dataDetail['total_hours'])){ $detail_total = $dataDetail['total_hours'];}
                                        if(!empty($dataDetail['start_hour'])){ $detail_start_hour = $dataDetail['start_hour'];}
                                        if(!empty($dataDetail['end_hour'])){ $detail_end_hour = $dataDetail['end_hour'];}
                                        if(!empty($dataDetail['start_hour_2'])){ $detail_start_hour_2 = $dataDetail['start_hour_2'];}
                                        if(!empty($dataDetail['end_hour_2'])){ $detail_end_hour_2 = $dataDetail['end_hour_2'];}              
                                    }
                                                                                           
                                    ?>
                                    <tr data-minhour='<?php echo $minhour ?>' data-maxhour='<?php echo $maxhour ?>' data-minhour2='<?php echo $minhour2 ?>' data-maxhour2='<?php echo $maxhour2 ?>'>
                                        <td class='text-center' style='white-space: nowrap;'><?php echo $user['name'].' '.$user['last_name'] ?></td>
                                        <td><input type='text' name='details[<?php echo $dayDate.'_'.$user['id'].'][total_hours]' ?>' value='<?php echo $detail_total ?>' class='form-control text-center <?php echo $uuid.'_total';?>' data-uuid='<?php echo $uuid ?>' readonly="true"/></td>
                                        <td><input type='text' name='details[<?php echo $dayDate.'_'.$user['id'].'][start_hour]' ?>' value='<?php echo $detail_start_hour ?>' class='_start_time form-control <?php echo $uuid.'_start_hour';?>' data-startend='start' data-parameter='1' data-uuid='<?php echo $uuid ?>'/></td>
                                        <td><input type='text' name='details[<?php echo $dayDate.'_'.$user['id'].'][end_hour]' ?>' value='<?php echo $detail_end_hour ?>' class='_end_time form-control <?php echo $uuid.'_end_hour';?>' data-startend='end' data-parameter='1' data-uuid='<?php echo $uuid ?>'/></td>
                                        <td><input type='text' name='details[<?php echo $dayDate.'_'.$user['id'].'][start_hour_2]' ?>' value='<?php echo $detail_start_hour_2 ?>' class='_start_time form-control <?php echo $uuid.'_start_hour_2';?>' data-startend='start2' data-parameter='2' data-uuid='<?php echo $uuid ?>'/></td>
                                        <td><input type='text' name='details[<?php echo $dayDate.'_'.$user['id'].'][end_hour_2]' ?>' value='<?php echo $detail_end_hour_2 ?>' class='_end_time form-control <?php echo $uuid.'_end_hour_2';?>' data-startend='end2' data-parameter='2' data-uuid='<?php echo $uuid ?>'/></td>
                                        <?php
                                        foreach($scheduleHours as $key => $hour){
                                            $onlyHour = explode(":", $hour);?>
                                            <td style='padding:0px;vertical-align: middle;border:solid 1px #000;'><span class='text-center <?php echo $uuid.'_'.$onlyHour[0] ?>' style='width:100%;display: inline-block'>&nbsp;</span></td><?php
                                        }
                                        ?>
                                    </tr><?php
                                }
                            }
                            ?>
                        </tbody>
                        </table><?php            
                    }
                }
            }
            ?>
            
            <span id='save' class='btn btn-primary pull-right'><?php echo $_translator->_getTranslation('Guardar') ?></span>
        </div>
        <div class="clear"></div>
        <div class="col-xs-12 col-md-12">
        </div>
        <?php echo $_formSchedule->closeForm();?>            
    </div><!-- /.box-body -->
</div><!-- /.box -->
</section>
<style>
    table td{
        position:relative;
    }
    
    ._start_time,._end_time{
        padding: 5px;
        text-align: center;        
    }
    
    
</style>
<script>   
    $('#store_id,#period_id').select2();
    $('._start_time').datetimepicker({format: 'HH:mm',useCurrent: false});    
    $('._end_time').datetimepicker({format: 'HH:mm',useCurrent: false});
    //$('._start_time').timepicker({});
    //$('._end_time').timepicker({});
    
    $('._start_time,._end_time').on('dp.change',function(e){ //e.oldDate         
        var error = null;    
        var msg_error = null;   
        var diffInHour = 0;
        var diffInHour2 = 0;
        var diffInHourTemp = 0;
        var diffInHour2Temp = 0;
        var minhour = $(this).closest('tr').data('minhour'); 
        var maxhour = $(this).closest('tr').data('maxhour');
        var minhour2 = $(this).closest('tr').data('minhour2');
        var maxhour2 = $(this).closest('tr').data('maxhour2');
        var selectedHour = $(this).val(); 
      
        if(selectedHour != ''){  
            if(maxhour2 == 0){
                /*si no esta configurado horario 2, asignamos maxhour a maxhour2*/
                var maxhour2Moment = moment('1984-05-20 '+maxhour); 
                maxhour2 = maxhour2Moment.format('HH');
            }
            
            if( parseFloat(selectedHour) < minhour){            
                error = true;
            }else if(parseFloat(selectedHour) > maxhour && parseFloat(selectedHour) < minhour2){
                error = true;
            }else if(parseFloat(selectedHour) > maxhour2){
                error = true;
            }

            if(error){
                $(this).data("DateTimePicker").date(null);/*clear campo*/     
                $.confirm({ 
                    title:"<i class='fa fa-info-circle'></i> Mensaje", 
                    content:'Hora selecionada esta fuera del horario de la sucursal.',
                    type: 'red',
                    columnClass: 'col-md-6 col-md-offset-3',
                    buttons: {   
                        ok: {
                            text: "OK",
                            btnClass: 'btn-default',
                            keys: ['esc'],
                            action: function(){
                                 $(this).remove();
                            }
                        }
                    }                             
                }); 
                return null;     
            }
        }        
        
        /*limpiamos todo el horario*/
        $(this).closest('tr').find('span').removeClass('bg-green').css({'margin-left':'0%','width':'100%'});
     
        var class_name = $(this).data('startend');
        var uuid = $(this).data('uuid');
        var parameter = $(this).data('parameter');
        var start_hour = null;
        var end_hour = null;
        var start_hour_2 = null;
        var end_hour_2 = null;       
        
        start_hour = $('.'+uuid+'_start_hour').val();           
        end_hour = $('.'+uuid+'_end_hour').val();
        
        var start = moment('1984-05-20 '+start_hour); 
        var start_temp = moment('1984-05-20 '+start_hour); 
        var end = moment('1984-05-20 '+end_hour);
        
        start_hour_2 = $('.'+uuid+'_start_hour_2').val();
        end_hour_2 = $('.'+uuid+'_end_hour_2').val();

        var start_2 = moment('1984-05-20 '+start_hour_2);
        var start_2_temp = moment('1984-05-20 '+start_hour_2);
        var end_2 = moment('1984-05-20 '+end_hour_2);        
        
        /*Graficamos primer rango hasta que inicio y fin tengan valor*/    
        if(end.format('HH') != '00' && start.format('HH') != '00' ){ 
            diffInHour = end.diff(start, 'hours'); 
            diffInHourTemp = end.diff(start, 'minutes'); 
            if(diffInHour > 0){
                var hour = start.format('HH');   
                var min = 0;             
                
                /*Para graficar minutos*/
                min = start.format('m'); 
                if(parseFloat(min) > 0){ 
                    var porcent = (parseFloat(min)/60) * 100;
                    porcent = 100 - porcent;
                    var padding_left = 100 - porcent;
                    $('.'+uuid+'_'+hour).addClass('bg-green').css({'margin-left':padding_left+'%','width':porcent.toFixed(2)+'%'});
                }else{
                    $('.'+uuid+'_'+hour).addClass('bg-green');  
                }
               
                while(end.diff(start_temp,'minutes') > 0 ){
                    start_temp.add(1,'hours');
                    hour = start_temp.format('HH');               
                    $('.'+uuid+'_'+hour).addClass('bg-green');           
                }
                $('.'+uuid+'_'+hour).removeClass('bg-green');/*despintamos ultima hora siempre*/                
                
                /*Para graficar minutos*/
                min = end.format('m'); 
                if(parseFloat(min) > 0){
                    hour = end.format('HH');
                    var porcent = (parseFloat(min)/60) * 100;
                    $('.'+uuid+'_'+hour).addClass('bg-green').css('width',porcent.toFixed(2)+'%');
                }
               
            }else if(diffInHour == 0){
                var hour = start.format('HH');           
                $('.'+uuid+'_'+hour).addClass('bg-green');
            }else{                                  
                if(class_name == 'start'){msg_error = 'Hora inicio debe ser menor a hora fin';}
                if(class_name == 'end'){msg_error = 'Hora fin debe ser mayor a hora inicio';}                    
            }                    
        }
        
        if(class_name == 'start' && start_hour != ''){
            var start_formated_hour = start.format('HH');
            var start_2_formated_hour = start_2.format('HH');
            var end_2_formated_hour = end_2.format('HH');

            if(end_2_formated_hour != '00'){                     
                if((parseFloat(end_2_formated_hour) - parseFloat(start_formated_hour) ) <= 0){msg_error = 'Hora inicio debe ser menor a hora fin 2';}
            }
            
            if(start_2_formated_hour != '00'){                                     
                if((parseFloat(start_2_formated_hour) - parseFloat(start_formated_hour) ) <= 0){msg_error = 'Hora inicio debe ser menor a hora inicio 2';}
            }           
        }
            
        if(class_name == 'end' && end_hour != ''){
            var end_formated_hour = end.format('HH');
            var start_2_formated_hour = start_2.format('HH');
            var end_2_formated_hour = end_2.format('HH');   
            
            if(end_2_formated_hour != '00'){
                if((parseFloat(end_2_formated_hour) - parseFloat(end_formated_hour) ) <= 0){msg_error = 'Hora fin debe ser menor a hora fin 2';}
            }
            
            if(start_2_formated_hour != '00'){
                if((parseFloat(start_2_formated_hour) - parseFloat(end_formated_hour) ) <= 0){msg_error = 'Hora fin debe ser menor a hora inicio 2';}
            }
        }
            
        if(msg_error){
            $(this).data("DateTimePicker").date(null);/*clear campo*/     
            $.confirm({ 
                title:"<i class='fa fa-info-circle'></i> Mensaje", 
                content:msg_error,
                type: 'red',
                columnClass: 'col-md-6 col-md-offset-3',
                buttons: {   
                    ok: {
                        text: "OK",
                        btnClass: 'btn-default',
                        keys: ['esc'],
                        action: function(){
                             $(this).remove();
                        }
                    }
                }                             
            }); 
            return null;             
        }           
        
        /*Graficamos primer rango hasta que inicio y fin tengan valor*/    
        if(end_2.format('HH') != '00' && start_2.format('HH') != '00' ){
            /*Graficamos segundo rango*/
            diffInHour2 = end_2.diff(start_2, 'hours'); 
            diffInHour2Temp = end_2.diff(start_2, 'minutes'); 
            if(diffInHour2 > 0){                        
                var hour = start_2.format('HH');                 
                
                /*Para graficar minutos*/
                min = start_2.format('m'); 
                if(parseFloat(min) > 0){
                    var porcent = (parseFloat(min)/60) * 100;
                    porcent = 100 - porcent;
                    var padding_left = 100 - porcent;
                    $('.'+uuid+'_'+hour).addClass('bg-green').css({'margin-left':padding_left+'%','width':porcent.toFixed(2)+'%'});
                }else{
                    $('.'+uuid+'_'+hour).addClass('bg-green');
                }
                
                while(end_2.diff(start_2_temp,'minutes') > 0 ){
                    start_2_temp.add(1,'hours');
                    hour = start_2_temp.format('HH');    
                    $('.'+uuid+'_'+hour).addClass('bg-green');
                }
                 $('.'+uuid+'_'+hour).removeClass('bg-green');/*despintamos ultima hora siempre*/   
                
                /*Para graficar minutos*/
                min = end_2.format('m'); 
                if(parseFloat(min) > 0){
                    hour = end_2.format('HH');
                    var porcent = (parseFloat(min)/60) * 100;
                    $('.'+uuid+'_'+hour).addClass('bg-green').css('width',porcent.toFixed(2)+'%');
                }

            }else if(diffInHour2 == 0){
                var hour = start_2.format('HH');           
                $('.'+uuid+'_'+hour).addClass('bg-green');
            }else{                                  
                if(class_name == 'start2'){msg_error = 'Hora inicio 2 debe ser menor a hora fin 2';}
                if(class_name == 'end2'){msg_error = 'Hora fin 2 debe ser mayor a hora inicio 2';}                    
            }         
        }       
        
        if(class_name == 'start2' && start_hour_2 != ''){
            var start_2_formated_hour = start_2.format('HH');
            var end_formated_hour = end.format('HH');
            var start_formated_hour = start.format('HH');       

            if(end_formated_hour != '00'){                     
                if((parseFloat(start_2_formated_hour) - parseFloat(end_formated_hour) ) < 0){msg_error = 'Hora inicio 2 debe ser mayor a hora fin';}
            }
            
            if(start_formated_hour != '00'){                                     
                if((parseFloat(start_2_formated_hour) - parseFloat(start_formated_hour) ) < 0){msg_error = 'Hora inicio 2 debe ser mayor a hora inicio';}
            }           
        }
            
        if(class_name == 'end2'  && end_hour_2 != ''){
            var end_2_formated_hour = end_2.format('HH');              
            var start_formated_hour = start.format('HH');             
            var end_formated_hour = end.format('HH');
            
            if(end_formated_hour != '00'){                     
                if((parseFloat(end_2_formated_hour) - parseFloat(end_formated_hour) ) < 0){msg_error = 'Hora fin 2 debe ser mayor a hora fin';}
            }
            
            if(start_formated_hour != '00'){                                     
                if((parseFloat(end_2_formated_hour) - parseFloat(start_formated_hour) ) < 0){msg_error = 'Hora fin 2 debe ser mayor a hora inicio';}
            }      
        }
            
        if(msg_error){
            $(this).data("DateTimePicker").date(null);/*clear campo*/     
            $.confirm({ 
                title:"<i class='fa fa-info-circle'></i> Mensaje", 
                content:msg_error,
                type: 'red',
                columnClass: 'col-md-6 col-md-offset-3',
                buttons: {   
                    ok: {
                        text: "OK",
                        btnClass: 'btn-default',
                        keys: ['esc'],
                        action: function(){
                             $(this).remove();
                        }
                    }
                }                             
            }); 
            return null;             
        }           
        
        /*Si incio y fin tienen valor se calculan horas totales*/      
        var total_hours = (parseFloat(diffInHourTemp) + parseFloat(diffInHour2Temp))/60;
        $('.'+uuid+'_total').val(total_hours.toFixed(1));           
        
    });
    
    
    $('#save').on('click',function(){
        if($('form[name=schedule_employee] #action').val() == 'edit'){            
            $('form[name=schedule_employee]').submit();
            return null;
        }
        var options = $('form[name=schedule_employee]').serializeArray();
        $.post('/Controller/ScheduleEmployee.php', {
        action: 'ajax',
        request: 'saveSchedule',            
        options: options
            }, function(data) {
               if(data.response){
                    document.location = 'ScheduleEmployee.php?action=edit&id='+data.schedule_id
               }else{
                   $.confirm({ 
                        title:"<i class='fa fa-info-circle'></i> Mensaje", 
                        content:data.msj,
                        type: 'red',
                        columnClass: 'col-md-6 col-md-offset-3',
                        buttons: {   
                            ok: {
                                text: "OK",
                                btnClass: 'btn-default',
                                keys: ['esc'],
                                action: function(){
                                     $(this).remove();
                                }
                            }
                        }                             
                    });     
               }                
            },
        'json');
    });
    
    $('._start_time').trigger('dp.change');
    $('._end_time').trigger('dp.change');
</script>
