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

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 mensa
	$anagrafiche = get_anagr(false,array('flt_serv_cod'=>'men','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]);
				$comune_id = intval($_POST['comune'][$anagr_id]);
			
				if(!empty($val)){
					
					$mysqli->query("INSERT INTO serv_men_presenze (id, anagr_id, comune_id, status, date) VALUES(".dbClean($presenza_id).", ".$anagr_id.", ".$comune_id.", ".dbClean($val).",'".$date."') ON DUPLICATE KEY UPDATE status=".dbClean($val));
				}else if($presenza_id > 0){
					$mysqli->query("DELETE FROM serv_men_presenze WHERE id = ".intval($presenza_id));	
				}
			}
		}
		
	}

	//estraggo presenze per questo giorno
	$presenze = get_presenze($grp,$date);
	$presenze_name = array(''=>'?','P' => 'PRESENTE', 'S' => 'SENZA BUONO', 'A' => 'ASSENTE', 'G' => 'ASSENTE GIUSTIFICATO');

	foreach($anagrafiche['list'] as $v){
		$grp_name = $v['gruppo'];
		$grp_sub_name = $v['sottogruppo'];
		
		$comune_id = $presenze[$v['anagr_id']]['comune_id'] ? $presenze[$v['anagr_id']]['comune_id'] : $v['comune_id'];
		$status = $presenze[$v['anagr_id']]['status'];
		$anagr_id = $presenze[$v['anagr_id']]['id'];
		$status_name = $presenze_name[$presenze[$v['anagr_id']]['status']];
		
		if($status == 'P' || $status == 'S')
			$n_presenze++;
		
		$content .= '
		<div class="col-md-6">
			<div class="row">
				<div class="col-sm-4 col-md-6 col-lg-5"><label class="control-label">'.$v['anagr_cognome'].' '.$v['anagr_nome'].'</label></div>
				<div class="col-sm-4 col-md-6 col-lg-5 p-bottom-5">
					<button type="button" class="btn btn-info btn-asm btn-block btn-presenze">
						<span>'.$status_name.'</span>
					</button>
					<input name="opt['.$v['anagr_id'].']" value="'.$status.'" type="hidden">
					<input name="id['.$v['anagr_id'].']" value="'.$anagr_id.'" type="hidden">					
					<input name="comune['.$v['anagr_id'].']" value="'.$comune_id.'" type="hidden">					
				</div>
				<div class="col-lg-2 col-visible-inline-lg"></div>
			</div>
		</div>
		';
	}
	
	echo '<h4 class="top text-center text-danger">'.giorno_ita($date).' '.$_POST['data'].'</h4>';
	echo '<div class="row m-bottom-10">'.$content.'</div>';
	echo '<div class="m-bottom-10 m-top-10 text-info">Totale presenti alla mensa: <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 Mensa <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('men') 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[''] = ''; //notfound
arr['P'] = 'PRESENTE';
arr['S'] = 'SENZA BUONO';
arr['A'] = 'ASSENTE';
arr['G'] = 'ASSENTE GIUSTIFICATO';

$('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').text(arr[x]);
			return;
		}
		if(x == current_val)
			founded = true;

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