<div class="wrap">
<?php
    global $wpgamasms_option;
    global $gama_sms;

    echo "<h1 class='wp-heading-inline'>".get_admin_page_title()."</h1><br /><br />";

    $table2 = "{$wpdb->prefix}gamasms_subscribes_group";
    $table3 = "{$wpdb->prefix}gamasms_subscribes";

    $token = $wpgamasms_option['token'];


    $sql3 = "select * from $table2 order by name asc";
    $list_subscribes_group = $wpdb->get_results($sql3,ARRAY_A);
    // Para que no se produzcan errores cuando no hay datos
    if(empty($list_subscribes_group)){ 
       $list_subscribes_group = array();
    }

    //cantidad de usuarios activos
    $sql4 = "select count(*) as total from $table3 where status='1'";
    $list_subscribes = $wpdb->get_results($sql4,ARRAY_A);
       // Para que no se produzcan errores cuando no hay datos
    if(empty($list_subscribes)){ 
          $list_groups = array();
          $total_subscribes = 0;
    }else{
          $total_subscribes = $list_subscribes[0]['total'];
    }


    if(isset($_POST['btn-submit'])){
       //print_r($_POST);
       $sms_type = $_POST['sms_type'];
       $sms_numbers = $_POST['sms_numbers'];
       $messaggio = $_POST['messaggio'];
       $sms_text = gamasms_normaliza_mensaje( $messaggio );
	   $shortener = $_POST['shortener'];
	   $fields_string = "";

       $deldupl = $_POST['deldupl'];
       $send_to = $_POST['send_to'];

       // numeros telefonicos
       if($send_to == "numbers"){
           $numbers_array= preg_split("/[\s,]+/",$sms_numbers,-1,PREG_SPLIT_NO_EMPTY);

           if($deldupl=='t'){
               $numbers_array = array_keys(array_count_values($numbers_array));
           }

           foreach($numbers_array as $key=>$value) { 
               $fields_string .= $value.','; 
           }
           $fields_string = rtrim($fields_string,',');

           $sms_numbers = $fields_string;

       }

       // grupo de suscritores
       if($send_to == "subscribes_group"){
            $send_to_subscribes_group_id = $_POST['send_to_subscribes_group_id'];

            if($send_to_subscribes_group_id >= 0){
                $sql5 = "select * from $table3 where group_id='$send_to_subscribes_group_id' and status='1'";
                $list_subscribes = $wpdb->get_results($sql5,ARRAY_A);
            }else{ // all
                $sql5 = "select * from $table3 where status='1'";
                $list_subscribes = $wpdb->get_results($sql5,ARRAY_A);
            }

            // Para que no se produzcan errores cuando no hay datos
            if(empty($list_subscribes)){ 
                 $list_subscribes = array();
            }

            foreach($list_subscribes as $key => $value){
                     $mobile = $value['mobile'];
                     $fields_string .= $mobile.',';  
            }
            $fields_string = rtrim($fields_string,',');
            $sms_numbers = $fields_string;
       }
       

       if($shortener == 't'){
           $shorturl = 1;
       }else{
           $shorturl = 0;
       }

       $gama_sms->smsnumber = $sms_numbers;
       $gama_sms->smstext = $sms_text;
       $gama_sms->smstype = $sms_type;
       $gama_sms->shorturl = $shorturl;
       $result_text = $gama_sms->SendSMS();
	   
	   // Limpiar variables
	   $sms_numbers = "";
       $messaggio = "";
       $sms_text = "";	

       //echo "<p><div class='alert alert-info' role='alert'>".$result_text."</div></p>";
	   echo "<div class='notice notice-success'><p>".$result_text."</p></div>";

    }else{
		
       $sms_numbers = "";
       $messaggio = "";
       $sms_text = "";		
		
	}

    $result_balance = $gama_sms->BalanceSMS();

    if(!is_null($result_balance)){
        if($result_balance["message"] == 0){
           $numsms = $result_balance["numsms"];
           $num_sms_corto_disponibles = $numsms["numshort"];
           $num_sms_largo_disponibles = $numsms["numlong"];

            echo '<div class="welcome-panel row"><div class="col-md-3"><div class="panel panel-primary"><div class="panel-heading"><h3 class="panel-title">Mensajes Disponibles:</h3></div><div class="panel-body"><h3>SMS Remitente Corto:<span id="mySmsRC"> '.$num_sms_corto_disponibles.' </span></h3><h3>SMS Remitente Largo:<span id="mySmsRL"> '.$num_sms_largo_disponibles.' </span></h3></div></div></div>';

        }else{
            echo '<div class="welcome-panel row"><div class="col-md-3"><div class="panel panel-primary"><div class="panel-heading"><h3 class="panel-title">Cantidad de Mensajes Disponibles</h3></div><div class="panel-body"> No Hay informacion disponible.<br> Verifique la <a href="./admin.php?page=gamasms/admin/ConfigMenu.php">configuracion.</a></div></div></div>';
        }
	}else{
		echo '<div class="welcome-panel row"><div class="col-md-3"><div class="panel panel-primary"><div class="panel-heading"><h3 class="panel-title">Cantidad de Mensajes Disponibles</h3></div><div class="panel-body"> No Hay informacion disponible.<br> Verifique la <a href="./admin.php?page=gamasms/admin/ConfigMenu.php">configuracion.</a></div></div></div>';
	}

    // Por seguridad solo muestra esta pagina al administrador
    if(current_user_can('manage_options')){ 
?>

                  <div class="col-md-9"> 
                    <h3>Enviar SMS:</h3>               
                    <form class="form-horizontal" role="form" name="theForm" id="sms_form" accept-charset="UTF-8" method="POST">
                          <input type=hidden name="push_post" value='1'>
		          
                          <div class="form-group" id="my-sms-type">       
                               <div class="radio-group">                          
                                    <input class="radio-inline" type="radio" name="sms_type" id="sms-l" value="0" checked> <label for="sms-l"> Remitente Largo</label>
                                    <input class="radio-inline" type="radio" name="sms_type" id="sms-c" value="1"> <label for="sms-c"> Remitente Corto</label>
                                </div>
		          </div>

                  <div class="form-group" id="my-sms-to">    
                               <label for="send_to" >Para:</label>
                               <div class="form-inline">   
                               <select name="send_to" id="send_to" class="form-control" type="select">
                                     <option value="numbers">Numeros</option>
                                     <option value="subscribes_group">Suscriptores</option>
                                </select>
                               <select name="send_to_subscribes_group_id" id="send_to_subscribes_group_id" class="form-control" type="select" style="display:none">
                                     
                                     <?php
                                          echo '<option value="-1">Todos ( '.$total_subscribes.' suscriptores activos)</option>';
                                          foreach($list_subscribes_group as $key => $value){
                                                $id = $value['id'];
                                                $name = $value['name'];
                                                echo '<option value="'.$id.'">'.$name.'</option>';
                                           }
                                      ?>
                                </select>
                                </div>
		          </div>

                          <div class="form-group" id="my-dest">
		                 <textarea class="form-control" name="sms_numbers" id="sms_numbers" placeholder="numeros telefonicos separados por comas, espacios o nueva linea." rows="2"><?php echo $sms_numbers; ?></textarea>
                                 <input type="checkbox" id="deldupl" name="deldupl" value="t" checked> <label> Descartar numeros duplicados.<span class='glyphicon glyphicon-question-sign' data-toggle="tooltip" title="Util si desea que el sistema descarte numeros duplicados agregados en destinatarios."></span></label> 
		          </div>		          
                          
                          <div class="form-group" id="my-textarea">
                              <div class="row">
                                 <div class="col-md-12">
		                    <label>Mensaje:</label>
                                 </div>
                              </div>
		              <textarea class="form-control" name="messaggio" id="messaggio" placeholder="Escriba el texto aqui." maxlength="480" rows="5"><?php echo $messaggio; ?></textarea>
		              <div class="row">
		              <div class="col-md-6 col-xs-5">		               
		               <input type="checkbox" id="shortener" name="shortener" value="t" checked> <label> Acortar URLs.</label> 
		              </div>
		              <div class="col-md-6  col-xs-7">
		              <p style="text-align:right;color:blue"><strong>Caracteres/Limite [<span id="countBox">0</span>/<span id="countBoxMax">480</span>], <span id="countNumSMS">1</span> SMS</strong> </p>
		              </div>
		              </div>
                          </div>
                                                    
                          <div class="form-group hidden" id="my-progressbar">
                              <h3>Total de mensajes: <span id="my-smstotal"></span></h3>
                              <p>Enviado: <span id="my-smsnumber"></span></p>
                              <div class="progress">
                                 <div id="my-progress-bar" class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width:0%">
                                    <span id="my-progress-value">0%</span>
                                 </div>
                              </div>
                          </div>


                          <div class="form-group hidden" id="my-ok-process">
		                       <input type="button" id="button-ok-process" class="btn btn-default" value="Aceptar">
		                  </div>                          

                          <div class="form-group text-center" id="my-button-submit">
                                 <div class="form-row">
		                         <div class="col-xs-6">
		                             <button class="btn btn-info" type="button" data-toggle="modal" data-target="#ModalSMSPreview">Vista Previa</button>		                 
		                        </div>
                                 <div class="col-xs-6">
                                     <button id="btn-submit" type="submit" class="btn btn-success disabled" name="btn-submit">Enviar SMS</button>
									 <span id="spinner" class="spinner"></span>
		                         </div>
		                         </div>
		                  </div>

		      </form>
                  </div>
              </div>


</div>


<!-- Modal ModalPreview -->
<div id="ModalSMSPreview" class="modal" role="dialog" tabindex="-1">
    <div class="modal-dialog">
    
      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header text-center">
          <h5>Vista Previa (La vista puede variar)</h5>
          <button type="button" class="close" data-dismiss="modal" aria-lael="Close"><span aria-hidden="true">&times;</span></button>
        </div>
        <div class="modal-body">
            <div class="form-group scrollbarPhone">
            
                    <div class="contenedorPhone">
			 <div class="interiorPhone">
			                <div class="preview_time"><div id="preview_time"">9:28PM</div></div>
			                <div class="preview_text_bubble">
					<div class="preview_text">
                                           <div id="preview_smstext"></div>
					</div>
					</div>
		         </div>
		    </div>
		    
            </div>

        </div>
	<div class="modal-footer">
			<button class="btn btn-info" data-dismiss="modal"> Cerrar</button>
        </div>     
      </div>
      <!-- End Modal content-->
    </div>
<?php

   }else{
	   echo "No tienes permisos para acceder.";
   }
?>
	
</div>