<?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">Item</h2>
                <button class="btn btn-outline-success" id="btnCreateNew">Create Item</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 id="myTable" class="table card-table table-vcenter text-nowrap datatable" >
                                <thead>
                                    <tr>
                                        <!-- <th class="w-1"><input class="form-check-input m-0 align-middle" type="checkbox" aria-label="Select all reservations"></th> -->
                                        <th>Category Code</th>
                                        <th>Category</th>
                                        <th>Type Code</th>
                                        <th>Type</th>
                                        <th>Item Code</th>
                                        <th>Item Name</th>
                                        <th>Barcode</th>
                                        <th>Capital Price</th>
                                        <th>Sales Price</th>
                                        <th>Supplier</th>
                                        <th class="w-1"></th>
                                    </tr>
                                </thead>
                                <tbody>

                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="createEntryModal" tabindex="-1" aria-labelledby="createEntryModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="createEntryModalLabel">Item 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="itemId">
                    <div class="mb-3 row">
                        <label for="category" class="col-4 col-form-label text-end">Category</label>
                        <div class="col">
                            <select class="form-select" id="category" required>
                                <option value="" disabled selected>Select category</option>
                            </select>
                        </div>

                    </div>
                    <div class="mb-3 row">
                    <label for="type" class="col-4 col-form-label text-end">Type</label>
                        <div class="col">
                            <select class="form-select" id="type" required>
                                <option value="" disabled selected>Select type</option>
                            </select>
                        </div>
                    </div>
                    <div class="mb-3 row">
                        <label class="col-4 col-form-label text-end">Item Code</label>
                        <div class="col">
                        <input type="text" id="itemCode" class="form-control" placeholder="Enter item code" disabled>
                        </div>
                    </div>
                    <div class="mb-3 row">
                        <label class="col-4 col-form-label text-end">Item Name</label>
                        <div class="col">
                        <input type="text" id="itemName" class="form-control" placeholder="Enter item name">
                        </div>
                    </div>
                    <div class="mb-3 row">
                        <label class="col-4 col-form-label text-end">Barcode</label>
                        <div class="col">
                        <input type="text" id="barcode" class="form-control" placeholder="Enter barcode">
                        </div>
                    </div>
                    <div class="mb-3 row">
                        <label class="col-4 col-form-label text-end">Capital Price</label>
                        <div class="col">
                        <input type="text" id="capitalPrice" class="form-control" placeholder="Enter capital price">
                        </div>
                    </div>
                    <div class="mb-3 row">
                        <label class="col-4 col-form-label text-end">Sales Price</label>
                        <div class="col">
                        <input type="text" id="salesPrice" class="form-control" placeholder="Enter sales price">
                        </div>
                    </div>
                    <div class="mb-3 row">
                        <label class="col-4 col-form-label text-end">Supplier</label>
                        <div class="col">
                        <input type="text" id="supplier" class="form-control" placeholder="Enter supplier">
                        </div>
                    </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() {

    // $('#createEntryModal').modal({
    //     backdrop: 'static', // Prevents closing the modal by clicking outside it
    //     keyboard: false // Prevents closing the modal with the Escape key
    // });

    $("input[type='number']").on("input", function() {
        this.value = this.value.replace(/[^0-9]/g, ''); // Remove non-numeric characters
    });
    fillCategory();
    fillType();
    getAll();
});

function fillCategory(){
    $.ajax({
        url: APP_URL + "api/category/get_all_rows.php"
    }).done(function(data) {	
    $("#category").find("option").remove();
        $.each(data.records, function(i, v) {	
            $("#category").append("<option value= '" + v.category + "' code='"+v.category_code+"' id='"+v.id+"'>" + v.category + "</option>");		
        });
    });
}

function fillType(){
    $.ajax({
        url: APP_URL + "api/type/get_all_rows.php"
    }).done(function(data) {	
    $("#type").find("option").remove();
        $.each(data.records, function(i, v) {	
            $("#type").append("<option value= '" + v.type + "' code='"+v.type_code+"' id='"+v.id+"'>" + v.type + "</option>");		
        });
    });
}

// function fillroom_type() {
//     $("#room_type").find("option").remove(); // Clear existing options
//     $("#room_type").append("<option value='' disabled selected>Select Room Type</option>"); // Add default option

//     $.ajax({
//         url: APP_URL + "api/room_type/get_all_rows.php"
//     }).done(function(data) {
//         $.each(data.records, function(i, v) {
//             console.log(v); // Log for debugging
//             $("#room_type").append("<option value='" + v.id + "'>" + v.room_type + "</option>");
//         });
//     }).fail(function(jqXHR, textStatus, errorThrown) {
//         console.error("Error fetching room types:", textStatus, errorThrown);
//         showAlert("Failed to load room types. Please try again later.", "danger", 2);
//     });
// }


function getAll() {
    $('#myTable').DataTable().destroy();
    let table = $('#myTable').DataTable({
        ajax: {
            url: APP_URL + "api/item/get_all_rows_datatable.php",
            method: "GET",
            dataType: "json",
            dataSrc: 'records' 
        },
        columns: [
            { data: 1 }, 
            { data: 2 },
            { data: 3 }, 
            { data: 4 }, 
            { data: 5 }, 
            { data: 6 }, 
            { data: 7 }, 
            { data: 8 },
            { data: 9 },
            { data: 10 },
            { 
                data: null, 
                render: function(data, type, row) {
                    return "<div class='btn-list flex-nowrap'>" +
                        "<button class='btn btn-outline-primary btn-sm' onclick='edit(\"" + row[0] + "\")'>Edit</button> " + // ID
                        "<button class='btn btn-outline-danger btn-sm' onclick='del(\"" + row[0] + "\", this)'>Delete</button>" + // ID
                        "</div>";
                }
            }
        ],
        paging: true,
        language: {
            emptyTable: "No records found",
            info: "Showing _START_ to _END_ of _TOTAL_ entries",
            lengthMenu: "Show _MENU_ entries",
            search: "Search:",
            zeroRecords: "No records found"
        }
    });
}

$("#btnCreateNew").click(function() {
    // $("#createEntryForm").trigger("reset");
    // $("#roomId").val("");
    // $("#roomNumber").prop("disabled", false);
    $('#createEntryModal').modal('show');
    $("#itemId").val("");
    generateItemCode();
    $("#btnSave").text("Create").removeClass("btn-outline-primary").addClass("btn-outline-success");
});

$("#category").change(function(){
    generateItemCode();
});


$("#type").change(function(){
    generateItemCode();
});

function generateItemCode() {
    $("#itemCode").val("");
    $("#itemName").val("");
    var categoryCode = $("#category option:selected").attr("code");
    var typeCode = $("#type option:selected").attr("code");
    
    if(categoryCode && typeCode) {
        var code = categoryCode + typeCode;
        $.ajax({
            url: APP_URL + "api/item/generate_item_code.php",
            type: "POST",
            data: JSON.stringify({ code: code }),
        }).done(function(data) {
            $("#itemCode").val(data.item_code);
        });
    }
}


function validateAndSave() {

    let isValid = true;

    $("#itemName").removeClass("is-invalid");
    $("#salesPrice").removeClass("is-invalid");

    if ($("#itemName").val() === null || $("#itemName").val().trim() === "") {
        $("#itemName").addClass("is-invalid");
        isValid = false; 
    }

    // if ($("#salesPrice").val() === null || $("#salesPrice").val().trim() === "" || $("#salesPrice").val().trim() === 0) {
    //     $("#salesPrice").addClass("is-invalid");
    //     isValid = false; 
    // }

    if (isValid) {

        // $(this).prop("disabled", true).text("Loading...");

        var item = {
            "id": $("#itemId").val(),
            "category_code": $("#category option:selected").attr("code"),
            "category": $("#category").val(),
            "type_code": $("#type option:selected").attr("code"),
            "type": $("#type").val(),
            "item_code": $("#itemCode").val(),
            "item_name": $("#itemName").val(),
            "barcode": $("#barcode").val(),
            "capital_price": (parseFloat($("#capitalPrice").val().replace(/,/g, ''))) ? parseFloat($("#capitalPrice").val().replace(/,/g, '')) : 0,
            "sales_price": (parseFloat($("#salesPrice").val().replace(/,/g, ''))) ? parseFloat($("#salesPrice").val().replace(/,/g, '')) : 0,
            "supplier": $("#supplier").val(),
        };

        $.ajax({
            type: "POST",
            url: APP_URL + "api/item/create_update.php",
            data: JSON.stringify(item),
            success: function(data) {
                if (data.message === "created" || data.message === "updated") {
                    // $("#createEntryForm").trigger("reset");
                    $('#createEntryModal').modal('hide');
                    $("#itemName").val("");
                    showAlert("Item " + (data.message === "created" ? "Created" : "Updated") + " Successfully!", "success");
                    getAll();

                } else if (data.message === "duplicate") {
                    showAlert("Item already exists!", "warning");
                } else {
                    showAlert("An error occurred on the server!", "error");
                }
            },
            error: function() {
                showAlert("An error occurred while saving!", "error");
            },
            complete: function() {
                // $("#btnSave").prop("disabled", false).text(button.innerText);
            }
        });
    }
}



function edit(id) {
    $("#createEntryForm").trigger("reset");
    $("#btnSave").text("Update").removeClass("btn-outline-success").addClass("btn-outline-primary");
    $('#createEntryModal').modal('show');
    $("#itemId").val(id);
    $.ajax({
        url: APP_URL + "api/item/get_one_row.php",
        type: "POST",
        data: JSON.stringify({ id: id })
    }).done(function(data) {
        if (data) {
            // $("#roomNumber").prop("disabled", true);
            $("#category").val(data.category);
            $("#type").val(data.type); 
            $("#itemCode").val(data.item_code);
            $("#itemName").val(data.item_name);
            $("#barcode").val(data.barcode);
            $("#capitalPrice").val(data.capital_price);
            $("#salesPrice").val(data.sales_price);
            $("#supplier").val(data.supplier);
        } else {
            console.log(data);
        }
    });
}

function del(id,obj) {
        Swal.fire({
            title: 'Are you sure?',
            text: `You are about to delete item`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    type: "POST",
                    url: APP_URL + "api/item/delete.php",
                    data: JSON.stringify({ id: id }),
                    success: function(data) {
                        if (data=== "deleted") {
                            getAll();
                            showAlert("Item Deleted Successfully!", "success");
                        } else {
                            showAlert("An error occurred on the server!", "error");
                        }
                    },
                    error: function() {
                        showAlert("An error occurred while saving!", "error");
                    }
                });
            }
        });
    }


function showAlert(message, type) {
    Swal.fire({
        title: type === 'success' ? 'Success!' : 'Oops!',
        text: message,
        icon: type,
        // confirmButtonText: 'OK',
        timer: 1000, // Auto close after 3000 milliseconds (3 seconds)
        timerProgressBar: true, // Optional: Show a progress bar
        willClose: () => {
            // Optional: Execute code just before the alert closes
            console.log('Alert closed');
        }
    });
}
</script>
