<?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">Vehicle Category</h2>
                <button class="btn btn-outline-success" id="btnCreateNew">Create Vehicle 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>Vehicle Category</th>
                                        <th>Description</th>
                                        <th>Rental Rate</th>
                                        <th>Max Occupancy</th>
                                        <th>Amenities</th>
                                        <th>Add-on Rate</th>
                                        <th class="w-1"></th>
                                    </tr>
                                </thead>
                                <tbody>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="createRoomTypeModel" tabindex="-1" aria-labelledby="createRoomTypeModelLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="createRoomTypeModelLabel">Vehicle 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="createRoomTypeForm">
                    <input type="hidden" class="form-control" id="txtRoomTypeId">
                    <div class="mb-3">
                        <label for="txtRoomType" class="form-label">Vehicle Category</label>
                        <input type="text" class="form-control" id="txtRoomType" placeholder="Enter vehicle category" required>
                    </div>
                    <div class="mb-3">
                        <label for="txtDescription" class="form-label">Description</label>
                        <textarea class="form-control" id="txtDescription" placeholder="Enter description" required></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="txtRoomRate" class="form-label">Rental Rate</label>
                        <input type="number" class="form-control" id="txtRoomRate" placeholder="Enter rate" step="10000" required>
                    </div>
                    <div class="mb-3">
                        <label for="txtMaxOccupancy" class="form-label">Max Occupancy</label>
                        <input type="number" class="form-control" id="txtMaxOccupancy" placeholder="Enter max occupancy" required>
                    </div>
                    <div class="mb-3">
                        <label for="txtAmenities" class="form-label">Amenities</label>
                        <input type="text" class="form-control" id="txtAmenities" placeholder="Enter amenities" required>
                    </div>
                    <div class="mb-3">
                        <label for="txtExtraBedRate" class="form-label">Add-on Rate</label>
                        <input type="number" class="form-control" id="txtExtraBedRate" placeholder="Enter add-on rate" step="10000" 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/room_type/get_all_rows.php"
    }).done(function(data) {
        $.each(data.records, function(i, v) {
            $("#myTable").find("tbody")
            .append($('<tr>')
                .append("<td>" + v.room_type + "</td>")
                .append("<td>" + v.description + "</td>")
                .append("<td>" + v.room_rate + "</td>")
                .append("<td>" + v.max_occupancy + "</td>")
                .append("<td>" + v.amenities + "</td>")
                .append("<td>" + v.extra_bed_rate + "</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() {
    $("#createRoomTypeForm").trigger("reset");
    $('#createRoomTypeModel').modal('show');
    $("#btnSave").text("Create").removeClass("btn-outline-primary").addClass("btn-outline-success");
});

function validate() {
    if ($("#txtRoomType").val().trim() === "") {
        showAlert("Vehicle category 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 roomRate = $("#txtRoomRate").val().trim() === "" ? 0 : parseFloat($("#txtRoomRate").val().replace(/,/g, ''));
        var maxOccupancy = $("#txtMaxOccupancy").val().trim() === "" ? 0 : parseFloat($("#txtMaxOccupancy").val().replace(/,/g, ''));
        var extraBedRate = $("#txtExtraBedRate").val().trim() === "" ? 0 : parseFloat($("#txtExtraBedRate").val().replace(/,/g, ''));

        var room_type = {
            "id": $("#txtRoomTypeId").val(),
            "room_type": $("#txtRoomType").val(),
            "description": $("#txtDescription").val(),
            "room_rate": roomRate,
            "max_occupancy": maxOccupancy,
            "amenities": $("#txtAmenities").val(),
            "extra_bed_rate": extraBedRate
        };

        $.ajax({
            type: "POST",
            url: APP_URL + "api/room_type/create_update.php",
            data: JSON.stringify(room_type),
            success: function(data) {
                if (data.message === "created" || data.message === "updated") {
                    $("#createRoomTypeForm").trigger("reset");
                    $('#createRoomTypeModel').modal('hide');
                    showAlert("Vehicle category " + (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) {
    $("#createRoomTypeForm").trigger("reset");
    $("#btnSave").text("Update").removeClass("btn-outline-success").addClass("btn-outline-primary");
    $('#createRoomTypeModel').modal('show');
    $("#txtRoomTypeId").val(id);
    $.ajax({
        url: APP_URL + "api/room_type/get_one_row.php",
        type: "POST",
        data: JSON.stringify({ id: id })
    }).done(function(data) {
        if (data.room_type) {
            $("#txtRoomType").val(data.room_type);
            $("#txtDescription").val(data.description);
            $("#txtRoomRate").val(data.room_rate);
            $("#txtMaxOccupancy").val(data.max_occupancy);
            $("#txtAmenities").val(data.amenities);
            $("#txtExtraBedRate").val(data.extra_bed_rate);
        } 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/room_type/delete.php",
            data: JSON.stringify({ id: id }),
            success: function(data) {
                if (data === "deleted") {
                    $(obj).closest('tr').remove();
                    showAlert("Vehicle category deleted successfully!", "success", 1);
                } else {
                    showAlert("Error on server side!", "danger", 1);
                }
                $('#modal-delete').modal('hide');
            },
            error: function() {
                showAlert("Error on server side!", "danger", 1);
            },
            complete: function() {
                $('#confirm-delete').prop("disabled", false).text("Delete");
            }
        });
    });
}

</script>
