<?php
ob_start();
session_start();





/*
 * required files
 */
require_once ('./models/PHP-MySQLi-Database-Class/MysqliDb.php');
require_once("./models/config.php"); // connect with db and load site info
require_once("./models/functions.php"); // site functions





/*
 * page variables
 */
$page_name = 'SMS';
$page_name_single = 'SMS';






/*
 * if user is not logged in redirect to login
 */
if ((!isset($_SESSION['sess_user_id']) || (trim(isset($_SESSION['sess_user_id'])) == ''))) {
  header("location: index.php");
  exit();
} else {
  /*
   * set session variables
   */
  $user_id = $_SESSION['sess_user_id'];
  $username = $_SESSION['sess_username'];
  $user_email = $_SESSION['sess_user_email'];
}






/*
 * active menu links
 */
$menu_active = 'sms';
if ($page == 'view') {
  $menu_sub_active = 'view';
}
if ($page == 'my') {
  $menu_sub_active = 'my';
}
if (($page == 'edit') || ( $page == 'add')) {
  $menu_sub_active = 'addnedit';
}
?>
<!DOCTYPE html>
<html>
  <head lang="en">

    <title><?= $page_name ?> | <?php echo $site_name; ?> - <?php echo $site_slogan; ?></title>
    <meta name="description" content="<?php echo $site_name . '.' . $site_slogan ?>">

    <?php require_once './includes/head.php'; ?>
    <link rel="stylesheet" href="css/lib/summernote/summernote.css"/>


  </head>
  <body class="with-side-menu theme-side-litmus-blue">

    <?php require_once './includes/header.php'; ?>

    <?php require_once './includes/side-menu.php'; ?>

    <div class="page-content">
      <div class="container-fluid">

        <header class="section-header">
          <div class="tbl">
            <div class="tbl-row">
              <div class="tbl-cell">
                <a href="sms.php?page=view" class="btn btn-sm btn-primary-outline pull-right"><i class="fa fa-group" aria-hidden="true"></i><span class="hidden-xs">  Send to All</span></a>
                <a href="sms.php?page=add" class="btn btn-sm btn-primary-outline pull-right"><i class="fa fa-user" aria-hidden="true"></i><span class="hidden-xs">  Send SMS</span></a>
                <h3>
                  <?
                  if ($page == 'view') {
                    ?>
                    Send SMS to All
                    <?
                  }
                  ?>
                  <?
                  if ($page == 'add') {
                    ?>
                    Send SMS
                    <?
                  }
                  ?>

                </h3>
              </div>
            </div>
          </div>
        </header>

        <?
        if ($errors != '') {
          echo '<div class = "alert alert-block alert-danger fade in">';
          foreach ($errors as $error) {
            echo '<p>' . $error . '.</p>';
          }
          echo '</div>';
        }
        if ($success != '') {
          echo '<div class = "alert alert-block alert-success fade in">';
          //foreach ($successes as $success) {
          echo '<p><b>' . $edit_name . '</b>  ' . $success . '.</p>';
          //}
          echo '</div>';
        }
        ?>
        <?
        if ($page == 'add') {
          ?>
          <div>
            <form enctype="multipart/form-data" role="form" method="POST" action="<?= $_SERVER['PHP_SELF'] ?>" id="myform">


              <div class="row">

                <div class="col-sm-4 col-sm-offset-2">

                  <div class="box-typical box-typical-padding">

                    <div class="row">
                      <div class="col-sm-12">
                        <div class="row">

                          <div class="col-sm-12">
                            <div class="form-group">
                              <label for="edit_name">Name</label>
                              <div>
                                <input type="text" id="edit_name" name="edit_name" class="form-control validate[required,maxSize[255]]"/>
                              </div>
                              <div class="clearfix"></div>
                            </div>
                          </div>

                          <div class="col-sm-12">
                            <div class="form-group">
                              <label for="edit_phone">Mobile</label>
                              <div>
                                <input type="text" id="edit_phone" name="edit_phone" class="form-control validate[required,maxSize[255]]"/>
                              </div>
                              <small class="help-block text-muted" style="margin-top: 5px;">No white spaces or dashes. Add 92 instead of 0.<br/>For Example: 923214567890</small>
                              <div class="clearfix"></div>
                            </div>
                          </div>

                          <div class="col-sm-12">
                            <div class="form-group">
                              <label for="edit_body">Message</label>
                              <div>
                                <textarea type="text" id="edit_body" name="edit_body" class="form-control validate[required,maxSize[400]]" rows="4"></textarea>
                                <small class="help-block text-muted" style="margin-top: 5px;">400 characters maximum.</small>
                              </div>
                              <div class="clearfix"></div>
                            </div>
                          </div>
                          <div class="clearfix"></div>


                        </div>

                        <div class="form-group text-center" >

                          <button type="button" class="btn btn-success" name="edit_submit" id="edit_submit" onclick="sendmessage()"><i class="fa fa-check"></i>
                            Send  <i style="display: none" class="fa fa-spinner fa-puls fa-spin" id="refresh"></i>
                          </button>
                          <button type="button" class="btn btn-default" onclick="clearmessage()"><i class="fa fa-times"></i>
                            Clear
                          </button>
                        </div>
                      </div>
                    </div>


                  </div>
                </div>

                <div class="col-sm-4">

                  <div class = "alert alert-block alert-info fade in">
                    <b>Status:</b>
                    <div id="alert" style="max-height: 425px;overflow-y: scroll;padding: 5px;">SMS status will show here</div>
                  </div>

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

          </div>
          <?
        } elseif ($page == 'view') {
          ?>
          <div>


            <div>
              <form enctype="multipart/form-data" role="form" method="POST" action="<?= $_SERVER['PHP_SELF'] ?>" id="myform">


                <div class="row">

                  <div class="col-sm-4 col-sm-offset-2">

                    <div class="box-typical box-typical-padding">

                      <div class="row">
                        <div class="col-sm-12">
                          <div class="row">

                            <div class="col-sm-12">
                              <div class="form-group">
                                <label for="edit_body">Message</label>
                                <div>
                                  <textarea type="text" id="edit_body" name="edit_body" class="form-control validate[required,maxSize[400]]" rows="12"></textarea>
                                  <small class="help-block text-muted" style="margin-top: 5px;">400 characters maximum.</small>
                                </div>
                                <div class="clearfix"></div>
                              </div>
                            </div>
                            <div class="clearfix"></div>

                          </div>

                          <div class="form-group text-center" >

                            <button type="button" class="btn btn-success" name="edit_submit" id="edit_submit" onclick="sendmessageall()"><i class="fa fa-check"></i>
                              Send  <i style="display: none" class="fa fa-spinner fa-puls fa-spin" id="refresh"></i>
                            </button>
                            <button type="button" class="btn btn-default" onclick="clearmessage()"><i class="fa fa-times"></i>
                              Clear
                            </button>
                          </div>
                        </div>
                      </div>


                    </div>
                  </div>

                  <div class="col-sm-4">

                    <div class = "alert alert-block alert-info fade in">
                      <b>Status:</b>
                      <div id="alert" style="max-height: 425px;overflow-y: scroll;padding: 5px;">SMS status will show here</div>
                    </div>

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

            </div>

          </div>
          <?
        }
        ?>

      </div><!--.container-fluid-->
    </div><!--.page-content-->

    <?php require_once './includes/footer.php'; ?>
    <script src="js/lib/summernote/summernote.min.js"></script>
    <?
    if ($page == 'add') {
      ?>
      <script>
                              $(document).ready(function () {

                                var keycode = (event.keyCode ? event.keyCode : event.which);
                                if (keycode == '13') {
                                  sendmessage()
                                }
                              })

                              function clearmessage()
                              {
                                $('#refresh').hide()
                                $('#edit_name').val('')
                                $('#edit_phone').val('')
                                $('#edit_body').val('')
                                $('#alert').html('SMS status will show here')
                              }

                              function sendmessage() {

                                if ($("#myform").validationEngine('validate')) {

                                  event.preventDefault();
                                  $('#refresh').show()


                                  // loop start here

                                  var edit_phone = $('#edit_phone').val();

                                  /*
                                   * ufone api
                                   */

                                  //  var sms_host = 'bsms.ufone.com';
                                  var sms_id = '<?= $sms_id ?>';
                                  var sms_message = 'Dear ' + $('#edit_name').val() + ' ' + $('#edit_body').val();
                                  var sms_shortcode = '<?= $sms_shortcode ?>';
                                  var sms_mobilenum = edit_phone;
                                  var sms_password = '<?= $sms_password ?>';
                                  sms_url = 'http://bsms.ufone.com/bsms_app5/sendapi-0.3.jsp';
                                  $.ajax({
                                    type: "POST",
                                    dataType: "xml",
                                    url: sms_url,
                                    data: {id: sms_id, message: sms_message, shortcode: sms_shortcode, lang: 'English', mobilenum: sms_mobilenum, password: sms_password, groupname: '<?= $sms_groupname ?>'}
                                  }).done(function (result) {

                                    $(result).find('response_to_browser').each(function () {
                                      var Titles = $(this).find('response_text').text();
                                      var d = new Date();
                                      var hr = d.getHours();
                                      var min = d.getMinutes();
                                      var dateString = hr + ":" + min;
                                      $('#alert').prepend('<hr style="margin:7px 0"/><div><b>Message at ' + dateString + ':</b> <br>Mobile : ' + sms_mobilenum + '<br>Message: ' + sms_message + '<br>Response: ' + Titles + '</div>');
                                      $('#alert').show()
                                      $('#edit_name').val('')
                                      $('#edit_phone').val('')
                                      $('#edit_body').val('')

                                    });
                                  });


                                  $('#refresh').hide()

                                  // loop end here

                                }
                                //                            else {
                                //                              alert('Please fill out the fields.')
                                //                            }
                              }
      </script>
    <? } ?>
    <?
    if ($page == 'view') {
      ?>
      <script>
        $(document).ready(function () {

          var keycode = (event.keyCode ? event.keyCode : event.which);
          if (keycode == '13') {
            sendmessage()
          }
        })

        function clearmessage()
        {
          $('#refresh').hide()
          $('#edit_body').val('')
          $('#alert').html('SMS status will show here')
        }

        function sendmessageall() {

          if ($("#myform").validationEngine('validate')) {
  <?
  $db->orderBy("name", "desc");
  $db->where('is_delete', 0);
  $db->where('is_active', 1);
  $db->where('phone!=""');
  $edit_infos = $db->get('customers');
// print_r($db->trace);
  if ($db->count > 0) {
    $counter = 1;
    foreach ($edit_infos as $edit_info) {
      ?>
                sendmessage('<?= $edit_info['phone'] ?>', '<?= $edit_info['name'] ?>');
      <?
    }
  } else {
    ?>
              alert('No customers.');
    <?
  }
  ?>
          }
        }

        function sendmessage(edit_phone, edit_name) {

          event.preventDefault();
          $('#refresh').show()



          /*
           * ufone api
           */

          //  var sms_host = 'bsms.ufone.com';
          var sms_id = '<?= $sms_id ?>';
          var sms_message = $('#edit_body').val();//'Dear ' + edit_name + ' ' + $('#edit_body').val();
          var sms_shortcode = '<?= $sms_shortcode ?>';
          var sms_mobilenum = edit_phone;
          var sms_password = '<?= $sms_password ?>';
          sms_url = 'http://bsms.ufone.com/bsms_app5/sendapi-0.3.jsp';
          $.ajax({
            type: "POST",
            dataType: "xml",
            url: sms_url,
            data: {id: sms_id, message: sms_message, shortcode: sms_shortcode, lang: 'English', mobilenum: sms_mobilenum, password: sms_password, groupname: '<?= $sms_groupname ?>'}
          }).done(function (result) {

            $(result).find('response_to_browser').each(function () {
              var Titles = $(this).find('response_text').text();
              var d = new Date();
              var hr = d.getHours();
              var min = d.getMinutes();
              var dateString = hr + ":" + min;
              $('#alert').prepend('<hr style="margin:7px 0"/><div><b>Message at ' + dateString + ':</b> <br>Mobile : ' + sms_mobilenum + '<br>Message: ' + sms_message + '<br>Response: ' + Titles + '</div>');
              $('#alert').show()
              $('#edit_body').val('')

            });
          });


          $('#refresh').hide()

          //                            else {
          //                              alert('Please fill out the fields.')
          //                            }
        }
      </script>
    <? } ?>
  </body>
</html>