<?php include_once "header.php" ?>
<?php
//if (!isset($conn)) $conn = ew_Connect();

if(isset($_POST['btn-submit'])) {
    $errorMsg = '';

    $userid           = ew_RemoveXSS(ew_StripSlashes($_POST['inputUserID'         ]));
    $fullname         = ew_RemoveXSS(ew_StripSlashes($_POST['inputFullname'       ]));
    $nric             = ew_RemoveXSS(ew_StripSlashes($_POST['inputNRIC'           ]));
    $nric             = str_replace("-", "", $nric); // Remove instances of hyphen symbol
    $password         = ew_RemoveXSS(ew_StripSlashes($_POST['inputPassword'       ]));
    $passwordconfirm  = ew_RemoveXSS(ew_StripSlashes($_POST['inputPasswordConfirm']));
    $email            = ew_RemoveXSS(ew_StripSlashes($_POST['inputEmail'          ]));
    $userlevel        = ew_RemoveXSS(ew_StripSlashes($_POST['inputUserLevel'      ]));
    $activated        = ew_RemoveXSS(ew_StripSlashes($_POST['inputActivate'      ]));
    //$activated        = $_POST['inputActivate'];
    //die("test=".$userlevel);
    if (empty($userid)){
      $errorMsg = "Sila isikan User ID!";
    } else if (empty($fullname)){
      $errorMsg = "Sila isikan Nama Penuh";
    } else if (!empty($password) && $password !== $passwordconfirm){
        $errorMsg = "Kata laluan dan sah kata kaluan tidak sama!";
    } else if (empty($password) or empty($passwordconfirm)){
        if (empty($password)){
            $errorMsg = "Sila isikan kata laluan!";
        } else if (empty($passwordconfirm)){
            $errorMsg = "Sila isikan kata lalaun!";
        } else if ($password !== $passwordconfirm){
            $errorMsg = "Kata laluan tidah sama!";
        }
    } else if (empty($email)){
      $errorMsg = "Sila isikan alamat Emel!";
    } else {
        // User level is selected. Check if "Normal, user_level=0" selected, it must exist in IndukTauliah
        if ($userlevel=='0' || $userlevel=='-1' || $userlevel=='50'){
            $stmt = $DB_con->prepare("DECLARE @uname varchar(50)
                                          SET @uname=:userid
                                       SELECT top 1 ArmyNo
                                         FROM VIEW_INDUKTAULIAH_MASTER
                                        WHERE LEFT(ArmyNo,7)=(SELECT CASE WHEN LEN(@uname) > 7
                                                                          THEN @uname
                                                                          ELSE RIGHT ('0000000'+ CAST (@uname AS varchar), 7)
                                                                     END)", array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
            $stmt->execute(array(':userid'=>$userid));
            $row=$stmt->fetchAll(PDO::FETCH_ASSOC);
            if(count($row) == 0){
              if ($userlevel=='0'){
                 $errorMsg =  'No Tentera tidak wujud. Sila daftar di sistem AFIS terdahulu.';
              }
            } else {
              //die("heree");
              if ($userlevel=='50' || $userlevel=='-1'){
                //die("heree2222");
                  $errorMsg = 'Tidah boleh mendaftar No Tentera sebagai user Administrator/JHEKP. Sila pilih ID lain';
              }
            }
        }

        // Check whether the User ID already exist
        $stmt = $DB_con->prepare("SELECT *
                                     FROM WEBUSER
                                    WHERE USERID=:userid", array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
        $stmt->execute(array(':userid'=>$userid));
        $row=$stmt->fetchAll(PDO::FETCH_ASSOC);
        if(count($row) > 0){
             $errorMsg =  'User ID telah wujud di dalam sistem!';
        }

    }

    if (empty($errorMsg)) {
        $password = password_hash($password, PASSWORD_DEFAULT); //encrypt password
        $userpin  = $user->GeneratePIN(8);

        // INSERT INTO WEBUSER TABLE
        $stmt = $DB_con->prepare("INSERT INTO WEBUSER
                                  ( USERID
                                   ,USERPASSWORD
                                   ,USERLEVEL
                                   ,USEREMAIL
                                   ,USERACTIVATIONPIN
                                   ,ACTIVATED
                                   ,DATECREATED
                                  ) VALUES (
                                    :uid
                                   ,:upassword
                                   ,:uuserlevel
                                   ,:uemail
                                   ,:uactpin
                                   ,:uactivated
                                   ,getdate()
                                  )
                                 ");
        $stmt->bindparam(":uid",       $userid);
        $stmt->bindparam(":upassword", $password);
        $stmt->bindparam(":uuserlevel",$userlevel);
        $stmt->bindparam(":uemail",    $email);
        $stmt->bindparam(":uactpin",   $userpin);        
        $stmt->bindparam(":uactivated",$activated);
        $stmt->execute();


        // INSERT INTO WEBUSERPROFILE TABLE
        $stmt = $DB_con->prepare("INSERT INTO WEBUSERPROFILE
                                  (
                                     USERID
                                    ,FULLNAME
                                    ,NRIC
                                    ,EMAIL
                                    ,DATEMODIFIED
                                  ) VALUES (
                                     :uid
                                    ,:uname
                                    ,:unric
                                    ,:umail
                                    ,getdate()

                                  )
                                 ");
        $stmt->bindparam(":uid",   $userid);
        $stmt->bindparam(":uname", $fullname);
        $stmt->bindparam(":unric", $nric);
        $stmt->bindparam(":umail", $email);
        $stmt->execute();

        $user->log($user_id, 11, "User account $userid created");
        
        $errors="<div class=\"alert alert-success alert-dismissable\" id=\"success-alert\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\">x</button>Update Success</div>";

        header("location: useraccount.php?success=1");
    } else {
        $errors="<div class=\"alert alert-danger alert-dismissable\" id=\"fail-alert\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\">x</button>Update Error! $errorMsg</div>";
    }



}

?>

<!-- Full Width Column -->
<div class="content-wrapper">
    <div class="container">
        <!-- Content Header (Page header) -->
        <section class="content-header">
          <h1>
            Akaun Ahli
            <small>Pengurusan Akaun Penguna</small>
          </h1>
          <ol class="breadcrumb">
            <li><a href="#"><i class="fa fa-dashboard"></i class="active">Laman Utama</a></li>
            <li>Akaun Ahli</li>
            <li>Add</li>
          </ol>
        </section>

        <!-- Main content -->
        <section class="content">

          <div class="row">
            <div class="col-md-3">

              <!-- Profile Image -->
              <div class="box box-primary">
                  <div class="small-box bg-aqua">
                  <div class="inner">
                    <h3>&nbsp;</h3>

                    <p>Tambah Ahli Baru</p>
                  </div>
                  <div class="icon">
                    <i class="ion ion-person-add"></i>
                  </div>

                </div>
              </div>
              <!-- /.box -->

            </div>
            <!-- /.col -->
            <div class="col-md-9">
              <div class="nav-tabs-custom">
                <ul class="nav nav-tabs">
                  <li class="active"><a href="#add" data-toggle="tab">Tambah rekod</a></li>
                </ul>
                <div class="tab-content">
                  <div class=" active tab-pane" id="settings">
                    <form class="form-horizontal" id="profile-form" action="<?php echo htmlspecialchars(ew_CurrentPage()) ?>" data-toggle="validator" role="form" method="POST" remote="true">
                      <div id="error">
                            <!-- error will be showen here ! -->
                        <?php echo $errors; ?>
                      </div>
                      <div class="form-group">
                        <label for="inputUserID" class="col-sm-2 control-label">User ID</label>

                        <div class="col-sm-10">
                          <input type="text" name="inputUserID" class="form-control" id="inputUserID" placeholder="User ID" value="<?php echo $userid;?>" required>
                        </div>
                      </div>
                      <div class="form-group">
                        <label for="inputFullname" class="col-sm-2 control-label">Nama Penuh</label>

                        <div class="col-sm-10">
                          <input type="text" name="inputFullname" class="form-control" id="inputFullname" placeholder="Nama Penuh" value="<?php echo $fullname;?>" required>
                        </div>
                      </div>
                      <div class="form-group">
                        <label for="inputNRIC" class="col-sm-2 control-label">Kad Pengenalan</label>

                        <div class="col-sm-10">
                          <input type="text" name="inputNRIC" class="form-control" id="inputNRIC" placeholder="Kad Pengenalan" value="<?php echo $nric;?>" data-mask>
                        </div>
                      </div>
                      <div class="form-group">
                        <label for="inputPassword" class="col-sm-2 control-label">Kata Laluan</label>

                        <div class="col-sm-10">
                          <input type="password" name="inputPassword" data-minlength="6" class="form-control" id="inputPassword" placeholder="Kata Laluan" pattern="(?=^.{6,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$" data-error="Minimum 6 karekter with 1 lowercase, 1 uppercase 1 numeric and a symbol!" value="<?php echo $password;?>" required>
                          <span class="help-block with-errors"></span>
                        </div>
                      </div>
                      <div class="form-group">
                        <label for="inputPasswordConfirm" class="col-sm-2 control-label">Sah Kata Laluan</label>

                        <div class="col-sm-10">
                          <input type="password" name="inputPasswordConfirm"  data-minlength="6" data-match="#inputPassword" class="form-control" id="inputPasswordConfirm" placeholder="Sahkan Kata Laluan"  data-error="Kata laluan tidak sama!" value="<?php echo $passwordconfirm;?>" required>
                          <span class="help-block with-errors"></span>
                        </div>
                      </div>
                      <div class="form-group">
                        <label for="inputEmail" class="col-sm-2 control-label">Emel</label>

                        <div class="col-sm-10">
                          <input type="email" name="inputEmail"  class="form-control" id="inputEmail" placeholder="Emel" value="<?php echo $email;?>" required>
                        </div>
                      </div>
                      <div class="form-group">
                        <label for="inputUserLevel" class="col-sm-2 control-label">User Level</label>
                        <div class="col-sm-10">
                          <select name="inputUserLevel" class="form-control" id="inputUserLevel" required>
                            <option value="-1">Administrator</option>
                            <option value="50">JHEKP</option>
                            <option value="0" selected>Normal User</option>
                          </select>
                        </div>
                      </div>
                      <div class="form-group">
                        <label for="inputActivate" class="col-sm-2 control-label">Activated</label>
                        <div class="col-sm-10">
                          <select name="inputActivate" class="form-control" id="inputActivate" required>
                            <option value="1">Yes</option>
                            <option value="0" selected>No</option>
                          </select>
                        </div>
                      </div>
                      <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-8">
                          <button type="submit" name="btn-submit" class="btn btn-danger">Submit</button>
                          <a href="useraccount.php" name="btn-cancel" class="btn btn-info">Cancel</a>
                        </div>
                      </div>
                    </form>
                  </div>
                  <!-- /.tab-pane -->
                </div>
                <!-- /.tab-content -->
              </div>
              <!-- /.nav-tabs-custom -->
            </div>
            <!-- /.col -->
          </div>
          <!-- /.row -->

        </section>
        <!-- /.content -->








    </div>
    <!-- /.container -->
</div>
<!-- /.content-wrapper -->

<?php include_once "footer.php" ?>
<script>
    // close the success message
    $(document).ready (function(){
        $("#success-alert").fadeTo(2000, 1000).slideUp(1000, function(){
            $("#success-alert").alert('close');
        });
        $("#fail-alert").fadeTo(2000, 1000).slideUp(1000, function(){
            $("#fail-alert").alert('close');
        });

        // input mask
        $("#inputNRIC").inputmask("999999-99-9999", {removeMaskOnSubmit: true, clearIncomplete: true});  //static mask

    });

</script>