<?php
include("../../../functions.inc.php");
checkLogin('adm');
checkEnteService('men');
include("../functions.inc.php");
include("../../anagrafiche/functions.inc.php");
include("../../servizi/functions.inc.php");

dbConnect();
check_my_anagr($_GET['id']);

//salvo impostazioni
if(isset($_POST['save'])){

	$anagr_id = intval($_REQUEST['id']);
	
	if(!anagr_has_serv($anagr_id,'men'))
		printParentJsError('Utente non associato a questo servizio',"danger");
	
	if(intval($_POST['scuola']) == 0)
		printParentJsError('Selezionare la Scuola',"danger");
	if(intval($_POST['classe']) == 0)
		printParentJsError('Selezionare la Classe',"danger");
	
	$result = $mysqli->query("
	UPDATE serv_men SET
	scuola_id = ".intval($_POST['scuola']).",
	classe_id = ".intval($_POST['classe']).",
	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');

	//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']);
			}
		}
	}

	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>");
			}
		}
	}
	
	Js('parent.closeDialog();');
	die();

}

//estraggo impostazioni
$s = get_servmen($_GET['id']);
?>
<div>
    <div class="modal-d-title">Servizio Mensa</div>
	<form role="form" class="form-horizontal" method="post" name="anagr_serv" action="<?php echo $_SERVER['REQUEST_URI'];?>" enctype="multipart/form-data" target="uplifra">
    <div class="modal-body modal-body-diag">    

        <div class="form-group form-subtitle"><h4>Scuola frequentata</h4></div>
        
        <ul class="list-group">
            <li class="list-group-item">
                <div class="row">
                    <div class="col-sm-8">
                        <div class="row">
                        	<label class="control-label col-sm-3 xs-ptop-0">Scuola</label>
                            <div class="col-sm-8">
                        		<select class="form-control" name="scuola" onChange="selXmlPop('#classe','sottogruppi',this.value)">
                                <option value=""></option>
                                <?php
								foreach(get_gruppi('men') as $grpid=>$name){
									$sel = $grpid == $s['scuola_id'] ? ' selected' : '';
									echo '<option value="'.$grpid.'"'.$sel.'>'.$name.'</option>';
								}
								?>
                                </select>
                            </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">
                        		<select class="form-control" name="classe" id="classe"<?php if(!$s['scuola_id']) echo ' disabled'; ?>>
                                <option value=""></option>
                                <?php
								if($s['scuola_id']){
									foreach(get_gruppi('men',$s['scuola_id']) as $grpid=>$name){
										$sel = $grpid == $s['classe_id'] ? ' selected' : '';
										echo '<option value="'.$grpid.'"'.$sel.'>'.$name.'</option>';
									}
								}
								?>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>
            </li>
        </ul>

        <div class="form-group form-subtitle"><h4>Impostazioni servizio</h4></div>
    	<div class="row">
			<div class="col-sm-6">

	            
                <ul class="list-group">
                    <li class="list-group-item">
                        <div class="row">
                            <label class="control-label col-xs-6 col-md-8" for="sospeso">Sospendi</label>
                            <div class="col-xs-3 col-sm-5 col-md-4 col-lg-3">
                                <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 class="col-sm-6">
                <ul class="list-group">
                    <li class="list-group-item">
                        <div class="row">
                            <label class="control-label col-xs-6 col-md-8" for="esente">Esente pagamento</label>
                            <div class="col-xs-3 col-sm-5 col-md-4 col-lg-3">
                                <input type="checkbox" name="esente" id="esente" value="1" class="switch-btn"<?php if($s['servmen_esente'] == 1) echo ' checked';?> />
                            </div>
                        </div>
                    </li>
                </ul>
            </div>
        </div>  
        
        <div class="form-group form-subtitle"><h4>Moduli allergie alimentari</h4></div>
        
        <ul class="list-group">
            <?php
			$serv_attachs = get_servmen_attach();
			$anagr_attachs = get_servmen_attach($_GET['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">
							<label class="control-label label-slim col-md-6">'.$v['attach_name'].'</label>
							<div class="col-md-6">
								<div class="input-group">
									<span class="input-group-btn'.$show_upl_btn.'">
										<span class="btn btn-primary btn-file">
											Seleziona... <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 id="result_anagr_serv"></div>
        
	</div>
    
    <div class="modal-footer">
        <button type="submit" class="btn btn-primary">Salva</button>
        <button type="button" class="btn btn-default" data-dismiss="modal">Chiudi</button>
    </div>
    <input type="hidden" name="save" value="1" />
    <input type="hidden" name="MAX_FILE_SIZE" value="3000000" />
    </form>	
    <iframe name="uplifra" src="blank.html" class="uplifra"></iframe>
</div>
<script>
$(function(){
	servsosp($('[name="sospeso"]'));	
});
</script>