<script>
  $().ready(function() {
    $("#signupForm").validate({
      rules: {
          name: "required",
          username: {
             required: true,
             minlength: 2
          },
          password: {
             required: false,
             minlength: 5
          },
          confirm_password: {
             required: false,
             minlength: 5,
             equalTo: "#password"
          },
          role: "required",
          status: "required"
       },
    });
  });
  function showMessage(status, client_id){
    if(status == 1){
        $title      = 'Great !!';
        $message    = 'USER UPDATED SUCCESSFUL';
        $type       = 'success';
    } else {
        $title      = 'Opps...';
        $message    = 'Error in adding user. Please try again';
        $type       = 'error';
    }

    swal({
        title: $title,
        text: $message,
        type: $type,
        showCancelButton: false,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "OK"
    },
    function(){
        if(status == 1){
            window.location.href = http_host + '?page=user_management/grid.php';
        } else {
            window.location.href = http_host + '?page=user_management/grid.php';    
        }
    });
  }
</script>
<?php 
  $status = '';
  $msg = '';
  if( !hasPermission($_SESSION['user_detail']['role_id'], 'user_add') ) {
      echo '<script>window.location.href="index.php?page=no_permission.php"</script>';
      die();
  }
  // ROLE 
  $role = "SELECT * FROM `roles`";
  $role_result = mysqli_query($conn,$role);

  if (isset($_REQUEST['eid']) && !empty($_REQUEST['eid']) && $_REQUEST['eid']!=0){
    $select_update="SELECT * FROM users WHERE id='".$_REQUEST['eid']."'";
    $select_update_res=mysqli_query($conn,$select_update);
    $update_row=mysqli_fetch_array($select_update_res,MYSQLI_BOTH);
    $comp               = trim($update_row['branch_id']);
    $compalain          = explode(',', $comp);
  }
  $bra_mst = "SELECT * FROM `branch_mst` WHERE `status` = '0'";
  $bra_res = mysqli_query($conn, $bra_mst);
  
  $bra = array();
  while ($bra_row = mysqli_fetch_array($bra_res)) {
    $bra[] = $bra_row;
  }
  if(isset($_POST['insert'])){
    $name                = $_REQUEST['name'];
    $email               = $_REQUEST['email'];
    $mobile              = $_REQUEST['mobile'];
    $username            = $_REQUEST['username'];
    $password            = md5($_REQUEST['password']);
    $confirm_password    = md5($_REQUEST['confirm_password']);
    $login_type         = $_REQUEST['login_type'];
    $branch_id          = mysqli_real_escape_string($conn, implode(",", $_POST['branch_id']));
    $status              = $_REQUEST['status'];
    $role_id             = $_REQUEST['role_id'];
    $created_id          = $_SESSION['user_detail']['id'];
    $created_datetime    = date('Y-m-d H:i:s'); 
    $updated_id          = $_SESSION['user_detail']['id'];
    $updated_datetime    = date('Y-m-d H:i:s');
    
    $update_mail = "UPDATE users SET name='$name',email='$email',mobile='$mobile',username='$username',password='$password',role_id='$role_id',branch_id='$branch_id',status='$status',login_type='$login_type',created_id='$created_id',created_datetime='$created_datetime',updated_id='$updated_id',updated_datetime='$updated_datetime' WHERE id='".$_REQUEST['eid']."'";

    $user_result = mysqli_query($conn,$update_mail) or die( mysqli_error($conn) );
      
    if($user_result){ 
      echo "<script type='text/javascript'> showMessage(1, 1); </script>";
    } else {
        echo "<script type='text/javascript'> showMessage(0, 0); </script>";
    }
  }

?>
<section class="content-header">
  <div class="row">
      <div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 bottom20">
        <h3 class="capital font15 padding5 bold">UPDATE USER DETAILS</h3>
      </div>
      <div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 text-right bottom20">
        <h3>
          <?php if( hasPermission($_SESSION['user_detail']['role_id'], 'user_list') ) { ?>
          <a href="index.php?page=user_management/grid.php" class="btn btn-danger capital bottom10 custome-btn">VIEW USER DETAILS</a>
          <?php } ?>
        </h3>
      </div>
  </div>
</section>
<hr class="bottom35"> 
<section class="hitz-top-header">
   <div class="row bottom40">
      <div class="col-xs-12">
         <div class="box box-success">
            <div class="box-body">
              <form class="" id="signupForm" method="post">
                <legend style="font-weight: bold;font-size: 12px !important;">BASIC INFORMATION</legend>
                <div class="row">
                  <div class="col-md-3">
                    <div class="form-group">
                      <label class="capital">Role</label><span style="color: red">*</span><br>
                      <select class="form-control" name="role_id" id="role_id">
                        <option></option>
                        <?php while ($role_rows = mysqli_fetch_array($role_result, MYSQLI_BOTH)) { ?>
                        <option  <?php if($role_rows['id'] == $update_row['role_id']) { echo "selected='selected'"; } ?>  value="<?php echo $role_rows['id'] ?>"><?php echo $role_rows['name'] ?></option>
                        <?php } ?>
                      </select>
                    </div>
                  </div>
                  <div class="col-md-3">
                    <div class="form-group">
                      <label class="capital">Name</label><span style="color: red">*</span>
                      <input type="text" size="35" id="name" name="name" class="form-control" placeholder="NAME" autocomplete="off" value="<?php echo $update_row['name'];?>" />
                    </div>
                  </div>
                  <div class="col-md-3">
                    <div class="form-group">
                      <label class="capital">Phone Number</label>
                      <input class="form-control" placeholder="PHONE NUMBER" name="mobile" type="text" id="quantity" maxlength="11" autocomplete="off" value="<?php echo $update_row['mobile'];?>">
                    </div>
                  </div>
                  <div class="col-md-3">
                    <div class="form-group">
                      <label class="capital">E-mail Id</label>
                      <input class="form-control" name="email" placeholder="E-MAIL ID" type="text" autocomplete="off" value="<?php echo $update_row['email'];?>">
                    </div>
                  </div>
                </div>
                <div class="row">
                  <div class="col-md-3">
                    <div class="form-group">
                      <label class="capital">BRANCH</label><span style="color: red">*</span>
                      <select id="branch_id" name="branch_id[]" class="form-control" required="" style="width: 100% !important;" multiple="">
                       <option></option>
                       <?php 
                      
                       foreach ($bra as $bra_id => $bras) {
                          $selected = '';
                          if(in_array($bras['id'], $compalain)){
                            $selected = "selected";
                          }
                          echo '<option value="'. $bras['id'] .'" '. $selected .'>' . $bras['branch'] . '</option>';
                        }
                       ?>
                      </select>
                    </div>
                  </div>
                </div>
                <legend style="font-weight: bold;font-size: 12px !important;">LOGIN CREDENTIALS</legend>
                <div class="row">
                  <div class="col-md-3">
                    <div class="form-group">
                      <label class="capital">Username</label><span style="color: red">*</span>
                      <input type="text" size="35" id="username" name="username" class="form-control" placeholder="USERNAME" autocomplete="off" onChange="CheckUname(this.value);" value="<?php echo $update_row['username'];?>" />
                    </div>
                  </div>
                  <div class="col-md-3">
                    <div class="form-group">
                      <label class="capital">Password</label><span style="color: red">*</span>
                      <input type="password" size="35" id="password" class="form-control" placeholder="PASSWORD" name="password" autocomplete="off">
                    </div>
                  </div>
                  <div class="col-md-3">
                    <div class="form-group">
                      <label class="capital">Re-Type Password</label><span style="color: red">*</span>
                      <input type="password" size="35" id="confirm_password" class="form-control" placeholder="RE-TYPE PASSWORD" name="confirm_password" autocomplete="off">
                    </div>
                  </div>
                  <div class="col-md-3">
                    <div class="form-group">
                      <label class="capital">Status</label><span style="color: red">*</span><br>
                      <label class="radio-inline fontradiobuttion">
                      <input type="radio" name="status" value="0" <?php if($update_row['status']=='0'){echo "checked";}?>> <span class="label-text">ACTIVE</span>
                      </label>
                      <label class="radio-inline fontradiobuttion">
                      <input type="radio" name="status" value="1" <?php if($update_row['status']=='1'){echo "checked";}?>> <span class="label-text">IN-ACTIVE</span>
                      </label>
                    </div>
                  </div>
                </div>
                <div class="row">
                  <div class="col-md-3">
                    <div class="form-group">
                      <label class="capital">LOGIN Type</label><span style="color: red">*</span><br>
                      <label class="radio-inline fontradiobuttion">
                      <input type="radio" name="login_type" value="S" <?php if($update_row['login_type']=='S'){echo "checked";}?>> <span class="label-text">SINGLE</span>
                      </label>
                      <label class="radio-inline fontradiobuttion">
                      <input type="radio" name="login_type" value="M" <?php if($update_row['login_type']=='M'){echo "checked";}?>> <span class="label-text">MULTIPLE</span>
                      </label>
                    </div>
                  </div>
                </div>
                <hr>
                <div class="row" align="center">
                  <button name="insert" class="btn btn-primary submit capital" type="submit"> UPDATE & SAVE</button>
                  <a href="index.php?page=user_management/grid.php" class="btn btn-danger capital"> Cancel</a>
                </div>
              </form>
              
            </div>
         </div>
      </div>
   </div>
</section>
<script type="text/javascript">
  $(document).ready(function() {
    $('input').iCheck({
        checkboxClass: 'icheckbox_flat',
        radioClass: 'iradio_flat'
    });
    $('#role_id').select2();
    $('#branch_id').select2();
    $("#checkAll").click(function() {
        $('input:checkbox').not(this).prop('checked', this.checked);
    });
  });
  function CheckUname() {
    var username      = $("#username").val();
    $.ajax({
      'type': 'POST',
      'url': 'user_management/check_uname.php',
      'data': {
        'username': username
      },
      dataType: 'JSON',
      success: function (result) {
        if(result.status == 1) {
          $('#username').val('');
          swal("Opps !!", "ALREADY CODE EXIST...!!!", "info")  
        }else{
          jQuery('.submit').attr('enable', true);
        }
      }
    });
  };
</script>