<?php
checkLogin('adm');
include(ROOT."/includes/modules/servizi/functions.inc.php");
include(ROOT."/includes/sms.inc.php");
include("menu.inc.php");

//popolo gruppi
if(isset($_GET['populate'])){
	foreach(get_sottogruppi(dbClean($_GET['populate'],false)) as $grp_id => $v){
		$childrens = array();
		foreach($v['sub'] as $sub_id => $sub_name)
			$childrens[] = array('label'=>entities($sub_name),'value'=>$sub_id);
			
		$row[] = array('title'=>entities($v['name']),'children'=>$childrens);
	}

	echo json_encode($row);	
	die();
}

//invio SMS
if(isset($_POST['text-msg'])){
	
	if(is_empty($_POST['text-msg']))
		die();
	
	//ho selezionato un servizio
	if($_POST['servizio'] <> 'all'){
		
		checkEnteService($_POST['servizio']);
		$serv_cod = $_POST['servizio'];

		$table = "serv_".$serv_cod;
		$join = "LEFT JOIN ".$table." ON anagrafiche.anagr_id = ".$table.".anagr_id";
		$w .= " AND ".$table.".classe_id IS NOT NULL";
		
		//ho selezionato dei gruppi
		if(count($_POST['grp'])>0){
			
			
			foreach($_POST['grp'] as $id){
				$ids[] = intval($id);
			}
			$w .= " AND ".$table.".classe_id IN (".implode(",",$ids).")";
		}

		
	}
	
	$result = $mysqli->query($q="
	SELECT user_cell FROM users 
	LEFT JOIN anagrafiche ON users.user_id = anagrafiche.user_id
	".$join."
	WHERE 
	users.user_cell REGEXP '^[0-9]{10}$' AND
	anagrafiche.ente_id = ".$_SESSION['user']['ente_id']." 
	".$w."
	GROUP BY users.user_id
	");
	
	$n = $result->num_rows;
	
	if($n>0){
		while($row = $result->fetch_assoc())
			$tel[] = $row['user_cell'];
		
		$numeri = implode(",",$tel);
		
		//abilitato solo online
		if($_SERVER['HTTP_HOST'] == 'www.servizicittadino.it'){
			
			if(!sendSMS($_GET['e'],$_POST['text-msg'],$numeri)){
				$msg = "Errore durante l'invio degli SMS";
			}else{
				date_default_timezone_set('Europe/Rome');
				$date = date("Y-m-d H:i:s");
				$mysqli->query("INSERT INTO sms_archive VALUES (NULL,".$_SESSION['user']['ente_id'].",".$_SESSION['user']['id'].",".dbClean($_POST['text-msg']).",".$n.",'".$date."')");
				$msg = "Inviati correttamente " . $n . " messaggi!";
			}
		}else{
			$msg = "DEMO INVIO - Servizio non abilitato. (" . $n . ")";
		}
		
	}else{
		$msg = "Nessun utente corrispondente.";
	}
	
	Js('$("#sms-grp").show();alert("'.$msg.'");');
	die();
}

$p = new Page('Invio SMS');
$p->addMenu('logged');
$p->addModuleJs('script');
$p->addJs('bootstrap-multiselect');
$p->addCss('bootstrap-multiselect');

if(!empty($_GET['id'])){
	$result = $mysqli->query("SELECT sms_text FROM sms_archive WHERE sms_id = ".intval($_GET['id'])." AND ente_id = ".$_SESSION['user']['id']);	
	$text = entities($result->fetch_object()->sms_text);
}


$p->printHeader();

?>
<div class="row">
	<div class="col-xs-9 col-sm-10">
		<h3 class="p-title">Invio SMS</h3>
    </div>
	<div class="col-xs-3 col-sm-2"><?php print_optMenu('adm_home');?></div>
</div>
    
<form data-role="form" id="SMSform" class="form-horizontal panel panel-default" action="./" onSubmit="return post(this,'f-sms-result')">

    <div class="panel-heading">
            <div class="row">
                <label class="control-label col-sm-1">Servizio</label>
                <div class="col-sm-5">
                    <select class="form-control" name="servizio" onChange="populateGrp(this.value)">
                        <option value="all">Invia a tutti</option>
                        <?php
                            foreach(get_ente_servizi() as $v)
                            echo '<option value="'.$v['serv_cod'].'">'.entities($v['serv_name']).'</option>';
                        ?>
                    </select>
                </div>
        
                <label class="control-label col-sm-1">Gruppi</label>
                <div class="col-sm-5">
                    <select class="multiselect" disabled id="sel-grp" name="grp[]" multiple size="5"></select>
                </div>

            </div>
    </div>

    <div class="panel-body">
        
        <div id="sms-grp">
            <div class="form-group">
                <label class="control-label col-sm-12">Testo del messaggio</label>
                <div class="col-sm-7 col-md-6 col-lg-5">
                    <textarea name="text-msg" id="text-msg" class="form-control" rows="5"><?php echo $text;?></textarea>
                    <div class="help-block">Caratteri: <span id="text-count">0</span>/160</div>
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-12"></div>
            </div>
            <div class="form-group">
                <div class="col-sm-12"><button type="button" class="btn btn-primary" onClick="confirmSMS()">Invia SMS</button></div>
            </div>
        </div>
        
        <div id="f-sms-result"></div>
    </div>
    
</form>
<?php
$p->printFooter();
?>