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

<style>
    #myTable tbody tr:hover {
        background-color: #f1f1f1;
        cursor: pointer;
    }
</style>

<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">Sales & Service</h2>
            </div>
        </div>
    </div>
</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>Category</th>
                                        <th>Type</th>
                                        <th>Item Code</th>
                                        <th>Item Name</th>
                                        <th>Sales Price</th>
                                        <th class="w-1"></th>
                                    </tr>
                                </thead>
                                <tbody>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- Item Selection Form -->
                    <div class="row">
                        <div class="col-4 mb-3 row">
                            <label class="col-4 col-form-label text-end">Item Name</label>
                            <div class="col">
                                <input type="hidden" id="itemCode" class="form-control" disabled>
                                <input type="text" id="itemName" class="form-control" placeholder="Enter item name" disabled>
                            </div>
                        </div>

                        <div class="col-4 mb-3 row">
                            <label class="col-4 col-form-label text-end">Quantity/Price</label>
                            <div class="col-3">
                                <input type="number" id="quantity" class="form-control" value="1" min="1" oninput="validateInput(this)">
                            </div>
                            <div class="col-5">
                                <input type="text" id="price" class="form-control" placeholder="Enter price" oninput="validateInput(this)">
                            </div>
                        </div>

                        <div class="col-2 mb-3 row">
                            <label class="col-4 col-form-label text-end">FOC</label>
                            <div class="form-check col-3" style="margin-top: 10px;">
                                <input type="checkbox" class="form-check-input" id="focCheck">
                            </div>
                        </div>

                        <div class="col-1 mb-3 row">
                            <button type="button" id="btnAdd" class="btn btn-outline-success" onclick="addItem()">Add</button>
                        </div>
                    </div>

                    <!-- Sales Table -->
                    <div class="mb-3 mt-3 table-responsive">
                        <table class="table table-vcenter card-table" id="salesTable">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Category</th>
                                    <th>Type</th>
                                    <th>Item Code</th>
                                    <th>Item Name</th>
                                    <th>Quantity</th>
                                    <th>Price</th>
                                    <th>Amount</th>
                                    <th class="w-1"></th>
                                    <th class="w-1"></th>
                                </tr>
                            </thead>
                            <tbody class="stay-grid">
                            </tbody>
                        </table>
                    </div>

                    <!-- Summary and Options -->
                    <div class="row">
                        <div class="col-4 mb-3 row offset-8">
                            <label class="col-4 col-form-label text-end">Total Amount</label>
                            <div class="col">
                                <input type="text" id="totalAmount" class="form-control" disabled>
                            </div>
                        </div>

                        <div class="col-4 mb-3 row offset-8">
                            <label class="col-4 col-form-label text-end">Payment Method</label>
                            <div class="col">
                                <select class="form-select" id="paymentMethod" required>
                                    <option value="Cash" selected>Cash</option>
                                    <option value="Card">Card</option>
                                    <option value="Charge to Booking">Charge to Booking</option>
                                </select>
                            </div>
                        </div>

                        <div class="col-4 mb-3 row offset-8">
                            <label class="col-4 col-form-label text-end">Vehicle No.</label>
                            <div class="col">
                                <select class="form-select" id="roomNo" required disabled>
                                    <option value=""></option>
                                </select>
                            </div>
                        </div>

                        <div class="col-4 mb-3 row offset-8">
                            <label class="col-4 col-form-label text-end">Customer Name</label>
                            <div class="col">
                                <input type="text" id="customerName" class="form-control" placeholder="Enter customer name" >
                            </div>
                        </div>

                        <div class="col-4 mb-3 row offset-8">
                            <div class="col">
                            <button type="button" id="btnSave" class="btn btn-outline-success col-4 offset-8 text-end" onclick="save()">Save</button>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

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

<script>
        let selectedRowData = null;

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




	function fillRoom(){
		$("#roomNo").find("option").remove();
		$("#roomNo").append("<option value = '' data-id = ''></option>");
		$.ajax({
			url: APP_URL + "api/check_in/get_all_room_no.php",
		}).done(function(data) {
			$.each(data.records, function(i, v) {
				$("#roomNo").append("<option value= '" + v.room_no + "' data-id = '"+ v.checkin_id +"' data-guest = '" + v.guest_name + "'>" + v.room_no + "</option>");
			});
			$("#txtGuestName").val($("#roomNo option:selected").attr('data-guest'));
		});
	}

    $("#paymentMethod").change(function(){
		if($("#paymentMethod").val()=="Cash" || $("#paymentMethod").val()=="Card"){
			$("#roomNo").find("option").remove();
            $("#roomNo").attr("disabled", true);
            $("#customerName").attr("disabled", false);
			$("#customerName").val("");
		}else{
			$("#roomNo").attr("disabled", false);
            $("#customerName").attr("disabled", true);
			fillRoom();
		}
	});

    $("#roomNo").change(function(){
		$("#customerName").val($("#roomNo option:selected").attr('data-guest'));
	});

        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: 2 }, 
                    { data: 4 },
                    { data: 5 }, 
                    { data: 6 }, 
                    { data: 8 }, 
                    { 
                        data: null, 
                        render: function(data, type, row) {
                            return "";
                        }
                    }
                ],
                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"
                }
            });

            $('#myTable tbody').on('click', 'tr', function() {
                $('#myTable tbody tr').removeClass('selected');
                $(this).addClass('selected');
                var table = $('#myTable').DataTable();
                selectedRowData = table.row(this).data();

                if (selectedRowData) {
                    $("#itemName").val(selectedRowData[6]);
                    $("#price").val(selectedRowData[8]);
                    $("#itemCode").val(selectedRowData[5]);
                }
            });
        }

        function addItem() {
            if (!selectedRowData) {
                showAlert("Please select an item from the table before adding.", "warning");
                return;
            }

            let itemName = selectedRowData[6];
            let itemCode = selectedRowData[5];
            let category = selectedRowData[2];
            let type = selectedRowData[4];

            let quantity = parseFloat($("#quantity").val());
            if (isNaN(quantity) || quantity <= 0) {
                showAlert("Please enter a valid quantity.", "warning");
                return;
            }

            // Set price and foc value
            let price = parseFloat($("#price").val());
            let priceC = $("#focCheck").is(":checked") ? 0 : parseFloat($("#price").val());
            let foc = $("#focCheck").is(":checked") ? 1 : 0; // 1 if checked, 0 if unchecked
            let displayItemName = $("#focCheck").is(":checked") ? itemName + " (FOC)" : itemName;
            let amount = quantity * priceC;

            console.log("Adding Item - Name:", displayItemName, "Quantity:", quantity, "Price:", price, "Amount:", amount, "FOC:", foc);

            $("#salesTable tbody").append(`
                <tr>
                    <td>${$("#salesTable tbody tr").length + 1}</td>
                    <td>${category}</td>
                    <td>${type}</td>
                    <td>${itemCode}</td>
                    <td>${displayItemName}</td>
                    <td>${quantity}</td>
                    <td>${price.toFixed(2)}</td>
                    <td class="amount">${amount.toFixed(2)}</td>
                    <td><button type="button" class="btn btn-sm btn-outline-danger" onclick="$(this).closest('tr').remove(); calculateTotalAmount();">Remove</button></td>
                    <td><input type="hidden" class="focValue" value="${foc}"> <!-- Hidden FOC value --></td>
                </tr>
            `);

            calculateTotalAmount();
        }



        function calculateTotalAmount() {
            let totalAmount = 0;

            $("#salesTable tbody .amount").each(function() {
                let amount = parseFloat($(this).text());
                totalAmount += isNaN(amount) ? 0 : amount;
            });
            $("#totalAmount").val(totalAmount.toFixed(2));
            console.log("Total Amount Updated:", totalAmount);
        }

        function validateInput(input) {
            if (input.value < 0) {
                input.value = 1;
            }
        }

        function showAlert(message, type) {
            Swal.fire({
                title: type === 'success' ? 'Success!' : 'Oops!',
                text: message,
                icon: type,
                timer: 1000,
                timerProgressBar: true,
            });
        }

        function save(){

            var room_no = $("#roomNo").val();
            var customer_name = $("#customerName").val();

            if($("#paymentMethod").val()=="Charge to Booking"){
                check_in_id = $("#roomNo option:selected").attr("data-id");
            }else{
                check_in_id = 0;
            }

            var items = [];
            $("#salesTable tbody tr").each(function (){
                var item = {
                    "category" : $(this).find("td").eq(1).text(),
                    "type" : $(this).find("td").eq(2).text(),
                    "item_code": $(this).find("td").eq(3).text(),
                    "item_name": $(this).find("td").eq(4).text(),
                    "foc": $(this).find(".focValue").val(), // Get FOC value from hidden field
                    "quantity": $(this).find("td").eq(5).text(),
                    "price": $(this).find("td").eq(6).text().replace(/,/g, ''),
                }
                items.push(item);
            });

            var item_sales = {
                "check_in_id": check_in_id,
                "room_no": room_no,
                "customer_name": customer_name,
                "payment_type": $("#paymentMethod").val(),
                "items": items
            };

            if($("#salesTable tbody tr").length==0){
                showAlert("Please add at least one item before saving.", "warning");

            }else{
                $.ajax({
                    url: APP_URL + "api/sales/create.php",
                    type: "POST",
                    data: JSON.stringify(item_sales)
                }).done(function(data) {

                    if(data.message=="created"){
                        // bootbox.confirm({
                        //     message: "<h4>Do you want to print?</h4>",
                        //     buttons: {
                        //         confirm: {
                        //             label: '<span class="glyphicon glyphicon-ok"></span> Yes',
                        //             className: 'btn-primary'
                        //         },
                        //         cancel: {
                        //             label: '<span class="glyphicon glyphicon-remove"></span> No',
                        //             className: 'btn-danger'
                        //         }
                        //     },
                        //     callback: function (result) {
                        //         if(result){
                        //             gotoItemSalePrint(data.date_time);
                        //         }
                        //     }
                        // });
                        showAlert2("Data saved successfully.", "success");
                        // setTimeout(function() {
                        //     location.reload();
                        // }, 2000);
                        // reload the page after 2 sec
                    }else if(data.message=="error"){
                        showAlert("Error on server side.",'error');
                    }
                });
            }
        }

        function showAlert2(message, type) {
            Swal.fire({
                title: type === 'success' ? 'Success!' : 'Oops!',
                text: message,
                icon: type,
                // confirmButtonText: 'OK',
                timer: 2000, // 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>
