<div class="content-top-1 box box-default">
    <div class="box-header">
        <div class="box-tools pull-right" style="padding-right: 30px">
            &nbsp;&nbsp;
            <a class="btn btn-success" data-target="#usersmodal" data-toggle="modal"><i class="fa fa-user"></i> Add User</a>
            &nbsp;&nbsp;
            <button id="disableuser" class="btn btn-danger"><i class="fa fa-ban"></i> Disable Access</button>
        </div>
    </div>

    <div class="box-body">
        <br><br>
        <div class="col-md-12">
            <div id="disablelabel" class="label label-info"></div>
            <table id="usersTable" class="ui celled table stripe" cellspacing="0" width="100%">
                <thead>
                    <th></th>
                    <th>Email</th>
                    <th>First Name</th>
                    <th>Email</th>
                    <th>Phone</th>
                    <th>Role</th>
                    <th>Registered On</th>
                    <th>Status</th>
                </thead>
            </table>
        </div>
    </div>
</div>

<div id="usersmodal" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title">Users</h4>
            </div> 
            <?= form_open("/users/addUser"); ?>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6">
                        <label for="name">First Name <span class="required">*</span></label>
                        <input class="form-control" required="required" name="firstname" placeholder="First Name" type="text">
                        <br>
                        <label for="name">Second Name <span class="required">*</span></label>
                        <input class="form-control" required="required" name="secondname" placeholder="Second Name" type="text">
                        <br>
                        <label for="phone">Phone Number <span class="required">*</span></label>
                        <input name="phoneno" class="form-control phone" required="required" pattern="^(0)([0-9]{9})$" title="Phone number should start with: 0xxxxxxxxx" placeholder="Phone number (0xxxxxxxxx)" type="text">
                        <label class="label label-danger" id="perror"></label>
                    </div>
                    <div class="col-md-6">
                        <label for="email">Email / Username <span class="required">*</span></label>
                        <input name="email" class="form-control email" required="required" placeholder="email@mzawadi.com" type="email">
                        <label class="label label-danger" id="error"></label>
                        <br>
                        <label for="name">User Level <span class="required">*</span></label>
                        <select class="form-control" required="required" name="usertype" style="width: 100%;">
                            <option selected="selected" value="">Select User Level</option>
                            <option value="Normal">Normal Level</option>
                            <option value="Admin">Admin Level</option>
                        </select>
                    </div>
                </div>
            </div>

            <div class="modal-footer">
                <button type="submit" class="btn btn-primary ">Save</button>
            </div>
            </form>
        </div>
    </div>
</div>

<script type="text/javascript">
    var table;

    function loadTable() {
        table = $('#usersTable').DataTable({
            destroy: true,
            responsive: true,
            "ajax": {
                url: '/tables/fetchusers',
                type: 'get'
            },
            select: {
                style: 'single',
                selector: 'td'
            },
            columnDefs: [{
                orderable: false,
                className: 'select-checkbox',
                targets: 0
            }],
            language: {
                searchPlaceholder: "Search records.."
            },
            scrollY: "600px",
            scrollX: true,
            scrollCollapse: true,
            paging: true,
            fixedColumns: true,
            lengthChange: true,
            buttons: ['excelHtml5', 'pdfHtml5', 'colvis'],
            "rowCallback": function(nRow, aData) {
                $('td', nRow).eq(0).html('<input type="hidden" class="select" value="' + aData[0] + '">');

                if(aData[7] == "Active")
                $('td', nRow).eq(7).html('<label class="label label-success">' + aData[7] + '</label>');
                else
                $('td', nRow).eq(7).html('<label class="label label-danger">' + aData[7] + '</label>');
            }

        });

        var buttons = new $.fn.dataTable.Buttons(table, {
            buttons: ['excelHtml5', 'pdfHtml5', 'colvis']
        });
        buttons.container().appendTo($('div.right.aligned.eight.column:eq(0)', table.table().container()));
    }

    $(document).ready(function() {
        var action = "";

        $('#disableuser').click(function() {
            if (table.rows('.selected').data().length > 0) {
                $(".btn").attr("disabled", "disabled");
                var row = table.rows('.selected').data()[0];
                $('#disablelabel').html("Processing Please Wait...");
                $.ajax({
                    url: "/users/disableThis",
                    data: {
                        usercode: btoa(row[0]),
                        action: action
                    },
                    type: "get",
                    success: function(data) {
                        alert(data);
                        $('#disablelabel').html("");
                        loadTable();
                        $(".btn").removeAttr("disabled");
                    }
                });
            } else
                alert("please select a user to continue");
        }); 

        $('.email').change(function() {
            var email = this.value;
            var memail = this;

            $.ajax({
                url: "/users/checkUser",
                data: {
                    email: email
                },
                type: "get",
                success: function(data) {
                    var json = JSON.parse(data);
                    if (json.result != "OK") {
                        $(memail).val('');
                        $(memail).css('border', 'solid 1px #ff0000');
                        $('#error').html("<i class='fa fa-exclamation-triangle'></i> This email has already been used in the system. Use another email");
                    } else
                        $('#error').html("");
                }
            });
        });

        $('.phone').change(function() {
            var edit = $('#edit').val();
            var email = this.value;
            var memail = this;
            $.ajax({
                url: "/users/checkPhone",
                data: {
                    phone: email
                },
                type: "get",
                success: function(data) {
                    var json = JSON.parse(data);
                    if (json.result != "OK") {
                        $(memail).val('');
                        $(memail).css('border', 'solid 1px #ff0000');
                        $('#perror').html("<i class='fa fa-exclamation-triangle'></i> This phone number has already been used in the system. Use another phone number");
                    } else if (edit == "")
                        $('#perror').html("");
                }
            });
        }); 

        loadTable();

        $('#usersTable tbody').on('click', 'tr', function () {
            var data = table.row( this ).data();
            action = data[7] == "Active"?0:1;
            if(data[7] == "Active"){
                $('#disableuser').html('<i class="fa fa-ban"></i> Disable Access')
            } else {
                $('#disableuser').html('<i class="fa fa-check"></i> Enable Access')
            }
        });

    });
</script>