var student_info = [];

$('#send_verification').click(function(){
  var sec_id = $("input[type=radio][name=send_to_section]:checked").val();
  var e_id = $("input[type=hidden][name=enrollment_id]").val();
  var data = {sec_id: sec_id,eid: e_id};
  if(sec_id){
    $('#sendstatus').html('Sending ...');
    $('#sendstatus').removeClass('border-danger d-none');
    $('#sendstatus').addClass('border-info');
    get_student_info(data).done(function(){
      $('#sendstatus').html('Sending (Sending verification message)...');
      send_sms(e_id).done(function(){
        $('#sendstatus').html('Done');
      });
    });

  }else{
    $('#sendstatus').removeClass('border-info d-none');
    $('#sendstatus').addClass('border-danger');
    $('#sendstatus').html('No section selected');
  }

});

function get_student_info(data){
  dfrd1 = $.Deferred();

  var url = "/index.php/gsm/send/enrollment/verification";
  $.post(url,data,function(data){
    student_info = data;
    dfrd1.resolve();
  });

  return $.when(dfrd1).done(function(){
  }).promise();
}

function send_sms(enrollment_id){
  dfrd1 = $.Deferred();
  var contact_no = [];
  var stud_id = [];
  var stud_fn = [];
  var gender = [];
  //console.log(student_info);
  for(i in student_info){
    if(student_info[i]['contact_1']){
      contact_no.push(student_info[i]['contact_1']);
      stud_id.push(student_info[i]['stud_id']);
      stud_fn.push(student_info[i]['stud_fn']);
      gender.push(student_info[i]['stud_gender']);
    }else if(student_info[i]['contact_2'] && student_info[i]['contact_2'] != ""){
      contact_no.push(student_info[i]['contact_2']);
      stud_id.push(student_info[i]['stud_id']);
      stud_fn.push(student_info[i]['stud_fn']);
      gender.push(student_info[i]['stud_gender']);
    }
  }
  var send = {
    id: stud_id,
    fn: stud_fn,
    gender: gender,
    contact: contact_no,
    eID: enrollment_id
  }

  //console.log(send);

  var url = "/index.php/gsm/send_sms/enrollment"
  $.post(url,send,function(data){
    dfrd1.resolve();
    console.log(data);
  });

  return $.when(dfrd1).done(function(){

  }).promise();
}
