<?php include '../header.php'; ?> 
<?php include '../sidemenu.php'; ?> 

<div class="page-header d-print-none">
    <div class="container-xl">
        <div class="row g-2 align-items-center">
            <div class="col d-flex justify-content-between">
                <h2 class="page-title">Category</h2>
                <button class="btn btn-outline-success" id="btnCreateNew">Create Category</button>
            </div>
        </div>
    </div>
</div>

<div class="container" id="alertContainer1"></div>
<div class="page-body">
    <div class="container-xl">
        <div class="row row-cards">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-vcenter card-table" id="myTable">
                                <thead>
                                    <tr>
                                        <th>Category Code</th>
                                        <th>Category</th>
                                        <th class="w-1"></th>
                                    </tr>
                                </thead>
                                <tbody>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="createModel" tabindex="-1" aria-labelledby="createModelLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="createModelLabel">Category Entry</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="container" id="alertContainer2"></div>
            <div class="modal-body">
                <form id="createEntryForm">
                    <input type="hidden" class="form-control" id="txtRoomId">
                    <div class="mb-3">
                        <label for="categoryCode" class="form-label">Category Code</label>
                        <input type="text" class="form-control" id="categoryCode" placeholder="Enter category code" required>
                    </div>
                    <div class="mb-3">
                        <label for="category" class="form-label">Category</label>
                        <input type="text" class="form-control" id="category" placeholder="Enter category" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" id="btnSave" class="btn btn-outline-success" onclick="validateAndSave()">Create</button>
            </div>
        </div>
    </div>
</div>

<?php include '../footer.php'; ?>

<script>
$(function() {
    getAll();
});


function getAll() {
    $("#myTable").find("tbody").empty();
    $.ajax({
        url: APP_URL + "api/category/get_all_rows.php"
    }).done(function(data) {
        $.each(data.records, function(i, v) {
            $("#myTable").find("tbody")
            .append($('<tr>')
                .append("<td>" + v.category_code + "</td>")
                .append("<td>" + v.room_type + "</td>")
                .append("<td><div class='btn-list flex-nowrap'><button class='btn btn-outline-primary btn-sm' onclick='edit(\"" + v.id + "\")'>Edit</button><button class='btn btn-outline-danger btn-sm' onclick='del(\"" + v.id + "\", this)'>Delete</button></div></td>")
            );
        });
    });
}

$("#btnCreateNew").click(function() {
    $("#createEntryForm").trigger("reset");
    $('#createModel').modal('show');
    $("#btnSave").text("Create").removeClass("btn-outline-primary").addClass("btn-outline-success");
});

function validate() {
    if ($("#categoryCode").val().trim() === "") {
        showAlert("Category code shouldn't be blank!", "warning", 2);
        return false;
    }

    // if ($("#cboRoomType").val() === null || $("#cboRoomType").val().trim() === "") {
    //     showAlert("Room Type shouldn't be blank!", "warning", 2);
    //     return false;
    // }
    return true;
}

function validateAndSave() {
    if (validate()) {
        $("#btnSave").prop("disabled", true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Saving...');

        var room_entry = {
            "id": $("#txtRoomId").val(),
            "category_code": $("#categoryCode").val(),
            "room_type_id": $("#cboRoomType").val(),
            "bed_type": $("#category").val()
        };

        $.ajax({
            type: "POST",
            url: APP_URL + "api/category/create_update.php",
            data: JSON.stringify(room_entry),
            success: function(data) {
                if (data.message === "created" || data.message === "updated") {
                    $("#createEntryForm").trigger("reset");
                    $('#createModel').modal('hide');
                    showAlert("Category Entry " + (data.message === "created" ? "Created" : "Updated") + " Successfully!", "success", 1);
                    getAll();
                }  else if (data.message === "duplicate") {
                    showAlert("Duplicate Entry!", "warning", 2);
                } else {
                    showAlert("Error on server side!", "danger", 2);
                }
            },
            error: function() {
                showAlert("Error on server side!", "danger", 2);
            },
            complete: function() {
                $("#btnSave").prop("disabled", false).text("Create");
            }
        });
    }
}

function edit(id) {
    $("#createEntryForm").trigger("reset");
    $("#btnSave").text("Update").removeClass("btn-outline-success").addClass("btn-outline-primary");
    $('#createModel').modal('show');
    $("#txtRoomId").val(id);
    $.ajax({
        url: APP_URL + "api/category/get_one_row.php",
        type: "POST",
        data: JSON.stringify({ id: id })
    }).done(function(data) {
        if (data) {
            $("#categoryCode").val(data.category_code);
            $("#cboRoomType").val(data.room_type_id); 
            $("#category").val(data.bed_type);
        } else {
            console.log(data);
        }
    });
}

function del(id, obj) {
    $('#modal-delete').modal('show');
    $('#confirm-delete').off('click').on('click', function() {
        $(this).prop("disabled", true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Deleting...');

        $.ajax({
            type: "POST",
            url: APP_URL + "api/category/delete.php",
            data: JSON.stringify({ id: id }),
            success: function(data) {
                if (data.message === "deleted") {
                    $(obj).closest("tr").remove();
                    showAlert("Category Entry Deleted Successfully!", "success", 1);
                } else {
                    showAlert("Error on server side!", "danger", 2);
                }
            },
            error: function() {
                showAlert("Error on server side!", "danger", 2);
            },
            complete: function() {
                $('#modal-delete').modal('hide');
                $('#confirm-delete').prop("disabled", false).text("Delete");
            }
        });
    });
}

</script>
