<?php
session_start();
require_once('../config/config.php');
require_once('../class/functions.php');
dbconnect();

if (!is_admin()) {
    redirect(LOGIN);
}

$page = "SMS";
$geo = ip2location($_SERVER['REMOTE_ADDR']);
$country = $geo->country;
$city = $geo->city;
visit_log($_SERVER['REMOTE_ADDR'], $country, $city, $_SERVER['HTTP_USER_AGENT'], getBrowser($_SERVER['HTTP_USER_AGENT']), getOS($_SERVER['HTTP_USER_AGENT']), $page, $_SESSION['admin_login']);


if (isset($_POST['addSms']) && $_POST['addSms'] == 'addSms')
{
if ($_POST['alrt_rcvr'] == ""){ store_msg("Select SMS receiver", "danger"); redirect(SMS);}
elseif ($_POST['alrt_cnt'] == ""){ store_msg("Your message cannot be empty", "danger"); redirect(SMS);}
else{
$sms_cnt = clean_data($_POST['alrt_cnt']);
$rcvr = clean_data($_POST['alrt_rcvr']);
$phone = clean_phone(user_phone($rcvr));
$sms_rcvr = $rcvr.'(+'.$phone.')';
$sms_sndr = 'admin';


//Send SMS
if (USE_SMS) {

$url="http://api.scrybasms.com/legacy/message/send";

$postfields = array(
'username' => SMS_USER,
'password' => SMS_WORD,
'recipient' => $phone,
'senderid' => SMS_SENDER,
'message' => $sms_cnt
);

if (!$curld = curl_init()) {
exit;
}

curl_setopt($curld, CURLOPT_POST, true);
curl_setopt($curld, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($curld, CURLOPT_URL,$url);
curl_setopt($curld, CURLOPT_RETURNTRANSFER, true);

$output = curl_exec($curld);
curl_close ($curld);

$ReponseDecoded = json_decode($output);

foreach ($ReponseDecoded as $Results)
{
    $Status = $Results->Status;
    $StatusMsg = $Results->StatusMsg;
    $MessageId =  $Results->MessageId;
    $Cost = $Results->Cost;
}

}

$stmt = $pdo->prepare('INSERT INTO '.SMS_TABLE_NAME.' (sms_cnt, sms_sender, sms_rcvr, sms_date, sms_status, status_msg, msg_id, sms_cost) VALUES (:cnt, :sndr, :rcvr, NOW(), :status, :msg, :msgid, :cost)');
$stmt->execute(array(':cnt' => $sms_cnt, ':sndr' => $sms_sndr, ':rcvr' => $sms_rcvr, ':status' => $Status, ':msg' => $StatusMsg, ':msgid' => $MessageId, ':cost' => $Cost));
if ($pdo->lastInsertId()){
log_info($_SERVER['REMOTE_ADDR'], $_SESSION['admin_login'], $sms_rcvr, 'SMS Sent Successfully');
store_msg("SMS Sent Successfully", "success"); redirect(SMS);
}else{
    store_msg("SMS sending Error", "danger"); redirect(SMS);
}
}
}


if (isset($_POST['delSms']) && $_POST['delSms'])
{
$smsid = clean_data($_POST['delSms']);
if (delete_sms($smsid)) {
    log_info($_SERVER['REMOTE_ADDR'], $_SESSION['admin_login'], $smsid, 'SMS Successfully Deleted');
    store_msg("SMS Successfully Deleted", "success"); redirect(SMS);
}else{
    store_msg("Delete SMS Error", "danger"); redirect(SMS);
}
}

require_once('head.php');  
?>

<body>
  <div class="app" id="app">

<!-- ############ LAYOUT START-->
  <!-- aside -->
  <?php require_once('aside.php'); ?>
  <!-- / aside -->



  <!-- content -->
  <div id="content" class="app-content box-shadow-z3" role="main">

    <?php require_once('header.php'); ?>

    <?php require_once('footer.php'); ?>

    <div ui-view class="app-body" id="view">
    <!-- ############ PAGE START-->

    <div class="item">
        <div class="item-bg">
          <img src="../users/user.png" class="blur opacity-3">
        </div>
        <div class="p-a-md">
          <div class="row m-t">
            <div class="col-sm-10">
              <a href class="pull-left m-r-md">
                <span class="avatar w-96">
                  <img src="../users/user.png">
                  <i class="on b-white"></i>
                </span>
              </a>
              <div class="clear m-b">
                <p class="text-md profile-status">Welcome</p>
                <h3 class="m-a-0 m-b-xs">Administrator</h3>
                <p class="text-muted">
                    <?php
                    $lastlogin = alast_login($_SESSION['admin_login']);
                    foreach($lastlogin as $last){
                        if ($last['last_ts'] == '0000-00-00 00:00:00') {
                            echo '';
                        }else{
                            $lastdate = date('l jS F Y', strtotime($last['last_ts']));
                            $lastip = $last['last_ip'];
                            echo'<span class="m-r">Last login: <strong>'.$lastdate.'</strong></span>';
                            echo' From: <small><strong><i class="fa fa-map-marker m-r-xs"></i>'.$lastip.'</strong> </small><br>';
                            echo' <a href="http://api.hostip.info/get_html.php?ip='.$lastip.'" target="_blank"><img src="http://api.hostip.info/flag.php?ip='.$lastip.'" alt="Country" width="39" height="24"></a> ';
                        }
                    } ?>
                </p>
              </div>
            </div>
          </div>
        </div>
    </div>

    <?php if (!empty($_SESSION['msg_text'])) {
    $msg = create_alert($_SESSION['msg_text'], $_SESSION['msg_type']);
    echo $msg;
    clear_msg(); }
    ?>


    <div class="padding">
      <div class="row">
        <div class="col-sm-12 col-md-12">
          <div class="box-header m-b">
              <h2 class="m-a-0 m-b-sm text-lg">SMS</h2>
              <button class="btn rounded btn-outline b-info text-info p-x-md pull-right" data-toggle="modal" data-target="#addMsg">New SMS</button>
              <small>SMS messages sent to account holders</small>
              <small>SMS CREDITS (REMAINING): <span class="label rounded primary">0</span></small>
          </div>
          <div class="m-b" id="accordion">
            <?php
			$sql = "SELECT * FROM `".SMS_TABLE_NAME."` ORDER BY sms_date DESC";
			$stmt = $pdo->query($sql);
            if ($stmt->rowCount() > 0) {
			while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
		    ?>
            <div class="panel box no-border m-b-xs">
              <div class="box-header p-y-sm">
                <span class="pull-right label text-sm warn"><?php echo $row['status_msg']; ?></span>
                <a data-toggle="collapse" data-parent="#accordion" data-target="#c_<?php echo $row['sms_id']; ?>">
                  <strong><?php echo substr($row['sms_cnt'], 0, 60); ?>...</strong>
                </a>
              </div>
              <div id="c_<?php echo $row['sms_id']; ?>" class="collapse">
                <div class="box-header">
                  <span class="pull-left label text-sm success">Sent to: <?php echo $row['sms_rcvr']; ?></span>
                  <span class="pull-right label text-sm info"><?php echo date('jS F Y', strtotime($row['sms_date'])); ?></span>
                </div>
                <div class="box-body">
                  <p class="text-md">
                  <?php echo $row['sms_cnt']; ?>
                  </p>

    			  	<div class="box-footer m-b">
    			  	<form id="Dlsms" method="post" action="" onsubmit="return confirm('Are you sure you want to delete this SMS?');" ui-jp="parsley">
                        <button type="submit" name="delSms" value="<?php echo $row['sms_id']; ?>" class="btn btn-sm rounded btn-outline b-danger text-danger pull-right">Delete</button>
                    </form>
    			  	</div>
                </div>
              </div>
            </div>
            <?php
            }
            }else{
                echo '<div class="text-muted">No SMS sent yet</div>';
            } ?>
          </div>
        </div>
      </div>
    </div>



    <!-- Add New SMS modal -->
    <div id="addMsg" class="modal" data-backdrop="true">
      <div class="modal-dialog">
      <form id="AddSms" method="post" action="" enctype="multipart/form-data" ui-jp="parsley">
        <div class="modal-content">
          <div class="modal-header">
          	<h5 class="modal-title">Add New SMS</h5>
          </div>
          <div class="modal-body p-lg">
           <div class="row row-sm">
              <div class="col-sm-12">
                <div class="md-form-group">
                  <select name="alrt_rcvr" class="md-input" data-parsley-error-message="Select Receiver" required>
                    <option value="">Select Receiver</option>
                    <?php
    				$users = get_users();
                    if (empty($users)) {
                    echo '<option value="">No User exist</option>';
                    }else{
    				foreach($users as $user)
    				{
    				echo '
                    <option value="'.$user['user_login'].'">'.$user['user_login'].' ('.$user['user_names'].')</option>
    				';
    				}
                    }
    			    ?>
                  </select>
                  <label>SMS Receiver</label>
                </div>
              </div>
            </div>
            <div class="row row-sm">
              <div class="col-sm-12">
                <div class="md-form-group float-label">
                  <textarea name="alrt_cnt" class="md-input" rows="3" data-parsley-error-message="SMS message is required" required></textarea>
                  <label>SMS Message</label>
                </div>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="submit" name="addSms" value="addSms" class="btn rounded btn-outline b-success text-success p-x-md">Send SMS</button>
            <button type="button" class="btn rounded btn-outline b-danger text-danger p-x-md" data-dismiss="modal">Cancel</button>
          </div>
        </div><!-- /.modal-content -->
      </form>
      </div>
    </div>
    <!-- / .modal -->




    <!-- ############ PAGE END-->
    </div>



    </div>
<!-- ############ LAYOUT END-->

  </div>
<!-- build:js scripts/app.html.js -->
<!-- jQuery -->
  <script src="../libs/jquery/jquery/dist/jquery.js"></script>

<!-- Bootstrap -->
  <script src="../libs/jquery/tether/dist/js/tether.min.js"></script>
  <script src="../libs/jquery/bootstrap/dist/js/bootstrap.js"></script>
<!-- core -->
  <script src="../libs/jquery/underscore/underscore-min.js"></script>
  <script src="../libs/jquery/jQuery-Storage-API/jquery.storageapi.min.js"></script>
  <script src="../libs/jquery/PACE/pace.min.js"></script>

  <script src="../scripts/config.lazyload2.js"></script>

  <script src="../scripts/palette.js"></script>
  <script src="../scripts/ui-load.js"></script>
  <script src="../scripts/ui-jp.js"></script>
  <script src="../scripts/ui-include.js"></script>
  <script src="../scripts/ui-device.js"></script>
  <script src="../scripts/ui-form.js"></script>
  <script src="../scripts/ui-nav.js"></script>
  <script src="../scripts/ui-screenfull2.js"></script>
  <script src="../scripts/ui-scroll-to.js"></script>
  <script src="../scripts/ui-toggle-class.js"></script>

  <script src="../scripts/app.js"></script>

  <!-- ajax -->
  <script src="../libs/jquery/jquery-pjax/jquery.pjax.js"></script>
  <script src="../scripts/ajax.js"></script>
<!-- endbuild -->
</body>
</html>
