<?php
checkLogin('adm');
include("functions.inc.php");

//edit
if(intval($_REQUEST['id']) > 0){
	$anagr_id = intval($_REQUEST['id']);
	$edit = true;
}

if(isset($_GET['del'])){
	if(del_anagr($anagr_id)){
		Js('window.history.back();');
	}else{
		Js('closeDialog();');
		printMsg("Errore durante l'eliminazione dell'anagrafica","danger");
	}
	die();
}

//salvataggio anagrafica
if(isset($_POST['nome'])){
	
	if(empty($_POST['nome']))
		printMsg("Completare il campo Nome",'danger');
	if(empty($_POST['cognome']))
		printMsg("Completare il campo Cognome",'danger');
	if(empty($_POST['indirizzo']))
		printMsg("Completare il campo Indirizzo",'danger');
	if(empty($_POST['provincia']))
		printMsg("Selezionare la Provincia residenza",'danger');
	if(empty($_POST['comune']) && $_POST['provincia'] <> 111)
		printMsg("Selezionare il Comune residenza",'danger');
	if(!is_codfis($_POST['codfis']))
		printMsg("Inserire il Codice fiscale corretto",'danger');
	if(!$_REQUEST['id'] && count($_POST['servizio']) == 0)
		printMsg("Selezionare almeno un servizio a cui associare l'anagrafica",'danger');
	
	###### UPDATE ANAGRAFICA ######
	if($edit){
		$result = $mysqli->query("UPDATE anagrafiche SET 
		anagr_nome = ".dbClean(welltxt($_POST['nome'])).",
		anagr_cognome = ".dbClean(welltxt($_POST['cognome'])).",
		anagr_codfis = ".dbClean($_POST['codfis']).",
		anagr_ind = ".dbClean(welltxt($_POST['indirizzo'])).",
		provincia_id = ".intval($_POST['provincia']).",
		comune_id = ".intval($_POST['comune']).",
		anagr_codfis = ".dbClean(strtoupper($_POST['codfis']))."
		WHERE anagr_id = ".$anagr_id." AND ente_id = ".$_SESSION['user']['ente_id']);


	###### NUOVA ANAGRAFICA ######
	}else{
		
		//controllo codice fiscale non sia gia in uso
		$result = $mysqli->query("SELECT * FROM anagrafiche WHERE anno=".$_SESSION['user']['ente_anno']." AND anagr_codfis = ".dbClean(strtoupper($_POST['codfis'])));
		if($result->num_rows > 0)
			printMsg("Codice fiscale gi&agrave; in uso",'danger');
		
		$result = $mysqli->query("INSERT INTO anagrafiche (anagr_nome,anagr_cognome,anagr_ind,anagr_codfis,provincia_id,comune_id,ente_id,anno) VALUES (
		".dbClean(welltxt($_POST['nome'])).",
		".dbClean(welltxt($_POST['cognome'])).",
		".dbClean(welltxt($_POST['indirizzo'])).",
		".dbClean(strtoupper($_POST['codfis'])).",
		".intval($_POST['provincia']).",
		".intval($_POST['comune']).",
		".$_SESSION['user']['ente_id'].",
		".$_SESSION['user']['ente_anno']."
		)");
		
		$anagr_id = $mysqli->insert_id;
		$_SESSION['current_anagr'] = $anagr_id;
	}
	
	if($result){

		add_anagr_servizi($anagr_id,$_POST['servizio']);
		Js('enableConf('.$anagr_id.');');
		
		//se non e' una modifica, mostro il pulsante per un nuovo inserimento
		if(!$edit)
			Js("$('#btn-reset').removeClass('hidden')");

		printMsg("Salvataggio avvenuto con successo!",'success');

	}

	printMsg("<strong>Attenzione!</strong> Errore durante il salvataggio. Contattare l'amministratore",'danger');
	
}

include("menu.inc.php");
$p = new Page('Anagrafica');
$p->addModuleJs('script');
$p->addModuleJs('script','servizi');
$p->addModuleJs('script','users');
$p->addMenu('logged');
$p->printHeader();
?>
<div class="row">
	<div class="col-xs-9 col-sm-10">
		<h3 class="p-title">Anagrafica</h3>
    </div>
	<div class="col-xs-3 col-sm-2"><?php print_optMenu('adm_add');?></div>
</div>
<?php print_optMenu('anagrafiche'); ?>
<div class="panel panel-default">
	<div class="panel-body">
		
		<?php if(($edit && $anagr = get_anagr($anagr_id)) || !$edit) : ?>
        
        <form id="form_anagr" class="form-horizontal" action="./" role="form" onSubmit="return post(this,'f-result')">
            <div class="form-group">
                <div class="col-sm-4">
                    <label class="control-label">Nome</label>
                    <input class="form-control" type="text" maxlength="40" name="nome" value="<?php echo entities($anagr['anagr_nome']);?>" />
                </div>
                <div class="col-sm-4">
                    <label class="control-label">Cognome</label>
                    <input class="form-control" type="text" maxlength="40" name="cognome" value="<?php echo entities($anagr['anagr_cognome']);?>" />
                </div>
                <div class="col-sm-4">
                    <label class="control-label">Codice fiscale</label>
                    <input class="form-control" type="text" maxlength="40" name="codfis" value="<?php echo entities($anagr['anagr_codfis']);?>" />
                </div>
            </div>
                
            <div class="form-group-inline">
                <div class="form-group">
                    <div class="col-sm-6">
                        <label class="control-label">Indirizzo di Residenza</label>
                        <input class="form-control" type="text" maxlength="40" name="indirizzo" value="<?php echo entities($anagr['anagr_ind']);?>" />
                    </div>
                    <div class="col-sm-6">
                        <label class="control-label">Provincia residenza</label>
                        <select class="form-control" name="provincia" onChange="selXmlPop('#sel_comune','comuni',this.value)">
                            <option value=""></option>
                            <?php print_province_opts($anagr['provincia_id']) ;?>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-6">
                        <label class="control-label">Comune di Residenza</label>
                        <select class="form-control" name="comune" id="sel_comune">
                            <option value=""></option>
                            <?php 
							if($anagr['provincia_id'])
								print_comuni_opts($anagr['provincia_id'],$anagr['comune_id']);
							?>
                        </select>
                    </div>
                    <div class="col-sm-6">
                        <label class="control-label">Inserita da</label>
                        
                        <div class="input-group">
							<?php if($anagr['user_id'] <> NULL) : ?>
                                <input type="text" readonly class="form-control" id="owner-name" value="<?php echo entities($anagr['user_cognome'].' '.$anagr['user_nome']);?>">
                            <?php else: ?>
                                <input type="text" readonly class="form-control" id="owner-name" value="Amministratore">
                            <?php endif ?>
                            <span class="input-group-btn">
                                <button class="btn btn-warning" onClick="showOwner(1)" type="button">
                                	<span class="glyphicon glyphicon-refresh"></span>
                                </button>
                                <button class="btn btn-info" onClick="showOwner()" type="button">
                                	<span class="glyphicon glyphicon-search"></span>
                                </button>
                            </span>
                        </div>
                    </div>
                </div>

			</div>
			
            <div id="services-conf">
            
                <div class="form-group form-subtitle"><h4>Servizi attivi</h4></div>
                <ul class="list-group">
                
                <?php
                $serv_ente = get_ente_servizi();
                if(count($serv_ente) > 0){
    
                    $serv_anagr = get_anagr_servizi($anagr['anagr_id']);
									
                    foreach($serv_ente as $k=>$v){
                        
                        //$disabled = !$serv_anagr[$k] && !$anagr_id ? ' disabled' : '';

                        
                        if($serv_anagr[$k]){
                            $checked = ' checked';
							$hidden = '';
							$disabled = '';
                        }else{
                            $checked = '';
							$hidden = ' hidden';
							$disabled = ' disabled';
                        }
						
                        echo '
                            <li class="list-group-item">
                                <div class="row">
                                    <label class="control-label xs-ptop-0 col-sm-3 col-md-2" for=""s'.$v['serv_id'].'"">'.$v['serv_name'].'</label>
                                    <div class="col-sm-9 col-md-10">
                                        <input type="checkbox" id="s'.$v['serv_id'].'" name="servizio[]" value="'.$v['serv_id'].'" class="switch-btn"'.$checked.'>
                                        <button'.$disabled.' type="button" class="opt-btn m-left-10 btn btn-info'.$hidden.'" onClick="servconfig(\''.$v['serv_cod'].'\')">
											<span class="glyphicon glyphicon-cog"></span>
										</button>
                                    </div>
                                </div>
                            </li>
                        ';
                    }
                }
                ?>
                </ul>
            </div>
            <div id="f-result"></div>
            <div class="form-buttons">
                <button type="submit" class="btn btn-primary">Salva</button> 
                <button type="button" class="btn btn-default hidden" id="btn-reset" onClick="resetForm('form_anagr'); $(this).addClass('hidden');">Nuova anagrafica</button> 
                <button type="button" class="btn btn-default" onClick="history.back();">Indietro</button> 
            </div>
            
            <input type="hidden" name="id" id="anagr_id" value="<?php echo $anagr_id;?>" />
            <input type="hidden" id="owner-id" value=" <?php echo $anagr['user_id'];?>" />
           
    	</form>
		<?php  
		else : 
			printMsg("Impossibile trovare l'anagrafica desiderata","warning",false);	
		endif 
		?>
    </div>
</div>
<?php
$p->printFooter();
?>