<style>
    .padding-5{
        padding: 5px !important;
    }
</style>
<div class="row grid-margin">
    <div class="col-md-12">
        <div class="card">
            <div class="card-body">
                <h4 class="card-title">Users</h4>
                <p class="card-description">List of Users</p>
                <button class="btn btn-success" onclick="add_user()"><i class="icon-plus"></i> Add User</button>
                <br />
                <br />
                <table id="table_id" class="table table-striped table-bordered table-hover" cellspacing="0" width="100%">
                    <thead>
                        <tr>
                            <th>No</th>
                            <th>UUID</th>
                            <th>Name</th>
                            <th>Email</th>
                            <th>Group</th>
                            <th>level</th>
                            <th style="width:125px;">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                            $level = array("", "Admin", "Super User", "User");
                            foreach ($users as $user) {?>
				            <tr>
				                <td><?php echo $user["id"] ?></td>
				                <td><?php echo $user['uuid'] ?></td>
								<td><?=$user['user_name']?></td>
								<td><?=$user['user_email']?></td>
                                <td><?php if(isset($groups[$user['group_id']])) echo $groups[$user['group_id']];?></td>
                                <td><?php if(isset($level[$user['level']])) echo $level[$user['level']];?></td>
								<td>
									<button class="btn btn-warning padding-5" onclick="edit_user(<?php echo $user["id"]; ?>)"><i class="icon-pencil"></i></button>
									<button class="btn btn-danger padding-5" onclick="delete_user(<?php echo $user["id"] ?>)"><i class="icon-trash"></i></button>
								</td>
				            </tr>
				        <?php }?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="modal_form" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
      <h3 class="modal-title">User Form</h3>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      </div>
      <div class="modal-body form">
        <form id="form" class="form-horizontal" enctype="multipart/form-data" method="post">
          <input type="hidden" value="" name="id"/>
          <div class="form-body">
            <div class="form-group">
              <label class="control-label col-3">UUID</label>
              <div class="col-9">
                <select name="uuid" class="form-control" id="select_uuid">
                    <option></option>
                    <?php 
                        foreach($uuids as $uuid){
                            echo "<option value='{$uuid["uuid"]}'>{$uuid["uuid"]}</option>";
                        }
                    ?>
                </select>
              </div>
            </div>
            <div class="form-group">
              <label class="control-label col-md-3">User Name</label>
              <div class="col-md-9">
                <input name="user_name" placeholder="Username" class="form-control" type="text">
              </div>
            </div>
            <div class="form-group">
              <label class="control-label col-md-3">Email</label>
              <div class="col-md-9">
                <input name="user_email" placeholder="Email address" class="form-control" type="text">
              </div>
            </div>
            <div class="form-group">
              <label class="control-label col-md-3">Password</label>
              <div class="col-md-9">
                <input name="password" placeholder="Password" class="form-control" type="password">
              </div>
            </div>
            <div class="form-group">
              <label class="control-label col-md-3">Group</label>
              <div class="col-md-9">
                <select name="group_id" class="form-control">
                    <?php 
                        foreach($group_options as $key=>$values)
                        {
                            echo "<optgroup label='${key}'>";
                            foreach($values as $value){
                                echo "<option value='{$value["id"]}'>{$value["group_name"]}</option>";
                            }
                            echo "<optgroup>";
                        }
                    ?>
                </select>
              </div>
            </div>
            <div class="form-group">
              <label class="control-label col-md-3">level</label>
              <div class="col-md-9">
              <select name="level" class="form-control">
                    <?php 
                        foreach($level as $key=>$value)
                        {
                            echo "<option value='{$key}'>{$value}</option>";
                        }
                    ?>
                </select>
              </div>
            </div>
          </div>
        </form>
          </div>
          <div class="modal-footer">
            <button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
            <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
          </div>
        </div><!-- /.modal-content -->
      </div><!-- /.modal-dialog -->
    </div>
<script>
$(function() {
    $('#table_id').DataTable();
});
 
var save_method;
var table;
 function add_user()
 {
   save_method = 'add';
   $('#form')[0].reset(); // reset form on modals
   $('#modal_form').modal('show'); // show bootstrap modal
 //$('.modal-title').text('Add Person'); // Set Title to Bootstrap modal title
 }

 function edit_user(id)
 {
   save_method = 'update';
   $('#form')[0].reset(); // reset form on modals

   var options = {
     url:  "<?php echo site_url('users/get_user/')?>" + id,
     type: 'POST',
     complete: function(response)
     {
       var data = JSON.parse(response.responseText);
         $('[name="id"]').val(data.id);
         $('[name="user_name"]').val(data.user_name);
         $('[name="user_email"]').val(data.user_email);

         $('[name="group_id"]').val(data.group_id);
         $('[name="level"]').val(data.level);
         
         var selector = "#select_uuid option[value='" + data.uuid + "']";
         if($(selector).length == 0) {
             $('#select_uuid').append($('<option>',{
                 value: data.uuid,
                 text: data.uuid
             }));
         }
         $('[name="uuid"]').val(data.uuid);
         
         $('#modal_form').modal('show'); 
         $('.modal-title').text('Edit User'); 
       }
     };
    $.ajax(options);

 }



 function save()
 {
   var url;
   if(save_method == 'add')
   {
        url = "<?php echo site_url('users/add_user')?>";
   }
   else
   {
        url = "<?php echo site_url('users/update_user')?>";
   }

   var options = {
     url: url,
     type: 'post',
     complete: function(response)
     {
       $('#modal_form').modal('hide');
       location.reload();
       if($.isEmptyObject(response.responseJSON.error)){
           alert('User Saved Successfully');
       }else{
           alert('Error in process');
         }
       }
     };
     $("#form").ajaxSubmit(options);
 }

 function delete_user(id)
 {
   if(confirm('Are you sure delete this data?'))
   {
     // ajax delete data from database
       $.ajax({
         url : "<?php echo site_url('users/delete_user')?>/"+id,
         type: "POST",
         dataType: "JSON",
         success: function(data)
         {
            location.reload();
         },
         error: function (jqXHR, textStatus, errorThrown)
         {
             alert('Error deleting data');
         }
     });
   }
 }
</script>
