$(document).ready(function(){
	const baseUrl = base_url + "/permits/getcomments";
	fetchPermitApplicationComments(); 
    $(".submitPermitCommentBtn").click(function (e) {
        e.preventDefault();
        // let formData = $(this).serialize();

        console.log('heere in permit comments');
        
        var currentStatus = $('permitCurrentStatus').val();

        var commentBody = $('.commentBody').val();
        var applicationCode = $('.applicationCode').val();
        const formData = new FormData();
        formData.append('comment_body', commentBody);
        formData.append('application_code', applicationCode);
        formData.append('application_current_status', currentStatus);

        $.ajax({
            url: base_url + "/permits/addcomment",
            type: "POST",
            data: formData,
            processData: false,
            contentType: false,
            headers: {
                "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
                "Accept": "application/json"
            },
            success: function (response) {
                if (response.success === true) {
                  $.alert("Comment successfully submitted!");
                  fetchPermitApplicationComments(); 
                }
                else{
                  $.alert(response.msg);
                }
                
                console.log(response);
            },
            error: function (xhr) {
                alert("Error: " + xhr.responseText);
            }
        });
    });

    // READ (fetch all)
    function fetchPermitApplicationComments() {
        var applicationCode = $('.applicationCode').val();
        var currentStatus = $('permitCurrentStatus').val();
        const formData = new FormData();

        formData.append('application_code', applicationCode);
        formData.append('application_current_status', currentStatus);

        $.ajax({
            url: baseUrl,
            type: "POST",
            data: formData,
            processData: false,
            contentType: false,
            headers: {
                "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
                "Accept": "application/json"
            },
            success: function (data) {
                console.log("Fetched Comments:", data);
                // $("#permitTableBody").empty();
                populateCommentsTimeline(data)
                // $.each(data, function (index, app) {
                //     $("#permitTableBody").append(`
                //         <tr>
                //             <td>${app.id}</td>
                //             <td>${app.user_id}</td>
                //             <td>${app.application_code}</td>
                //             <td>${app.comment_body ?? ""}</td>
                //             <td>
                //                 <button class="editBtn" data-id="${app.id}">Edit</button>
                //                 <button class="deleteBtn" data-id="${app.id}">Delete</button>
                //             </td>
                //         </tr>
                //     `);
                // });
            },
            error: function (xhr) {
                alert("Failed to fetch applications.");
            }
        });
    }

    // UPDATE
    $(document).on("click", ".editBtn", function () {
        let id = $(this).data("id");
        let updatedData = {
            comment_body: prompt("Enter new comment:")
        };

        $.ajax({
            url: `${baseUrl}/${id}`,
            type: "PUT",
            data: updatedData,
            headers: {
                "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
                "Accept": "application/json"
            },
            success: function (response) {
                alert("Application Updated!");
                console.log(response);
                fetchPermitApplicationComments();
            },
            error: function (xhr) {
                alert("Update failed: " + xhr.responseText);
            }
        });
    });

    // DELETE
    $(document).on("click", ".deleteBtn", function () {
        let id = $(this).data("id");

        if (confirm("Are you sure you want to delete this application?")) {
            $.ajax({
                url: `${baseUrl}/${id}`,
                type: "DELETE",
                headers: {
                    "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content"),
                    "Accept": "application/json"
                },
                success: function (response) {
                    alert("Application Deleted!");
                    console.log(response);
                    fetchPermitApplicationComments();
                },
                error: function (xhr) {
                    alert("Delete failed: " + xhr.responseText);
                }
            });
        }
    });


    // Example AJAX setup assuming your response is stored in a variable called 'response'
    function populateCommentsTimeline(response) {
        const $timeline = $('#commentsTimeline');
        
        // Clear out any old data or loading spinners
        $timeline.empty(); 

        // Check if we have a successful response with data
        if (response.success && response.count > 0) {
            
            // Loop through each comment in the data array
            $.each(response.data, function(index, item) {
                
                // Format the date to look like "19 Jun 2026, 06:55 PM"
                const dateObj = new Date(item.created_date);
                const formattedDate = dateObj.toLocaleDateString('en-GB', { 
                    day: 'numeric', 
                    month: 'short', 
                    year: 'numeric', 
                    hour: '2-digit', 
                    minute: '2-digit',
                    hour12: true
                });

                // Construct the Timeline Item HTML
                const timelineHtml = `
                    <div class="timeline-item">
                        <div class="timeline-icon bg-secondary text-white shadow-sm">
                            <i class="bi bi-chat-text"></i>
                        </div>
                        <div class="timeline-content border rounded p-3 shadow-sm mb-3">
                            <div class="d-flex justify-content-between align-items-center mb-1">
                                <strong class="text-dark">${item.created_by}</strong>
                                <small class="text-muted">${formattedDate}</small>
                            </div>
                            <p class="mb-0 text-dark small">${item.app_comments}</p>
                        </div>
                    </div>
                `;

                // Append it to the container
                $timeline.append(timelineHtml);
            });
            
        } 
        else {
            // Fallback UI if there are no comments yet
            $timeline.append(`
                <div class="text-center text-muted mt-5">
                    <i class="bi bi-inbox fs-1"></i>
                    <p class="mt-2">No history or comments found for this application.</p>
                </div>
            `);
        }
    }
});