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

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

$page = "Messages";
$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['addMsg']) && $_POST['addMsg'] == 'addMsg')
{
if ($_POST['msg_subject'] == ""){ store_msg("Enter a subject for your message", "danger"); redirect(MESSAGES);}
elseif ($_POST['msg_rcvr'] == ""){ store_msg("Select message receiver", "danger"); redirect(MESSAGES);}
elseif ($_POST['msg_cnt'] == ""){ store_msg("Your message cannot be empty", "danger"); redirect(MESSAGES);}
else{
$msg_subject = clean_data($_POST['msg_subject']);
$msg_cnt = clean_data($_POST['msg_cnt']);
$msg_sender = clean_data($_POST['msg_sender']);
$msg_rcvr = clean_data($_POST['msg_rcvr']);
$msg_read = clean_data($_POST['msg_read']);
$adm_read = clean_data($_POST['adm_read']);
$sender_name = clean_data($_POST['sender_name']);

$stmt = $pdo->prepare('INSERT INTO '.MSGS_TABLE_NAME.' (msg_subject, msg_cnt, msg_sender, msg_rcvr, msg_date, msg_read, adm_read, sender_name) VALUES (:subject, :cnt, :sender, :rcvr, NOW(), :msgread, :admread, :name)');
$stmt->execute(array(':subject' => $msg_subject, ':cnt' => $msg_cnt, ':sender' => $msg_sender, ':rcvr' => $msg_rcvr, ':msgread' => $msg_read, ':admread' => $adm_read, ':name' => $sender_name));
if ($pdo->lastInsertId()) {
log_info($_SERVER['REMOTE_ADDR'], $_SESSION['admin_login'], $sender_name, 'Message Sent Successfully');
store_msg("Message Sent Successfully", "success"); redirect(MESSAGES);
}else{
    store_msg("Message sending Error", "danger"); redirect(MESSAGES);
}
}
}


if (isset($_POST['addrep']) && $_POST['addrep'] == 'addrep')
{
if ($_POST['rply_cnt'] == ""){ store_msg("Your reply cannot be empty", "danger"); redirect(MESSAGES);}
else{
$rply_cnt = clean_data($_POST['rply_cnt']);
$rply_sender = clean_data($_POST['rply_sender']);
$rply_rcvr = clean_data($_POST['rply_rcvr']);
$sender_name = clean_data($_POST['sender_name']);
$msg_id = clean_data($_POST['msg_id']);

$stmt = $pdo->prepare('INSERT INTO '.RPLY_TABLE_NAME.' (rply_cnt, rply_sender, 	rply_rcvr, sender_name, rply_date, msg_id) VALUES (:cnt, :sender, :rcvr, :name, NOW(), :msg)');
$stmt->execute(array(':cnt' => $rply_cnt, ':sender' => $rply_sender, ':rcvr' => $rply_rcvr, ':name' => $sender_name, ':msg' => $msg_id));
if ($pdo->lastInsertId()) {
msg_read($msg_id, '0');
log_info($_SERVER['REMOTE_ADDR'], $_SESSION['admin_login'], $rply_sender, 'Message Replied Successfully');
store_msg("Reply Sent Successfully", "success"); redirect(MESSAGES);
}else{
    store_msg("Reply Error", "danger"); redirect(MESSAGES);
}
}
}

if (isset($_POST['delMsg']) && $_POST['delMsg'])
{
$msgid = clean_data($_POST['delMsg']);
if (delete_msg($msgid)) {
    delete_rply($msgid);
    log_info($_SERVER['REMOTE_ADDR'], $_SESSION['admin_login'], $msgid, 'Message Successfully Deleted');
    store_msg("Message Successfully Deleted", "success"); redirect(MESSAGES);
}else{
    store_msg("Delete Message Error", "danger"); redirect(MESSAGES);
}
}

if (isset($_POST['delRep']) && $_POST['delRep'])
{
$repid = clean_data($_POST['delRep']);
if (rply_delete($repid)) {
    log_info($_SERVER['REMOTE_ADDR'], $_SESSION['admin_login'], $repid, 'Reply Successfully Deleted');
    store_msg("Reply Successfully Deleted", "success"); redirect(MESSAGES);
}else{
    store_msg("Delete Message Error", "danger"); redirect(MESSAGES);
}
}

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">Messages</h2>
              <button class="btn rounded btn-outline b-info text-info p-x-md pull-right" data-toggle="modal" data-target="#addMsg">New Message</button>
              <small>Messages from Account Holders</small>
          </div>
          <div class="m-b" id="accordion">
            <?php
			$sql = "SELECT * FROM `".MSGS_TABLE_NAME."` WHERE msg_rcvr='admin' OR msg_sender='admin' ORDER BY msg_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" style="background-color:<?php if ($row['adm_read'] == "0") { echo '#d9edf7'; }else{ echo "";} ?>;">
              <div class="box-header p-y-sm">
                <span class="pull-right label text-sm info"><?php echo date('jS F Y', strtotime($row['msg_date'])); ?></span>
                <a data-toggle="collapse" data-parent="#accordion" data-target="#c_<?php echo $row['msg_id']; ?>">
                  <strong><?php echo $row['msg_subject']; ?></strong>
                </a>
              </div>
              <div id="c_<?php echo $row['msg_id']; ?>" class="collapse">
                <div class="box-header">
                  <span class="pull-left label text-sm success">From: <?php if ($row['msg_sender'] == 'admin') { echo "You"; }else{ echo $row['sender_name'];} ?></span>
                  <form id="Dlmes" method="post" action="" onsubmit="return confirm('Are you sure you want to delete this message?');" ui-jp="parsley">
                  <button type="submit" name="delMsg" value="<?php echo $row['msg_id']; ?>" class="btn btn-sm rounded btn-outline b-danger text-danger pull-right">Delete</button>
                  </form>
                </div>
                <div class="box-body">
                  <p class="text-md">
                  <?php echo $row['msg_cnt']; ?>
                  </p>

                  	<div class="streamline b-l m-l">
                        <div class="sl-item b-success">
                          <div class="sl-icon">
                            <i class="fa fa-share"></i>
                          </div>
                          <div class="sl-content">
                            <div><strong>Replies</strong></div>
                          </div>
                        </div>
                        <?php
                        $reply = get_replies($row['msg_id']);
                        if (empty($reply)) {
                        echo '<div class="text-muted">No replies added yet</div>';
                        }else{
                        foreach($reply as $rep)
                        {
                        ?>
                        <div class="sl-item <?php if ($rep['rply_sender'] == 'admin') { echo
					  "b-info"; } else{ echo "b-danger";} ?>">
                          <div class="sl-content">
                            <div class="sl-date text-muted">Replied by: <strong><?php if ($rep['rply_sender'] == 'admin') { echo "You"; } else{ echo $row['sender_name'];} ?></strong> on <strong><?php if ($rep['rply_date'] == "") { echo ""; }else{ echo date('jS F Y', strtotime($rep['rply_date']));} ?></strong>
                            <form id="Dlrep" method="post" action="" onsubmit="return confirm('Are you sure you want to delete this reply?');" ui-jp="parsley">
                                <button type="submit" name="delRep" value="<?php echo $rep['rply_id']; ?>" class="nav-link label danger pull-right">Delete</button>
                            </form>
                            </div>
                            <div><?php echo $rep['rply_cnt']; ?></div>
                          </div>
                        </div>
                        <?php
                        }}
                        ?>
                    </div>

    			  	<div class="box-footer">
			  	    <form id="addRep" method="post" action="" enctype="multipart/form-data" ui-jp="parsley">
                        <div class="row row-sm">
            			  <div class="col-sm-12">
            				<div class="md-form-group float-label">
            				  <textarea name="rply_cnt" class="md-input" rows="3" data-parsley-error-message="Your reply is required" required></textarea>
            				  <label>Reply</label>
            				</div>
            			  </div>
            			</div>
                        <input type="hidden" name="rply_sender" value="admin">
						<input type="hidden" name="sender_name" value="Account Officer">
						<input type="hidden" name="rply_rcvr" value="<?php echo $row['msg_rcvr']; ?>">
						<input type="hidden" name="msg_id" value="<?php echo $row['msg_id']; ?>">
    			  		<button type="submit" name="addrep" value="addrep" class="btn btn-sm rounded btn-outline b-info text-info">Reply</button>
                        </form>
    			  	</div>
                    <?php adm_read($row['msg_id'], '1'); ?>
                </div>
              </div>
            </div>
            <?php
            }
            }else{
                echo '<div class="text-muted">No messages added yet</div>';
            } ?>
          </div>
        </div>
      </div>
    </div>



    <!-- Add New Message modal -->
    <div id="addMsg" class="modal" data-backdrop="true">
      <div class="modal-dialog">
      <form id="AddMsg" method="post" action="" enctype="multipart/form-data" ui-jp="parsley">
        <div class="modal-content">
          <div class="modal-header">
          	<h5 class="modal-title">Add New Message</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="msg_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>Message Receiver</label>
                </div>
              </div>
            </div>
            <div class="row row-sm">
              <div class="col-sm-12">
                <div class="md-form-group float-label">
                  <input type="text" name="msg_subject" class="md-input" data-parsley-error-message="Message subject is required" required>
                  <label>Subject</label>
                </div>
              </div>
            </div>
            <div class="row row-sm">
              <div class="col-sm-12">
                <div class="md-form-group float-label">
                  <textarea name="msg_cnt" class="md-input" rows="3" data-parsley-error-message="Message detail is required" required></textarea>
                  <label>Message</label>
                </div>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <input type="hidden" name="msg_sender" value="admin">
        	<input type="hidden" name="sender_name" value="Account Officer">
        	<input type="hidden" name="msg_read" value="0">
        	<input type="hidden" name="adm_read" value="1">
            <button type="submit" name="addMsg" value="addMsg" class="btn rounded btn-outline b-success text-success p-x-md">Send Message</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>
