<?php
if (session_id() == "") session_start(); // Initialize Session data
ob_start(); // Turn on output buffering

include_once 'db.php';
include_once "ewcfg12.php";
include_once ((EW_USE_ADODB) ? "adodb5/adodb.inc.php" : "ewmysql12.php");
include_once "phpfn12.php";
include_once "class.user.php";

$Security = new cAdvancedSecurity();
$user     = new USER($DB_con);

$user_id = trim(ew_RemoveXSS(ew_StripSlashes($_SESSION['user_session'])));
//die("admin=".$_SESSION[EW_SESSION_USER_LEVEL]);
//if ($_SESSION[EW_SESSION_SYS_ADMIN] == 0) {
//die("ulevel=".$_SESSION[EW_SESSION_USER_LEVEL]);

if(!$user->is_loggedin())
{
  $user->redirect('login.php');
}

$localpath    = getenv("SCRIPT_NAME");
$absolutepath = realpath($localPath);
// fix the Windows slashes
$absolutepath = str_replace("\\","/",$absolutepath);
$docroot      = substr($absolutepath, 0, strpos($absolutepath, $localpath));
$docroot      = $docroot."/ltatonline";
// an example of use
//include($docroot."/includes/config.php");

if ($_SESSION[EW_SESSION_SYS_ADMIN] == 1 || $_SESSION[EW_SESSION_USER_LEVEL]==-1 || $_SESSION[EW_SESSION_USER_LEVEL]==-2){
  $idx = "dashboard.php";
} else {
  $idx = "index.php";
}

if ($_SESSION[EW_SESSION_USER_LEVEL]!=-999 && $_SESSION[EW_SESSION_USER_LEVEL]!=-2 && $_SESSION[EW_SESSION_USER_LEVEL]!=50 && $_SESSION[EW_SESSION_USER_LEVEL]!=-1){
    //if (!isset($_SESSION['CURRENTMILITARYRANK']) && empty($_SESSION['CURRENTMILITARYRANK'])){
    if (!isset($_SESSION['CURRENTMILITARYRANK']) && empty($_SESSION['CURRENTMILITARYRANK'])){
      if (isset($_SESSION['MILITARYRANK']) && !empty($_SESSION['MILITARYRANK'])){
        foreach($_SESSION['MILITARYRANK'] as $key=>$value){
            if ($key==0){
                $_SESSION['CURRENTMILITARYRANK'] = $value;
                Break;
            }
        }
      //} else {
      //  $_SESSION['CURRENTMILITARYRANK'] = '0';
      }      
    }

    if ($_SESSION['CURRENTMILITARYRANK']=='1'){
      $milrankname = 'Sukarela';
    } else if ($_SESSION['CURRENTMILITARYRANK']=='2'){
      $milrankname = 'Pegawai LLP';
    } else if ($_SESSION['CURRENTMILITARYRANK']=='5'){
      $milrankname = 'Pegawai Wajib';
    } else {
      $milrankname = 'Others';
    }

    $user_rank                  = trim(ew_RemoveXSS(ew_StripSlashes($_SESSION['CURRENTMILITARYRANK'])));
    $_SESSION['ARMYNOWITHRANK'] = str_pad($user_id.$user_rank, 8, '0', STR_PAD_LEFT);

    //$stmt    = $DB_con->prepare("SELECT * FROM TBMILITARIES WHERE MILITARYID=:user_id ORDER BY NPID");
    //$stmt->execute(array(":user_id"=>$user_id));
    //$userRow = $stmt->fetch(PDO::FETCH_ASSOC);

}
//printf($_SESSION['CURRENTMILITARYRANK']);

$a_mailfrom    = array();
$a_mailsubject = array();
$a_datecreated = array();

// getting total number records without any search
if ($_SESSION[EW_SESSION_USER_LEVEL]==-999 || $_SESSION[EW_SESSION_USER_LEVEL]==-1 || $_SESSION[EW_SESSION_USER_LEVEL]==50){
    $sql = "
            SELECT ID, MAILFROM, MAILTO, MAILSUBJECT, DATECREATED
              FROM MAILBOX
             WHERE (MAILFROM IN (SELECT USERID 
                               FROM WEBUSER
                              WHERE USERLEVEL IN (-999, -1, 50)         
                            ) OR
                      MAILTO IN (SELECT USERID 
                                   FROM WEBUSER
                                  WHERE USERLEVEL IN (-999, -1, 50)         
                            )
                   )
               AND PARENTID IS NULL
               AND MAILREAD=0
           "; 
} else {
    $sql = "
            SELECT ID, MAILFROM, MAILTO, MAILSUBJECT, DATECREATED
              FROM MAILBOX
             WHERE (MAILFROM='$user_id' OR MAILTO='$user_id')
               AND PARENTID IS NULL
               AND MAILREAD=0
           ";
}
$stmt = $DB_con->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute();
//$totalData = $stmt->rowCount();
$totalData = 0;
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $rowid  = $row["ID"];
    $mailto = $row["MAILTO"];
    $sql = "
            SELECT ID
              FROM MAILBOX
             WHERE PARENTID=$rowid
           ";
    $stmt2 = $DB_con->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
    $stmt2->execute();
    if ($stmt2->rowCount()==0){
        if ($mailto==$user_id){
            $totalData       = $totalData + 1;
            $a_mailfrom[]    = $row["MAILFROM"   ];
            $a_mailsubject[] = $row["MAILSUBJECT"];
            $a_datecreated[] = $row["DATECREATED"];
        }
    } else {
        if ($_SESSION[EW_SESSION_USER_LEVEL]==-999 || $_SESSION[EW_SESSION_USER_LEVEL]==-1 || $_SESSION[EW_SESSION_USER_LEVEL]==50){
            $sql = "
                    SELECT ID
                      FROM MAILBOX
                     WHERE PARENTID=$rowid
                       AND MAILTO IN (SELECT USERID 
                                        FROM WEBUSER
                                       WHERE USERLEVEL IN (-999, -1, 50)         
                                     )
                       AND MAILREAD=0
                   ";          
        } else {
            $sql = "
                    SELECT ID
                      FROM MAILBOX
                     WHERE PARENTID=$rowid
                       AND MAILTO  ='$user_id'
                       AND MAILREAD=0
                   ";
        }
        $stmt3 = $DB_con->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
        $stmt3->execute();
        if ($stmt3->rowCount()==0){

        } else {
            $totalData = $totalData + 1;
            $a_mailfrom[]    = $row["MAILFROM"   ];
            $a_mailsubject[] = $row["MAILSUBJECT"];
            $a_datecreated[] = $row["DATECREATED"];
        }
    }
}

?>


<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>i-Wira - Sistem Semakan Caruman Atas Talian</title>
  <!-- Tell the browser to be responsive to screen width -->
  <meta name="description" content="Portal i-Wira:Sistem Semakan Caruman Atas Talian,iwira.ltat.org.my">
  <meta name="keywords" content="iwira,IWIRA,ltat,LTAT,i-Wira,Semak Penyata LTAT,Penyata Atas Talian,Semak Waris Semasa,Semak Saham Amanah Affin Hwang, Semak Sejarah Pengeluaran,Aduan,Cadangan dan Pertanyaan,Daftar iwira, Daftar i-Wira">
  <meta name="author" content="Unit Teknologi Maklumat,Lembaga Tabung Angkatan Tentera">
  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
  <!-- Bootstrap 3.3.6 -->
  <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
  <!-- Font Awesome -->
  <!--<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css">-->
  <!--<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">-->
  <script src="https://use.fontawesome.com/238cc4642d.js"></script>
  <!-- iCheck for checkboxes and radio inputs -->
  <link rel="stylesheet" href="plugins/iCheck/all.css">
  <!-- Ionicons -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">
  <!-- DataTables -->
  <!--
  <link rel="stylesheet" type="text/css" href="plugins/datatables/datatables.min.css"/>
  <link rel="stylesheet" href="plugins/datatables/DataTables-1.10.13/css/dataTables.bootstrap.css">
  <link rel="stylesheet" href="plugins/datatables/Responsive-2.1.1/css/dataTables.responsive.css">
  -->
  <link rel="stylesheet" href="plugins/datatables//dataTables.bootstrap.css">
  <link rel="stylesheet" href="plugins/datatables/extensions/Responsive/css/dataTables.responsive.css">
  <!-- Theme style -->
  <link rel="stylesheet" href="dist/css/AdminLTE.min.css">
  <!-- AdminLTE Skins. Choose a skin from the css/skins
       folder instead of downloading all of them to reduce the load. -->
  <link rel="stylesheet" href="dist/css/skins/skin-blue.min.css">


  <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
  <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
  <!--[if lt IE 9]>
  <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
  <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
  <![endif]-->
  <style>
    .navbar-brand {
      padding: 0px;
    }
    .navbar-brand>img {
      height: 100%;
      padding: 15px;
      width: auto;
    }

    /* EXAMPLE 4 - Small Narrow Logo*/
    .example4 .navbar-brand>img {
      padding: 3px 0px;
    }

    .ellipsis {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }
  </style>

  <script type="text/javascript">
      function run(sel) {
          var i = sel.selectedIndex;
          if (i != -1) {
              //document.getElementById("car").value = sel.options[i].text;
              $.ajax({
                  type: "POST",
                  url: "ajax_updaterank.php",
                  data: { MilitaryRank: sel.options[i].value }
                  // success:function(result)//we got the response
                  // {
                      // alert(result);
                  // },
                  //error:function(exception)
                  // error: function (request, status, error)
                  // {
                      // alert(request.responseText);
                  // }
                 //error:function(exception)
                  //{
                  //    alert('Exeption:'+exception);
                  //}
              }).done(function() {
                window.location.href = window.location.href;
              });
          }
          <?php
          /*
            if (basename(htmlspecialchars($_SERVER["PHP_SELF"]))=='penyata.php'    ||
                basename(htmlspecialchars($_SERVER["PHP_SELF"]))=='unittrust.php'  ||
                basename(htmlspecialchars($_SERVER["PHP_SELF"]))=='waris.php'      ||
                basename(htmlspecialchars($_SERVER["PHP_SELF"]))=='withdrawal.php'
               )
            {
              echo "document.myForm.submit();";
            }
            */
          ?>
      }
  </script>

</head>
<!-- ADD THE CLASS layout-top-nav TO REMOVE THE SIDEBAR. -->
<body class="hold-transition skin-blue layout-top-nav">
<div class="wrapper">

  <header class="main-header">
    <nav class="navbar navbar-static-top">
      <div class="container example4">
        <div class="navbar-header">
          <a href="<?php echo $idx;?>" class="navbar-brand"><img src="dist/img/LTATLogo2.png" class="d-inline-block align-top" width="35" alt=""></a>
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse">
            <i class="fa fa-bars"></i>
          </button>
        </div>
        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse pull-left" id="navbar-collapse">
          <ul class="nav navbar-nav">
            <li class="active"><a href="<?php echo $idx;?>">Utama <span class="sr-only">(current)</span></a></li>
            <?php if ($_SESSION[EW_SESSION_SYS_ADMIN] == 0 && ($_SESSION[EW_SESSION_USER_LEVEL]!=-1) && $_SESSION[EW_SESSION_USER_LEVEL]!=50) { ?>
            <li><a href="penyata.php">Penyata</a></li>
            <!--<li><a href="waris.php">Waris</a></li>-->
            <li><a href="unittrust.php">Unit Trust</a></li>
            <li><a href="withdrawal.php">Pengeluaran</a></li>
            <li><a href="mailbox.php">Maklum Balas</a></li>
            <li><a href="activitylogs-users.php">Semakan Aktiviti</a></li>
            <?php } ?>
            <?php if ($_SESSION[EW_SESSION_SYS_ADMIN] == 1 || $_SESSION[EW_SESSION_USER_LEVEL]==-1 || $_SESSION[EW_SESSION_USER_LEVEL]==-2) { ?>
            <!--<li class="dropdown">
              <a href="#" class="dropdown-toggle" data-toggle="dropdown">Administration <span class="caret"></span></a>
              <ul class="dropdown-menu" role="menu">-->
                <li><a href="mailbox.php">Maklum Balas</a></li>
                <li><a href="useraccount.php">Akaun Ahli</a></li>
                <li class="divider"></li>
                <li><a href="activitylogs.php">Log Aktiviti</a></li>
                <li class="divider"></li>
                <li><a href="changelogs.php">Log Perubahan</a></li>
              <!--</ul>
            </li>-->
            <?php } ?>
            <?php if ($_SESSION[EW_SESSION_SYS_ADMIN] == 0 && $_SESSION[EW_SESSION_USER_LEVEL]==50) { ?>
            <!--<li class="dropdown">
              <a href="#" class="dropdown-toggle" data-toggle="dropdown">Administration <span class="caret"></span></a>
              <ul class="dropdown-menu" role="menu">-->
                <li><a href="mailbox.php">Maklum Balas</a></li>
              <!--</ul>
            </li>-->
            <?php } ?>
          </ul>
          <?php if ($_SESSION[EW_SESSION_USER_LEVEL]!=-999 && $_SESSION[EW_SESSION_USER_LEVEL]!=-2 && $_SESSION[EW_SESSION_USER_LEVEL]!=50 && $_SESSION[EW_SESSION_USER_LEVEL]!=-1){ ?>
          <form name="myForm" method="POST" class="navbar-form navbar-left" role="search">
            <div class="form-group">
              <!--<input type="text" class="form-control" id="navbar-search-input" placeholder="Search">-->
              <!-- select -->
              <!--<label>Select</label>-->
              <!--<select class="form-control" id="navbar-search-input">
                <option>option 1</option>
                <option>option 2</option>
                <option>option 3</option>
                <option>option 4</option>
                <option>option 5</option>
              </select>-->
              <select class="form-control" id="navbar-search-input" name="MilitaryRank" onchange="run(this)">
              <?php
              // loop through the session array with foreach
              if (isset($_SESSION['MILITARYRANK']) && !empty($_SESSION['MILITARYRANK'])){
                  foreach($_SESSION['MILITARYRANK'] as $key=>$value)
                  {
                      if ($value=='1'){
                        $valuedisplay = 'Sukarela';
                      } else if ($value=='2'){
                        $valuedisplay = 'Pegawai LLP';
                      } else if ($value=='5'){
                        $valuedisplay = 'Pegawai Wajib';
                      } else {
                        $valuedisplay = 'Others';
                      }

                  ?>
                    <option value="<?php echo $value; ?>" <?php if ($_SESSION['CURRENTMILITARYRANK'] == $value) echo "selected"?>><?php echo $valuedisplay ?></option>
                  <?php
                  }
              }
                  ?>
              </select>
            </div>
          </form>
          <?php } ?>
        </div>
        <!-- /.navbar-collapse -->
        <!-- Navbar Right Menu -->
        <div class="navbar-custom-menu">
          <ul class="nav navbar-nav">
            <!-- Messages: style can be found in dropdown.less-->
            <li class="dropdown messages-menu">
              <!-- Menu toggle button -->
              <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                <i class="fa fa-envelope-o"></i>
                <span class="label label-success"><?php echo $totalData;?></span>
              </a>
              <ul class="dropdown-menu">
                <li class="header">Anda menpunyai <?php echo $totalData;?> mesej baru</li>
                <li>
                  <!-- inner menu: contains the messages -->
                  <ul class="menu">

                    <?php
                    $cnt = 0;
                    foreach ($a_mailfrom as $key1=>$mfrom){
                        foreach ($a_mailsubject as $key2=>$msubject){
                            foreach ($a_datecreated as $key3=>$mdatecreated){
                                if ($key1==$cnt){
                                  if ($key2==$cnt){
                                      if ($key3==$cnt){
                                          if ($cnt==4) break 2; //only shows 4 records max

                    ?>

                    <li><!-- start message -->
                      <a href="#">
                        <div class="pull-left">
                          <!-- User Image -->
                          <img src="dist/img/email-icon-23.png" class="img-circle" alt="User Image">
                        </div>
                        <!-- Message title and timestamp -->
                        <h4>
                          <?php echo $mfrom;?>
                          <small><i class="fa fa-clock-o"></i> <time class="timeago" datetime="<?php echo $mdatecreated;?>"><?php echo $mdatecreated;?></time></small>
                        </h4>
                        <!-- The message -->
                        <p class="ellipsis"><?php echo $msubject;?>
                        </p>
                      </a>
                    </li>
                    <!-- end message -->

                    <?php
                                         $cnt = $cnt + 1;
                                      }
                                  }
                                }
                            }
                        }
                    }
                    ?>


                  </ul>
                  <!-- /.menu -->
                </li>
                <li class="footer"><a href="mailbox.php">Lihat semua mesej</a></li>
              </ul>
            </li>
            <!-- /.messages-menu -->


            <!--
            <li class="dropdown notifications-menu">
              <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                <i class="fa fa-bell-o"></i>
                <span class="label label-warning">10</span>
              </a>
              <ul class="dropdown-menu">
                <li class="header">You have 10 notifications</li>
                <li>
                  <ul class="menu">
                    <li>
                      <a href="#">
                        <i class="fa fa-users text-aqua"></i> 5 new members joined today
                      </a>
                    </li>
                  </ul>
                </li>
                <li class="footer"><a href="#">View all</a></li>
              </ul>
            </li>
            -->

            <!-- User Account Menu -->
            <li class="dropdown user user-menu">
              <!-- Menu Toggle Button -->
              <a href="#" class="dropdown-toggle" data-toggle="dropdown">
                <!-- The user image in the navbar-->
                <img src="dist/img/soldier.png" class="user-image" alt="User Image">
                <!-- hidden-xs hides the username on small devices so only the image appears. -->
                <span class="hidden-xs"><?php echo $user->ellipsis($_SESSION['user_name'], 25); ?></span>
              </a>
              <ul class="dropdown-menu">
                <!-- The user image in the menu -->
                <li class="user-header">
                  <img src="dist/img/soldier.png" class="img-circle" alt="User Image">

                  <p>
                    <?php echo $_SESSION['user_name']; ?>
                    <!--<small>Member since Nov. 2012</small>-->
                    <small>Login Terakhir: <?php echo $_SESSION['last_login']; ?></small>
                  </p>
                </li>
                <!-- Menu Body -->
                <!--
                <li class="user-body">
                  <div class="row">
                    <div class="col-xs-4 text-center">
                      <a href="#">Followers</a>
                    </div>
                    <div class="col-xs-4 text-center">
                      <a href="#">Sales</a>
                    </div>
                    <div class="col-xs-4 text-center">
                      <a href="#">Friends</a>
                    </div>
                  </div>
                </li>
                  -->
                  <!-- /.row -->

                <!-- Menu Footer-->
                <li class="user-footer">
                  <div class="pull-left">
                    <a href="profile.php" class="btn btn-default btn-flat">Profil</a>
                  </div>
                  <div class="pull-right">
                    <a href="logout.php?logout=true" class="btn btn-default btn-flat">Log Keluar</a>
                  </div>
                </li>
              </ul>
            </li>
            <!-- Control Sidebar Toggle Button -->
            <li>
              <a href="#" data-toggle="control-sidebar"><i class="fa fa-gears"></i></a>
            </li>            
          </ul>
        </div>
        <!-- /.navbar-custom-menu -->
      </div>
      <!-- /.container-fluid -->
    </nav>
  </header>