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

<style>
        .custom-modal {
            max-width: 1400px; /* Adjust the width as needed */
            width: 100%; /* Makes the modal responsive */
        }

        .custom-alert-container {
            max-width: 1385px; /* Same width as modal */
            width: 100%; /* Makes the alert container responsive */
            margin: 0 auto; /* Center the container */
        }

</style>

<div class="page-header d-print-none">
    <div class="container-xl">
        <div class="row g-2 align-items-center">
            <div class="col">
                <h2 class="page-title">Stock Out</h2>
            </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">
                        <form id="checkInForm">
                        <!-- Reservation Number -->
                            <div class="row">
								<div class="col-3">
									<div class="mb-3">
										<label for="dateOfBirth" class="form-label">Stock Out Date</label>
										<input type="text" class="flatpickr flatpickr-input active form-control" id="dateOfBirth" required>
									</div>
									<!-- <div class="mb-3">
										<label for="reservationNumber" class="form-label">Voucher Number</label>
										<input type="text" class="form-control" id="reservationNumber" placeholder="Enter voucher number" required>
									</div> -->
								</div>
								<div class="col-3">
									<div class="mb-3">
										<label for="reservationNumber" class="form-label">Item Code</label>
										<div class="input-group mb-2">
											<input type="text" class="form-control" id="reservationNumber" placeholder="Enter Item Code" required disabled>
											<button class="btn bg-info" id="btnGuestList" type="button">…</button>
										</div>
									</div>
									<div class="mb-3">
										<label for="reservationNumber" class="form-label">Item Name</label>
										<input type="text" class="form-control" id="reservationNumber" placeholder="Enter item name" required>
									</div>
								</div>
								<div class="col-3">
									<div class="mb-3">
										<label for="numberOfNight" class="form-label">Quantity</label>
										<input type="number" class="form-control" id="numberOfNight" placeholder="Enter quantity" required>
									</div>
									<div class="mb-3">
                                        <label for="roomType" class="form-label">Stock Out Reason</label>
                                        <select class="form-control" id="roomType" required>
                                            <option value="" selected>Use</option>
											<option value="">Lost</option>
											<option value="">Damage</option>
											<option value="">Expire</option>
                                        </select>
                                    </div>
								</div>
								<div class="col-3">
									<!-- <div class="mb-3">
										<label for="Address" class="form-label">Remark</label>
										<textarea class="form-control"  id="remarks" data-bs-toggle="autosize"  style="overflow: hidden; overflow-wrap: break-word; resize: none; text-align: start; height: 39.6px;"></textarea>
									</div> -->
									<div class="mb-3">
										<label for="numberOfNight" class="form-label">Stock Out By</label>
										<input type="number" class="form-control" id="numberOfNight" placeholder="Enter stock in by" required>
									</div>
									<div class="mb-3  d-flex justify-content-end">
										<div class="col-auto">
                                        <label for="guestDetails" class="form-label">&nbsp;</label>
                                            <button type="button" id="btnGuestList" class="btn btn-outline-success">Stock Out</button>
                                        </div>
									</div>
								</div>
                                <div class="col-12">
                                    

                                    <!-- Stay Details Table -->
                                        <div class="mb-3 table-responsive" style="overflow-y: auto;height: 254px;">
                                            <!-- <label class="form-label">Stay Details</label> -->
                                            <table class="table table-vcenter card-table" id="stayDetailsTable">
                                                <thead>
                                                    <tr>
                                                        <th>Stock Out Date</th>
                                                        <th>Item Code</th>
                                                        <th>Item Name</th>
                                                        <th>Quantity</th>
														<th>Stock Out Reason</th>
														<th>Stock Out By</th>
                                                        <th class="w-1"></th>
                                                    </tr>
                                                </thead>
                                                <tbody class="stay-grid">
                                                </tbody>
                                            </table>
                                        </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="guestModel" tabindex="-1" aria-labelledby="guestModelLabel" aria-hidden="true">
    <div class="modal-dialog custom-modal">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="guestModelLabel">Item List</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="container custom-alert-container" id="alertContainer2"></div>
            <div class="modal-body">
                <form id="addGestForm">
					<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</th>
								<th>Type</th>
								<th>Item Code</th>
								<th>Item Name</th>
								<th>Price</th>
								<th>Min.Stock</th>
								<th>Actions</th>
							</tr>
						</thead>
						<tbody>
							<!-- Data will be dynamically inserted here by DataTable -->
						</tbody>
					</table>
					</div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary text-end" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

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

<script>
    $(document).ready(function() {

        $("#genderMale").prop("checked", true);
        flatpickr("#dateOfBirth", {
            dateFormat: "Y-m-d", 
            defaultDate: "2000-01-01",
            // onChange: function(selectedDates, dateStr, instance) {
            //     if (selectedDates.length > 0) {
            //         const birthDate = new Date(selectedDates[0]);
            //         const today = new Date();
            //         let age = today.getFullYear() - birthDate.getFullYear();
            //         const monthDifference = today.getMonth() - birthDate.getMonth();

            //         if (monthDifference < 0 || (monthDifference === 0 && today.getDate() < birthDate.getDate())) {
            //             age--; 
            //         }

            //         $("#age").val(age);
            //     }
            // },
        });
    });

// Update room rate when room number is selected
$("#roomNumber").change(function() {
    const selectedOption = $(this).find(':selected');
    const roomRate = selectedOption.data("rate"); // Extract room rate from data attribute
    $("#roomRate").val(roomRate); // Set room rate input
});

    $("#numberOfNight").on('input', function() {
        const roomNumber = $('#roomNumber').val(); // Get the room number input value

        if (roomNumber != null && roomNumber !== "") { // Check if room number is provided
            const numberOfNights = parseInt($(this).val()) || 0; // Get the number of nights from the input field
            updateStayDetailsTable(numberOfNights); // Call function to update the table
        }
    });


    function updateStayDetailsTable(numberOfNights) {
    const $stayDetailsTableBody = $("#stayDetailsTable tbody");
    $stayDetailsTableBody.empty(); // Clear existing rows

    // Get the current date
    const today = new Date();
    const roomRate = $("#roomRate").val().trim() === "" ? 0 : parseInt($("#roomRate").val().replace(/,/g, ''));

    for (let i = 0; i < numberOfNights; i++) {
        // Create a new row for each night
        const checkInDate = new Date(today);
        checkInDate.setDate(today.getDate() + i); // Increment the date

        const row = `
            <tr>
                <td>${formatDateToYMD(checkInDate)}</td>
                <td><input type="number" class="form-control roomRate" value="${roomRate}" onchange="updateTotal(this)" step="10000" /></td>
                <td><input type="number" class="form-control extraBedRate" value="0" onchange="updateTotal(this)" step="10000" /></td>
                <td><input type="number" class="form-control extraPersonRate" value="0" onchange="updateTotal(this)" step="10000" /></td>
                <td class="total">0</td> <!-- Total -->
                <td>
                    <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeStayRow(this)">Remove</button>
                </td>
            </tr>
        `;
        $stayDetailsTableBody.append(row); // Add the new row to the table
    }
    
    // Update totals for each row after adding rows
    updateAllTotals();
}

function updateTotal(input) {
    const $row = $(input).closest("tr"); // Get the current row
    const roomRate = parseFloat($row.find(".roomRate").val()) || 0;
    const extraBedRate = parseFloat($row.find(".extraBedRate").val()) || 0;
    const extraPersonRate = parseFloat($row.find(".extraPersonRate").val()) || 0;

    // Calculate total for the row
    const total = roomRate + extraBedRate + extraPersonRate; // Adjust this calculation as needed
    $row.find(".total").text(total.toLocaleString()); // Update the total cell with the formatted total
}

function updateAllTotals() {
    $("#stayDetailsTable tbody tr").each(function() {
        updateTotal($(this).find(".roomRate").get(0)); // Call updateTotal for each row
    });
}


    function formatDateToYMD(date) {
        const year = date.getFullYear();
        const month = ('0' + (date.getMonth() + 1)).slice(-2);
        const day = ('0' + date.getDate()).slice(-2);
        return `${year}-${month}-${day}`;
    }

    // Function to remove a stay row from the table
    function removeStayRow(button) {
        $(button).closest('tr').remove();
    }


    $("#btnGuestList").click(function() {
        $('#guestModel').modal('show');
    });

    $("#btnSubmitGuest").click(function() {
    const guestName = $("#guestName").val();
    const contactNumber = $("#contactNumber").val();
    const nrcNumber = $("#nrcNumber").val();
    const passportNumber = $("#passportNumber").val();
    const gender = $("input[name='gender']:checked").val() || "male"; 
    const dateOfBirth = $("#dateOfBirth").val(); 
    const age = $("#age").val(); 
    const address = $("#Address").val(); 

    if (!guestName) {
        showAlert("Please fill guest name.", "warning", 2);
        return;
    }
    if (!contactNumber) {
        showAlert("Please fill contact number.", "warning", 2);
        return;
    }

    const newRow = `
        <tr>
            <td>${guestName}</td>
            <td>${contactNumber}</td>
            <td>${nrcNumber || '-'}</td>
            <td>${passportNumber || '-'}</td>
            <td>${gender}</td>
            <td>${dateOfBirth || '-'}</td> <!-- Optional field -->
            <td>${age || '-'}</td> <!-- Optional field -->
            <td>${address || '-'}</td> <!-- Optional field -->
            <td>
                <button type="button" class="btn btn-outline-danger btn-sm" onclick="removeGuestRow(this)">Remove</button>
            </td>
        </tr>
    `;

    $("#guestTable tbody").append(newRow);

    $("#addGestForm")[0].reset();
    $("#genderMale").prop("checked", true);
});

    function removeGuestRow(button) {
        $(button).closest('tr').remove();
    }

$("#btnSubmitCheckIn").click(function() {

    if ($("#roomType").val().trim() === "") {
        showAlert("Room Type shouldn't be blank!", "warning", 1);
        return false;
    }

    if ($("#roomNumber").val().trim() === "") {
        showAlert("Room Number shouldn't be blank!", "warning", 1);
        return false;
    }

    if ($("#numberOfNight").val().trim() === "" || isNaN($("#numberOfNight").val().trim()) || Number($("#numberOfNight").val().trim()) <= 0) {
        showAlert("Number of Nights should be a positive number!", "warning", 1);
        return false;
    }
    // Collect stay details (if you have a table for stay details, similar to the reservation)
    const stayDetails = []; // Update this if needed to collect stay details
    $('#stayDetailsTable .stay-grid tr').each(function() {
        const row = $(this);
        const stayDetail = {
            date: row.find('td').eq(0).text(),                // Date
            room_rate: row.find('td').eq(2).text(),           // Room Rate
            extra_bed_rate: row.find('td').eq(3).text(),     // Extra Bed Rate
            extra_person_rate: row.find('td').eq(4).text(),      // Extra Person Rate
            total: row.find('td').eq(5).text()                 // Total
        };
        stayDetails.push(stayDetail); // Collect stay details
    });

    // Collect guest information
    const guests = [];
    $("#guestTable tbody tr").each(function() {
        const row = $(this);
        const guest = {
            guestName: row.find("td").eq(0).text(),         // Guest Name
            contactNumber: row.find("td").eq(1).text(),     // Contact Number
            nrcNumber: row.find("td").eq(2).text(),         // NRC Number
            passportNumber: row.find("td").eq(3).text(),     // Passport Number
            gender: row.find("td").eq(4).text(),             // Gender
            dateOfBirth: row.find("td").eq(5).text(),        // Date of Birth
            age: row.find("td").eq(6).text(),                 // Age
            address: row.find("td").eq(7).text()              // Address
        };
        guests.push(guest); // Add guest data to the array
    });

    // Prepare data to be sent to the server
    const checkInData = {
        reservation_number: $('#reservationNumber').val(),
        room_number: $('#roomNumber').val(),
        number_of_night: $('#numberOfNight').val(),
        remarks: $('#remarks').val(),
        stayDetails: stayDetails, // Include stay details
        guests: guests             // Include guest data
    };

    console.log(checkInData); // Log for debugging

    // Implement the AJAX call to save check-in data
    $.ajax({
        type: "POST",
        url: APP_URL + "api/check_in/create.php", // Adjust URL as needed
        contentType: "application/json", // Set the correct content type for JSON
        data: JSON.stringify(checkInData),
        success: function(response) {
            if (response.success) {
                showAlert("Check-in saved successfully!", "success", 1);
                // Optionally, reset the form and clear the guest table
                $("#checkInForm")[0].reset(); // Reset form fields
                $("#guestTable tbody").empty(); // Clear guest table
            } else {
                showAlert("Error: " + response.message, "danger", 1);
            }
        },
        error: function() {
            showAlert("Error on server side!", "danger", 1);
        },
        complete: function() {
            $('#checkInModal').modal('hide'); // Close the modal after submission
        }
    });
});



</script>




