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

if (!is_user()) {
    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['user_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_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['user_login'], $_SESSION['user_number'], '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()) {
adm_read($msg_id, '0');
log_info($_SERVER['REMOTE_ADDR'], $_SESSION['user_login'], $_SESSION['user_number'], 'Message Replied Successfully');
store_msg("Reply Sent Successfully", "success"); redirect(MESSAGES);
}else{
    store_msg("Reply 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-->

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


    <?php
    $notify = get_alerts($_SESSION['user_login'], 'all');
    foreach($notify as $ntfy){
    echo "<div class=\"alert alert-warning\" role=\"alert\">
    <strong>".date('l jS F Y', strtotime($ntfy['alrt_date']))."</strong><br>".$ntfy['alrt_cnt']."
    </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>Send messages to your Account Officer</small>
          </div>
          <div class="m-b" id="accordion">
            <?php
			$sql = "SELECT * FROM `".MSGS_TABLE_NAME."` WHERE msg_rcvr='{$_SESSION['user_login']}' OR msg_sender='{$_SESSION['user_login']}' 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['msg_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'] == $_SESSION['user_login']) { echo "You"; }else{ echo "Account Officer";} ?></span>
                </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'] == $_SESSION['user_login']) { 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'] == $_SESSION['user_login']) { echo "You"; } else{ echo "Account Officer";} ?></strong> on <strong><?php if ($rep['rply_date'] == "") { echo ""; }else{ echo date('jS F Y', strtotime($rep['rply_date']));} ?></strong></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="<?php echo $_SESSION['user_login']; ?>">
						<input type="hidden" name="sender_name" value="<?php echo user_names($_SESSION['user_login']); ?>">
						<input type="hidden" name="rply_rcvr" value="admin">
						<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 msg_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 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="<?php echo $_SESSION['user_login']; ?>">
        	<input type="hidden" name="msg_rcvr" value="admin">
        	<input type="hidden" name="sender_name" value="<?php user_names($_SESSION['user_login']); ?>">
        	<input type="hidden" name="msg_read" value="1">
        	<input type="hidden" name="adm_read" value="0">
            <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.lazyload.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-screenfull.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>
