<?php
checkLogin('adm','per');
checkEnteService('pps');

include(ROOT."/includes/modules/anagrafiche/functions.inc.php");
include(ROOT."/includes/modules/servizi/functions.inc.php");
include("functions.inc.php");

function get_ids($element){
	return $element['anagr_id'];
}

if(isset($_POST['grp'])){
	
	if(intval($_POST['grp']) == 0)
		printMsg("Selezionare la classe",'danger');
	if(!$date = is_date(urldecode($_POST['data'])))
		printMsg("Selezionare la data",'danger');
	
	$grp = intval($_POST['grp']);
	list($gg,$mm,$aaaa) = explode('-',$date);
	
	//estraggo alunni iscritti al servizio pre/post
	$anagrafiche = get_anagr(false,array('flt_serv_cod'=>'pps','flt_grp_sub'=>$grp,'no_limit'=>true));
		
	if(!$anagrafiche){
		Js('$("#btn-save").addClass("hidden");');
		printMsg("Non risultano iscritti al servizio",'warning');
	}
	
	
	//salvo presenze
	if(isset($_POST['opt'])){
		
		$my_ids = array_map('get_ids', $anagrafiche['list']);
		
		foreach($_POST['opt'] as $anagr_id => $val){
			//se e' una mia anagrafica
			if(in_array($anagr_id,$my_ids)){
			
				$presenza_id = intval($_POST['id'][$anagr_id]);
			
				if(!empty($val['pre']) || !empty($val['post'])){
					$mysqli->query("INSERT INTO serv_pps_presenze (id, anagr_id, pre, post, date) VALUES(".dbClean($presenza_id).", ".$anagr_id.", ".dbClean($val['pre']).", ".dbClean($val['post']).",'".$date."') ON DUPLICATE KEY UPDATE pre=".dbClean($val['pre']).", post=".dbClean($val['post']));
				}else if($presenza_id > 0){
					$mysqli->query("DELETE FROM serv_pps_presenze WHERE id = ".intval($presenza_id));	
				}
			}
		}
		
	}

	//estraggo presenze per questo giorno
	$presenze = get_presenze($grp,$date);
	$delegati = get_delegati_all();
	
	$presenze_name = array(''=>'hidden','P' => 'visible');

	foreach($anagrafiche['list'] as $v){
		$grp_name = $v['gruppo'];
		$grp_sub_name = $v['sottogruppo'];
		
		$pre = $presenze[$v['anagr_id']]['pre'];
		$post = $presenze[$v['anagr_id']]['post'];
		$anagr_id = $presenze[$v['anagr_id']]['id'];
		$show_pre = $presenze_name[$pre];
		$show_post = $presenze_name[$post];
		
		$is_pre = $v['servpps_pre'] == 1 || $pre == 'P' ? 'visible' : 'hidden';
		$is_post = $v['servpps_post'] == 1 || $post == 'P'  ? 'visible' : 'hidden';
		
		if($pre == 'P' || $post == 'P')
			$n_presenze++;
		
		$content .= '
		<div class="col-md-6">
			<div class="row">
				<div class="col-xs-12 col-sm-4 col-md-6 col-lg-5">

					<div class="dropdown">
					  	<label class="control-label" style="cursor:pointer" data-toggle="dropdown">
					  		 <span class="glyphicon glyphicon-info-sign text-primary"></span> '.$v['anagr_cognome'].' '.$v['anagr_nome'].'
						</label>
					  	<ul class="dropdown-menu" role="menu" aria-labelledby="dLabel">
							<li role="presentation"><a role="menuitem" tabindex="-1"><span class="glyphicon glyphicon-earphone text-danger"></span> '.$v['user_cell'].'</a></li>
							<li role="presentation" class="divider"></li>
							'.print_delegati_item($delegati[$v['anagr_id']]).'
							<li role="presentation" class="divider"></li>
							<li role="presentation"><a role="menuitem" tabindex="-1">Congedo autonomo: <strong>'. ($v['servpps_congedo'] == 1 ? 'SI' : 'NO').'</strong></a></li>
					  	</ul>
					</div>

				</div>
				
				<div class="col-xs-6 col-sm-2 col-md-3 col-lg-3 p-bottom-5">
					<div class="row" style="visibility:'.$is_pre.'">
						<div class="col-xs-2 visible-xs-inline m-top-10 text-muted">Pre</div>
						<div class="col-xs-9 col-sm-10 col-lg-9">
							<button type="button" class="btn btn-info btn-asm btn-block btn-presenze">
								<span class="glyphicon glyphicon-ok" style="visibility:'.$show_pre.'"></span>
							</button>
							<input name="opt['.$v['anagr_id'].'][pre]" value="'.$pre.'" type="hidden">
						</div>
					</div>
				</div>
				
				
				<div class="col-xs-6 col-sm-2 col-md-3 col-lg-3 p-bottom-5">
					<div class="row" style="visibility:'.$is_post.'">
						<div class="col-xs-2 visible-xs-inline m-top-10 text-muted">Pos</div>
						<div class="col-xs-9 col-sm-10 col-lg-9">
							<button type="button" class="btn btn-info btn-asm btn-block btn-presenze">
								<span class="glyphicon glyphicon-ok" style="visibility:'.$show_post.'"></span>
							</button>
							<input name="opt['.$v['anagr_id'].'][post]" value="'.$post.'" type="hidden">
						</div>
					</div>
				</div>
				
				<input name="id['.$v['anagr_id'].']" value="'.$anagr_id.'" type="hidden">					
			</div>
		</div>
		';
	}
	
	echo '<h4 class="top text-center text-danger p-bottom-5">'.giorno_ita($date).' '.$_POST['data'].'</h4>';

	echo '
	<div class="form-group hidden-xs">
			<div class="col-md-6">
				<div class="row">
					<div class="col-sm-2 col-md-3 col-lg-3 col-sm-offset-4 col-md-offset-6 col-lg-offset-5 text-muted"><strong>Pre</strong> scuola</div>
					<div class="col-sm-2 col-md-3 col-lg-3 text-muted"><strong>Post</strong> scuola</div>
				</div>
			</div>
			<div class="col-md-6 hidden-sm hidden-xs">
				<div class="row">
					<div class="col-sm-2 col-md-3 col-lg-3 col-sm-offset-4 col-md-offset-6 col-lg-offset-5 text-muted"><strong>Pre</strong> scuola</div>
					<div class="col-sm-2 col-md-3 col-lg-3 text-muted"><strong>Post</strong> scuola</div>
				</div>
			</div>
	</div>
	';
	
	echo '<div class="row m-bottom-10">'.$content.'</div>';
	echo '<div class="m-bottom-10 m-top-10 text-info">Totale presenti: <strong style="font-size:22px; font-weight:normal; margin-left:5px">'.intval($n_presenze).'</strong></div>';
	
	
	if(isset($_POST['opt']))
		printMsg('Salvataggio avvenuto con successo!','success',false);

	Js('$("#btn-save").removeClass("hidden");$("#save_grp").val('.$_POST['grp'].');$("#save_data").val("'.$_POST['data'].'");');

	die();
}

$p = new Page('Servizio Mensa - presenze');
$p->addCss('datepicker');
$p->addJs('bootstrap-datepicker');
$p->addJs('presenze');
$p->addMenu('logged');
$p->printHeader();
?>
<h3 class="p-title">Servizio Pre / Post scuola <small>registro presenze</small></h3>

<div class="panel panel-default">
    <div class="panel-heading">
        <form data-role="form" id="dateForm" class="form-horizontal" action="./" onSubmit="return post(this,'f-result')">
            <div class="row">
                <label class="control-label col-sm-1">Classe</label>
                <div class="col-sm-5">
                    <select class="form-control" name="grp">
                        <option value=""></option>
                        <?php
                            foreach(get_sottogruppi('pps') as $grp_id => $v){
                                echo '<optgroup label="'.entities($v['name']).'">';
                                    foreach($v['sub'] as $sub_id => $sub_name){
                                        $sel = $grp_allowed[$sub_id] ? ' selected' : '';
                                        echo '<option value="'.$sub_id.'"'.$sel.'>'.entities($sub_name).'</option>';
                                    }
                                echo '</optgroup>';
                            }
                        ?>
                    </select>
                </div>
                <label class="control-label col-sm-offset-1 col-sm-1">Data</label>
                <div class="col-sm-4 col-md-3">
        
                    <div class="input-group">
                        <span class="input-group-btn">
                            <button class="btn btn-default btn-primary" id="date-btn" type="button" data-date="<?php echo date("d/m/Y");?>" data-date-format="dd/mm/yyyy">
                                <span class="glyphicon glyphicon-calendar"></span>
                            </button>
                        </span>
                        <input class="form-control" name="data" id="data" size="16" value="<?php echo date("d/m/Y");?>" readonly type="text">
                        <span class="input-group-btn">
                            <button class="btn btn-default btn-primary" type="submit">
                                <span class="glyphicon glyphicon-chevron-right"></span>
                            </button>
                        </span>
                    </div>
                </div>
            </div>
        </form>
    </div>



	<div class="panel-body">
        <form class="form-horizontal" data-role="form" action="<?php echo $_SERVER['REQUEST_URI'];?>" onSubmit="return post(this,'f-result')">
            <div id="f-result">
	            <div class="alert alert-info">Seleziona una classe e una data da visualizzare</div>
            </div>
            <div class="form-buttons m-top-10">
           		<button type="submit" id="btn-save" class="btn btn-primary hidden">Salva</button>
                <button type="button" class="btn btn-default" onClick="window.history.back()">Torna al menu</button>
            </div>
       		<input type="hidden" id="save_grp" name="grp">
       		<input type="hidden" id="save_data" name="data">
         </form>
	</div>
</div>
<script>
var arr = new Array();
arr[''] = 'hidden'; //notfound
arr['P'] = 'visible';

$('body').on('click','.btn-presenze',function(){
	var current_val = $(this).next('input').val();
	var index = 0;
	var founded = false;

	for(var x in arr){
		if(founded){
			$(this).next('input').val(x);
			$(this).find('span').css('visibility',arr[x]);
			return;
		}
		if(x == current_val)
			founded = true;

		index++;
	}
	
	$(this).next('input').val('');
	$(this).find('span').css('visibility','hidden');
	
});
</script>
<?php
$p->printFooter();
?>