<?php
checkLogin('usr');
$serv_cod = 'men';
checkEnteService($serv_cod);
include("functions.inc.php");
include(ROOT."/includes/modules/anagrafiche/functions.inc.php");
include(ROOT."/includes/modules/servizi/functions.inc.php");

$anagr_id = intval($_REQUEST['id']);	

//cerco fra le mie anagrafiche di questo servizio
if($anagr_id > 0){
	check_my_anagr($anagr_id);
}else if($anagr = get_anagr(false,array('flt_serv_cod'=>$serv_cod))){
	$anagr = current($anagr['list']);
	$anagr_id = $anagr['anagr_id'];
}

//elimina
if(isset($_GET['del'])){
	$serv_id = get_servizio_id($serv_cod);
	$mysqli->query("DELETE FROM servizi_anagr WHERE anagr_id = ".$anagr_id." AND serv_id=".$serv_id);	
	clear_anagr_servizi($anagr_id);	
	usrlog("Servizio ".get_serv_name($serv_cod)." - Alunno: %s. Eliminato dal servizio",$anagr_id,true); //log 
	Js('window.location="./"');
	die();
}

//estraggo impostazioni
$s = get_servmen($anagr_id);

//salvo impostazioni
if(isset($_POST['save'])){
	
	$anagr_has_serv = anagr_has_serv($anagr_id,$serv_cod);
	if(!$anagr_has_serv){
		
		if(intval($_POST['scuola']) == 0)
			printParentJsError('Selezionare la <strong>Scuola frequentata</strong>',"danger");
		if(intval($_POST['classe']) == 0)
			printParentJsError('Selezionare la <strong>Classe frequentata</strong>',"danger");
		
		$result = $mysqli->query("INSERT INTO serv_".$serv_cod." (anagr_id,scuola_id,classe_id) VALUES (".$anagr_id.",".intval($_POST['scuola']).",".intval($_POST['classe']).")");
		if(!$result)
			printParentJsError("Errore durante il salvataggio, contattare l'Ente","danger");
		
		//assegnazione al servizio
		if(!assign_anagr_servizio($anagr_id,$serv_cod))
			printParentJsError("Errore durante l'assegnazione al servizio, contattare l'Ente","danger");

	}
	
	$result = $mysqli->query("
	UPDATE serv_men SET
	servmen_sospeso = ".intval($_POST['sospeso']).",
	servmen_esente = ".intval($_POST['esente']).",
	servmen_note = ".dbClean($_POST['note'])."
	WHERE anagr_id = ".$anagr_id);

	if(!$result)
		printParentJsError("Errore durante il salvataggio","danger");
	
	//log sospensione
	if($s['servmen_sospeso'] <> intval($_POST['sospeso'])){
		if(intval($_POST['sospeso']) == 1)
			usrlog("Servizio ".get_serv_name($serv_cod)." - Alunno: %s. Sospeso il servizio",$anagr_id,true); //log 
		else
			usrlog("Servizio ".get_serv_name($serv_cod)." - Alunno: %s. Ripreso il servizio",$anagr_id,true); //log 
	}
	
	//modulistica
	$uploaded = rearrange($_FILES['allegato']);
	$attach_names = get_servmen_attach();
	$anagr_attachments = get_servmen_attach($anagr_id);
	$dest_dir = realpath(ROOT.'/userfiles/allegati/');

	//elimino quelli da eliminare
	foreach($_POST['f-label'] as $k=>$v){
		if(empty($v) || !empty($uploaded[$k]['name'])){
			$result = $mysqli->query("SELECT * FROM attachments WHERE anagr_id = ".$anagr_id." AND attach_id = '".$k."'");
			if($result->num_rows == 1){
				$row = $result->fetch_assoc();
				unlink($dest_dir.'/'.$row['att_fname']);
				$mysqli->query("DELETE FROM attachments WHERE att_id = ".$row['att_id']);
			}
		}
	}

	if($uploaded){
		
		foreach($uploaded as $k=>$v){
			if(!empty($v['name'])){
	
				if(!$attach_name = $attach_names[$k]['attach_name'])
					printParentJsError("Errore durante il caricamento del modulo");
		
				if($v['error'] > 0)
					printParentJsError("Errore durante il caricamento del modulo <strong>".$name."</strong>");
					
				$ext = getExt($v['name']);
				
				$allowed_ext = array('pdf','jpg','jpeg','png','doc','docx');
				if(!in_array($ext,$allowed_ext))
					printParentJsError("Errore durante il caricamento del modulo <strong>".$name."</strong>:<br />Tipo di file non supportato, sono ammessi solo PDF, DOC, DOCX, JPG, PNG'");
					
				if($v['size'] > 3000000)
					printParentJsError("Errore durante il caricamento del modulo <strong>".$name."</strong>:<br />Dimensioni del file troppo grandi, massimo consentito 3 Mb");
				
				$fname = $anagr_id.'_intoll-'.$k.'.'.strtolower($ext);
				$dest_path = $dest_dir.'/'.$fname;
	
				if(move_uploaded_file($v["tmp_name"], $dest_path)){
					$mysqli->query("INSERT INTO attachments VALUES (NULL,".$anagr_id.",'".$fname."','".$k."',NULL)");
					Js('parent.attachUploaded("f-label['.$k.']",'.$mysqli->insert_id.')');
				}else{
					printParentJsError("Errore durante il caricamento del modulo <strong>".$name."</strong>");
				}
			}
		}
		if($ext)
			usrlog("Servizio ".get_serv_name($serv_cod)." - Alunno: %s. Caricato modulo intolleranze",$anagr_id,true); //log 
	}

	Js('parent.$(".hide-on-save").hide();');

	if(isset($_GET['newanagr']))
		printParentJsError("<strong>Complimenti, l'iscrizione al servizio Mensa &egrave; avvenuta con successo!</strong><br /><br />Ti ricordiamo che, se vorrai apportare modifiche, potrai potrai farlo direttamente da questa applicazione","success");
	else
		printParentJsError("Salvataggio modifiche avvenuto con successo!","success");
	die();
}

include("menu.inc.php");
$p = new Page('Servizio Mensa');
$p->addMenu('logged');
$p->addModuleJs('script','servizi');
$p->printHeader();
?>

<div class="row">
    <div class="col-xs-9 col-sm-10">
		<h3 class="p-title"><a class="btn-back" href="../../home/usr/"><span class="glyphicon glyphicon-chevron-left"></span></a> Servizio Mensa</h3>
    </div>
	<div class="col-xs-3 col-sm-2"><?php print_optMenu('usr_conf');?></div>
</div>

<div class="panel panel-default">
	<div class="panel-body">
	
    <?php if($anagr_id > 0) : ?>
    
	<form role="form" class="form-horizontal" method="post" name="anagr_serv" action="<?php echo $_SERVER['REQUEST_URI'];?>" enctype="multipart/form-data" target="uplifra">
        
		<?php print_serv_anagr_select($anagr_id,$serv_cod); ?>
        <div class="hide-on-save">
        <div class="form-group form-subtitle"><h4>Scuola frequentata</h4></div>
        
        <ul class="list-group">
            <li class="list-group-item">                
                <div class="row no-readonly">
                    <div class="col-sm-8">
                        <div class="row">
                        	<label class="control-label col-sm-2 xs-ptop-0">Scuola</label>
                            <div class="col-sm-8">
                        		<?php 
								foreach(get_gruppi($serv_cod) as $grpid=>$name){

									if($grpid == $s['scuola_id']){
										$scuola = $name;
										$sel = ' selected';
									}else{
										$sel = '';	
									}
									$opts_scuola .='<option value="'.$grpid.'"'.$sel.'>'.$name.'</option>';

								}
								
								if(!$s['scuola_id']) {
									echo '
									<select class="form-control" name="scuola" onChange="selXmlPop(\'#classe\',\'sottogruppi\',this.value)">
									<option value=""></option>'.$opts_scuola.'</select>';
									
								}else{
									echo '<p class="form-control-static">'.$scuola.'</p>';
								}
								?>
                                
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-sm-4">
                        <div class="row">
                        	<label class="control-label col-sm-4">Classe</label>
                            <div class="col-sm-8">
                        		<?php 
								if(!$s['scuola_id']) {
									echo '<select class="form-control" name="classe" id="classe" disabled></select>';
								}else{
									$gruppi = get_gruppi($serv_cod,$s['scuola_id']);
									echo '<p class="form-control-static">'.$gruppi[$s['classe_id']].'</p>';
								}
								?>
                            </div>
                        </div>
                    </div>
                </div>
            </li>
        </ul>

    	<div class="row">
			<div class="col-sm-6">

        		<div class="form-group form-subtitle"><h4>Impostazioni servizio</h4></div>
	            
                <ul class="list-group">
                    <li class="list-group-item">
                        <div class="row">
                            <label class="control-label col-xs-6 col-md-4" for="sospeso">Sospendi</label>
                            <div class="col-xs-6 col-sm-6 col-md-4 text-right">
                                <input onChange="servsosp(this)" type="checkbox" id="sospeso" name="sospeso" value="1" class="switch-btn"<?php if($s['servmen_sospeso'] == 1) echo ' checked';?> />
                            </div>
                        </div>
                    </li>
                </ul>
                
            </div>
        </div>    

        <div class="form-group form-subtitle"><h4>Moduli allergie alimentari</h4></div>
        <div class="form-block-descr">
        In caso di <strong>allergie / intolleranze alimentari</strong>, per l'accesso al servizio mensa occorrer&agrave; <span class="glyphicon glyphicon-download text-danger"></span> <strong class="text-danger">Scaricare</strong> la modulistica seguente e <strong><span class="text-primary">Ricaricarla</span>, timbrata e firmata dal medico curante</strong>
        </div>
        
        <ul class="list-group">
            <?php
			$serv_attachs = get_servmen_attach();
			$anagr_attachs = get_servmen_attach($anagr_id);

			foreach($serv_attachs as $attach_id=>$v){
				
				if($anagr_attachs[$attach_id]){
					$label = 'Modulo caricato';
					$show_upl_btn = " hidden";
					$show_del_btn = "";
				}else{
					$label = '';
					$show_upl_btn = "";
					$show_del_btn = " hidden";
				}

				echo '
					<li class="list-group-item">
						<div class="form-group">
							
							<div class="col-md-6">
								<label class="control-label label-slim">'.$v['attach_name'].'</label>
								<div><a href="/download/?module=intolleranze-'.strtolower($attach_id).'.pdf" class="text-danger"><span class="glyphicon glyphicon-download"></span> Scarica</a></div>
							</div>
							
							<div class="col-md-6">
								<div class="input-group">
									<span class="input-group-btn'.$show_upl_btn.'">
										<span class="btn btn-primary btn-file">
											Carica... <input class="f-name" type="file" name="allegato['.$attach_id.']">
										</span>
									</span>
									<input class="form-control f-label" readonly="" type="text" name="f-label['.$attach_id.']" value="'.$label.'">
									<span class="input-group-btn'.$show_del_btn.'">
										<button type="button" class="btn btn-info show-doc" onClick="goto(\'/download/?id='.$anagr_attachs[$attach_id]['att_id'].'\')">
											<span class="glyphicon glyphicon-search"></span>
										</button>
										<button type="button" class="btn btn-danger" onClick="removeAttach(this)">
											<span class="glyphicon glyphicon-remove"></span>
										</button>
									</span>
								</div>
							</div>
						</div>
					</li>
				';	
			}
			?>

            <li class="list-group-item">
                <div class="form-group">
                    <label class="control-label col-sm-3 xs-ptop-0">Richieste particolari</label>
                    <div class="col-sm-9">
                        <textarea  style="height:60px" name="note" class="form-control"><?php echo $s['servmen_note'];?></textarea>
                    </div>
                </div>
            </li>
        </ul>
		</div>

		<div id="result_anagr_serv"></div>
        
        <div class="form-buttons">
            <button type="submit" class="btn btn-primary hide-on-save">Salva</button>
            <button type="button" class="btn btn-default" onClick="goto('../../home/usr/')">Torna al menu</button>
        </div>
        
        <input type="hidden" name="save" value="1" />
        <input type="hidden" name="id" value="<?php echo $anagr_id;?>" />
    	<input type="hidden" name="MAX_FILE_SIZE" value="3000000" />
	</form>
    <iframe name="uplifra" src="blank.html" class="uplifra"></iframe>
 
 
 	<?php else : ?>
    <div class="alert alert-info"><h4>Devi effettuare una registrazione al servizio Mensa?</h4>Allora clicca sul pulsante verde <strong> Opzioni <span class="glyphicon glyphicon-cog"></span> </strong>, in alto a destra, e scegli <strong>Nuova iscrizione</strong></div>
    <div class="text-center">
        <a href="../../home/usr/" class="btn btn-default">Pagina principale</a>
    </div>
    <?php endif ?>
 
    
    </div>
</div>

<script>
$(function(){
	servsosp($('[name="sospeso"]'));
});
</script>
<?php
$p->printFooter();
?>
