<%- include('../common-scripts/dropdown-icon-rotate') %>
<!-- xlsx-->
<script src="/backend/js/xlsx/xlsx.full.min.js"></script>
<script>
const CAN_CHANGE_STATUS = `<%= userInfo.permissions.includes('post_status') %>`;
$(document).ready(function() {
    let activeTabId = ($('.nav-tabs .nav-link.active').attr('href') || '#product')
    .replace('#', '') ||'product';
window.selectedDateRange = '';

    $('a[data-bs-toggle="tab"]').on('shown.bs.tab', function(e) {
        activeTabId = $(e.target).attr('href').replace('#', '');
    reloadActiveTable();
    });

    flatpickr(".flatpickr-input", {
        mode: "range",
        dateFormat: "Y-m-d",
        onClose: function(selectedDates, dateStr, instance) {
            if (selectedDates.length === 2) {
                window.selectedDateRange = dateStr;
                reloadActiveTable();
                toggleResetButton(true);
            }
        }
    });
function getFilterContainer() {
    return $(`.custom-search-filteration[data-parent-container="${activeTabId}-search-filter"]`);
}

function getScopedStatus() {
    return getFilterContainer().find(".status-filter").val() || '';
}
    function reloadActiveTable() {
        switch (activeTabId) {
            case 'product':
                window.productTable.ajax.reload();
                break;
            case 'job':
                window.jobTable.ajax.reload();
                break;
            case 'community':
                window.communityTable.ajax.reload();
                break;
            case 'service':
                window.serviceTable.ajax.reload();
                break;
        }
    }

    $(document).on("change", '.status-filter', function() {
         activeTabId = $(this)
        .closest(".custom-search-filteration")
        .data("parent-container")
        ?.replace("-search-filter", "") || activeTabId;
        reloadActiveTable();
        toggleResetButton(true);
    });


   function toggleResetButton(enable) {
    getFilterContainer().find(".btnResetFileration").prop("disabled", !enable);
}

    $(document).on("click", ".btnResetFileration", function(e) {
        e.preventDefault();
        const $parent = getFilterContainer();

        $parent.find('input[type="text"], input[type="search"], select').val('');
        $parent.find('.flatpickr-input').each(function() {
            if (this._flatpickr) {
                this._flatpickr.clear();
            }
        });

        // if (activeTabId === $parent.data("parent-container").replace("-search-filter", "")) {
        //     window.selectedDateRange = ''};
         window.selectedDateRange = '';
        
        reloadActiveTable();
        toggleResetButton(false);
    });

    const lang = `<%= lang %>`;
    window.productTable = $('.productsTable').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: '/admin/posts?form_type=product',
            type: 'GET',
            dataType: 'json',
            data: function(d) {
                d.dateRange = window.selectedDateRange || '';
                d.status = getScopedStatus();
                return d;
            }
        },
        columns: [
            { 
                data: null,
                render: function(data, type, row, meta) {
                    return meta.row + meta.settings._iDisplayStart + 1;
                }
            },
            {
                data: 'title', 
                render: function(data) {
                    return data;
                }
            },
            {
                data: 'first_name', 
                render: function(data, type, row) {
                    const full_name = `${row?.createdBy?.firstName} ${row?.createdBy?.lastName}`;
                    return `<a href="/admin/platform-user/${row?.createdBy?.id}/view" target="_blank" class="link-underline">
                        ${full_name}
                    </a>`;
                }
            },
            {
                data: 'status',
                render: function(data, type, row) {
                    let statusClass = '';
                    let statusText = '';
                    let statusToggleAction = '';

                    switch (data) {
                        case 'active':
                            statusClass = 'bg-success';
                            statusText = 'Active';
                            statusToggleAction = 'inactive';
                            break;
                        case 'inactive':
                            statusClass = 'bg-danger';
                            statusText = 'Inactive';
                            statusToggleAction = 'archived';
                            break;
                        case 'sold':
                            statusClass = 'bg-warning';
                            statusText = 'Sold';
                            statusToggleAction = 'out_of_stock';
                            break;
                        case 'out_of_stock':
                            statusClass = 'bg-info';
                            statusText = 'Out of Stock';
                            statusToggleAction = 'preorder';
                            break;
                        case 'preorder':
                            statusClass = 'bg-primary';
                            statusText = 'Preorder';
                            statusToggleAction = 'backorder';
                            break;
                        case 'discontinued':
                            statusClass = 'bg-secondary';
                            statusText = 'Discontinued';
                            statusToggleAction = 'archived';
                            break;
                        case 'draft':
                            statusClass = 'bg-light';
                            statusText = 'Draft';
                            statusToggleAction = 'active';
                            break;
                        case 'archived':
                            statusClass = 'bg-dark';
                            statusText = 'Archived';
                            statusToggleAction = 'inactive';
                            break;
                        case 'pending_approval':
                            statusClass = 'bg-warning';
                            statusText = 'Pending Approval';
                            statusToggleAction = 'active';
                            break;
                        case 'backorder':
                            statusClass = 'bg-info';
                            statusText = 'Backorder';
                            statusToggleAction = 'sold';
                            break;
                        default:
                            statusClass = 'bg-secondary';
                            statusText = 'Unknown';
                    }

                    <% if (userInfo.permissions.includes('post_status')) { %>
                        return `<div class="post-status cursor-pointer" data-id="${row.id}" data-status="${data}">
                                    <span class="badge ${statusClass}">${statusText}</span>
                                </div>`;
                    <% } else { %>
                        return `<div>
                                    <span class="badge ${statusClass}">${statusText}</span>
                                </div>`;
                    <% } %>
                }
            },
            { 
                data: 'createdAt',
                render: function(data) {
                    if (!data) return `<%= trans.global.not_available %>`;
                    return new Date(data).toLocaleDateString(`${lang}`);
                }
            },
            {
                data: 'createdAt',
                render: function(data, type, row){
                    let html = '<div class="d-flex gap-1">';
                    <% if (userInfo.permissions.includes('view_post')) { %>
                        html += `<a href="/admin/post/${row.id}/view?form_type=product" class="btn btn-sm btn-info btn-view viewPost">
                                    <i class="fas fa-eye"></i>
                                </a>`;
                    <% } %>
                    html += `</div>`;
                    return html;
                },
                orderable: false
            }
        ],
        responsive: true,
        lengthMenu: [10, 25, 50, 100, 1000, 10000],
        stateSave: false,
        order: [[4, 'desc']],
        language: languageConfig,
    });


    // window.jobTable = $('.jobsTable').DataTable({
    //     processing: true,
    //     serverSide: true,
    //     ajax: {
    //         url: `<%= '/admin/posts?form_type=job' %>`,
    //         type: 'GET',
    //         dataType: 'json',
    //         data: function(d) {
    //             d.dateRange = window.selectedDateRange || '';
    //             d.status = $(document).find('.status-filter').val() || '';
    //             return d;
    //         }
    //     },
    //     columns: [
    //         { 
    //             data: null,
    //             render: function(data, type, row, meta) {
    //                 return meta.row + meta.settings._iDisplayStart + 1;
    //             }
    //         },
    //         {
    //             data: 'title', 
    //             render: function(data) {
    //                 return data;
    //             }
    //         },
    //         {
    //             data: 'first_name', 
    //             render: function(data, type, row) {
    //                 const full_name = `${row?.createdBy?.firstName} ${row?.createdBy?.lastName}`;
    //                 return `<a href="/admin/platform-user/${row?.createdBy?.id}/view" target="_blank" class="link-underline">
    //                     ${full_name}
    //                 </a>`;
    //             }
    //         },
    //         {
    //             data: 'status',
    //             render: function (data, type, row) {
                    
    //                 let statusClass = "";
    //                 let statusText = "";
    //                 let nextStatus = "";

    //                 switch (data) {
    //                     case "active":
    //                         statusClass = "bg-success";
    //                         statusText = "Active";
    //                         nextStatus = "inactive";
    //                         break;

    //                     case "inactive":
    //                         statusClass = "bg-danger";
    //                         statusText = "Inactive";
    //                         nextStatus = "filled";
    //                         break;

    //                     case "filled":
    //                         statusClass = "bg-primary";
    //                         statusText = "Filled";
    //                         nextStatus = "closed";
    //                         break;

    //                     case "expired":
    //                         statusClass = "bg-warning";
    //                         statusText = "Expired";
    //                         nextStatus = "archived";
    //                         break;

    //                     case "archived":
    //                         statusClass = "bg-secondary";
    //                         statusText = "Archived";
    //                         nextStatus = "";
    //                         break;

    //                     case "closed":
    //                         statusClass = "bg-dark";
    //                         statusText = "Closed";
    //                         nextStatus = "";
    //                         break;

    //                     default:
    //                         statusClass = "bg-light text-dark";
    //                         statusText = "Unknown";
    //                 }

    //                 if (CAN_CHANGE_STATUS) {
    //                     return `
    //                         <div class="post-status cursor-pointer"
    //                             data-id="${row.id}"
    //                             data-status="${data}"
    //                             data-next="${nextStatus}">
    //                             <span class="badge ${statusClass}">${statusText}</span>
    //                         </div>
    //                     `;
    //                 }
    //                 return `
    //                     <div>
    //                         <span class="badge ${statusClass}">${statusText}</span>
    //                     </div>
    //                 `;
    //             }
    //         },
    //         { 
    //             data: 'createdAt',
    //             render: function(data) {
    //                 if (!data) return `<%= trans.global.not_available %>`;
    //                 return new Date(data).toLocaleDateString(`${lang}`);
    //             }
    //         },
    //         {
    //             data: 'createdAt',
    //             render: function(data, type, row){
    //                 let html = '<div class="d-flex gap-1">';
    //                 <% if (userInfo.permissions.includes('view_post')) { %>
    //                     html += `<a href="/admin/post/${row.id}/view?form_type=job" class="btn btn-sm btn-info btn-view viewPost">
    //                                 <i class="fas fa-eye"></i>
    //                             </a>`;
    //                 <% } %>
    //                 html += `</div>`;
    //                 return html;
    //             },
    //             orderable: false
    //         }
    //     ],
    //     responsive: true,
    //     lengthMenu: [10, 25, 50, 100, 1000, 10000],
    //     stateSave: false,
    //     order: [[3, 'desc']],
    //     language: languageConfig,
    // });

    // window.communityTable = $('.communitiesTable').DataTable({
    //     processing: true,
    //     serverSide: true,
    //     ajax: {
    //         url: `<%= '/admin/posts?form_type=community' %>`,
    //         type: 'GET',
    //         dataType: 'json',
    //         data: function(d) {
    //             d.dateRange = window.selectedDateRange || '';
    //             d.status = $(document).find('.status-filter').val() || '';
    //             return d;
    //         }
    //     },
    //     columns: [
    //         { 
    //             data: null,
    //             render: function(data, type, row, meta) {
    //                 return meta.row + meta.settings._iDisplayStart + 1;
    //             }
    //         },
    //         {
    //             data: 'title', 
    //             render: function(data) {
    //                 return data;
    //             }
    //         },
    //         {
    //             data: 'first_name', 
    //             render: function(data, type, row) {
    //                 const full_name = `${row?.createdBy?.firstName} ${row?.createdBy?.lastName}`;
    //                 return `<a href="/admin/platform-user/${row?.createdBy?.id}/view" target="_blank" class="link-underline">
    //                     ${full_name}
    //                 </a>`;
    //             }
    //         },
    //         {
    //             data: 'status',
    //             render: function (data, type, row) {
    //                 let statusClass = '';
    //                 let statusText = '';
    //                 let statusToggleAction = '';

    //                 switch (data) {
    //                     case 'active':
    //                         statusClass = 'bg-success';
    //                         statusText = 'Active';
    //                         statusToggleAction = 'inactive';
    //                         break;

    //                     case 'inactive':
    //                         statusClass = 'bg-danger';
    //                         statusText = 'Inactive';
    //                         statusToggleAction = 'upcoming';
    //                         break;

    //                     case 'upcoming':
    //                         statusClass = 'bg-info';
    //                         statusText = 'Upcoming';
    //                         statusToggleAction = 'ongoing';
    //                         break;

    //                     case 'ongoing':
    //                         statusClass = 'bg-primary';
    //                         statusText = 'Ongoing';
    //                         statusToggleAction = 'past';
    //                         break;

    //                     case 'past':
    //                         statusClass = 'bg-warning';
    //                         statusText = 'Past';
    //                         statusToggleAction = 'archived';
    //                         break;

    //                     case 'archived':
    //                         statusClass = 'bg-secondary';
    //                         statusText = 'Archived';
    //                         statusToggleAction = '';
    //                         break;

    //                     default:
    //                         statusClass = 'bg-light text-dark';
    //                         statusText = 'Unknown';
    //                 }
    //                 if (CAN_CHANGE_STATUS) {
    //                     return `
    //                         <div class="post-status cursor-pointer"
    //                             data-id="${row.id}"
    //                             data-status="${data}"
    //                             data-next="${statusToggleAction}">
    //                             <span class="badge ${statusClass}">${statusText}</span>
    //                         </div>
    //                     `;
    //                 }
    //                 return `
    //                     <div>
    //                         <span class="badge ${statusClass}">${statusText}</span>
    //                     </div>
    //                 `;
    //             }
    //         },
    //         { 
    //             data: 'createdAt',
    //             render: function(data) {
    //                 if (!data) return `<%= trans.global.not_available %>`;
    //                 return new Date(data).toLocaleDateString(`${lang}`);
    //             }
    //         },
    //         {
    //             data: 'createdAt',
    //             render: function(data, type, row){
    //                 let html = '<div class="d-flex gap-1">';
    //                 <% if (userInfo.permissions.includes('view_post')) { %>
    //                     html += `<a href="/admin/post/${row.id}/view?form_type=community" class="btn btn-sm btn-info btn-view viewPost">
    //                                 <i class="fas fa-eye"></i>
    //                             </a>`;
    //                 <% } %>
    //                 html += `</div>`;
    //                 return html;
    //             },
    //             orderable: false
    //         }
    //     ],
    //     responsive: true,
    //     lengthMenu: [10, 25, 50, 100, 1000, 10000],
    //     stateSave: false,
    //     order: [[3, 'desc']],
    //     language: languageConfig,
    // });

    window.serviceTable = $('.servicesTable').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: `<%= '/admin/posts?form_type=service' %>`,
            type: 'GET',
            dataType: 'json',
            data: function(d) {
                d.dateRange = window.selectedDateRange || '';
                d.status = getScopedStatus();
                return d;
            }
        },
        columns: [
            { 
                data: null,
                render: function(data, type, row, meta) {
                    return meta.row + meta.settings._iDisplayStart + 1;
                }
            },
            {
                data: 'title', 
                render: function(data) {
                    return data;
                }
            },
            {
                data: 'first_name', 
                render: function(data, type, row) {
                    const full_name = `${row?.createdBy?.firstName} ${row?.createdBy?.lastName}`;
                    return `<a href="/admin/platform-user/${row?.createdBy?.id}/view" target="_blank" class="link-underline">
                        ${full_name}
                    </a>`;
                }
            },
            {
                data: 'status',
                render: function(data, type, row) {
                    let statusClass = '';
                    let statusText = '';
                    let statusToggleAction = '';

                    switch (data) {
                        case 'active':
                            statusClass = 'bg-success';
                            statusText = 'Active';
                            statusToggleAction = 'inactive';
                            break;

                        case 'inactive':
                            statusClass = 'bg-danger';
                            statusText = 'Inactive';
                            statusToggleAction = 'discontinued';
                            break;

                        case 'discontinued':
                            statusClass = 'bg-warning';
                            statusText = 'Discontinued';
                            statusToggleAction = 'archived';
                            break;

                        case 'archived':
                            statusClass = 'bg-secondary';
                            statusText = 'Archived';
                            statusToggleAction = '';
                            break;

                        default:
                            statusClass = 'bg-light text-dark';
                            statusText = 'Unknown';
                    }

                    if (CAN_CHANGE_STATUS) {
                        return `
                            <div class="post-status cursor-pointer"
                                data-id="${row.id}"
                                data-status="${data}"
                                data-next="${statusToggleAction}">
                                <span class="badge ${statusClass}">${statusText}</span>
                            </div>`;
                    }

                    return `
                        <div>
                            <span class="badge ${statusClass}">${statusText}</span>
                        </div>`;
                }
            },
            { 
                data: 'createdAt',
                render: function(data) {
                    if (!data) return `<%= trans.global.not_available %>`;
                    return new Date(data).toLocaleDateString(`${lang}`);
                }
            },
            {
                data: 'createdAt',
                render: function(data, type, row){
                    let html = '<div class="d-flex gap-1">';
                    <% if (userInfo.permissions.includes('view_post')) { %>
                        html += `<a href="/admin/post/${row.id}/view?form_type=service" class="btn btn-sm btn-info btn-view viewPost">
                                    <i class="fas fa-eye"></i>
                                </a>`;
                    <% } %>
                    html += `</div>`;
                    return html;
                },
                orderable: false
            }
        ],
        responsive: true,
        lengthMenu: [10, 25, 50, 100, 1000, 10000],
        stateSave: false,
        order: [[3, 'desc']],
        language: languageConfig,
    });

    /* $(function() {
        const $loader = $(".page-loader");

        function toggleStatus(formType, postId, currentStatus, table) {
            const newStatus = currentStatus === "active" ? "inactive" : "active";
            $loader.removeClass("d-none");

            $.ajax({
                url: `/admin/post/${postId}/status?form_type=${formType}`,
                type: "POST",
                data: { 
                    status: newStatus
                },
                success(response) {
                    $loader.addClass("d-none");
                    if (response.status) {
                        table.ajax.reload();
                        showNotificationPopup(response.message, "success");
                    } else {
                        showNotificationPopup(response.message, "error");
                    }
                },
                error(xhr) {
                    $loader.addClass("d-none");
                    console.error("Error updating status:", xhr);
                    showNotificationPopup(`<%= t(trans.messages.oops_something_went_wrong, {
                        attribute: trans.cruds.POST?.tab_heading?.service?.title_singular
                    }) %>`, 'error');
                }
            });
        }

        const mapping = {
            productsTable: { 
                table: productTable, 
                formType: "product" 
            },
            jobsTable: { 
                table: jobTable, 
                formType: "job" 
            },
            communitiesTable: { 
                table: communityTable, 
                formType: "community" 
            },
            servicesTable: { 
                table: serviceTable, 
                formType: "service" 
            }
        };

        Object.entries(mapping).forEach(([containerClass, { table, formType }]) => {
            $(`.${containerClass}`).off("click.statusToggle").on("click.statusToggle", ".post-status", function() {
                const $btn = $(this);
                const postId = $btn.data("id");
                const currentStatus = $btn.data("status");
                toggleStatus(formType, postId, currentStatus, table);
            });
        });
    }); */

    /* 
    ** For Download 
    */
    $(document).on("click", ".btnExcel, .btnCSV", function(e) {
        e.preventDefault();
        const type = $(this).hasClass("btnExcel") ? "excel" : "csv";
        $(".page-loader").removeClass('d-none');

        let globalSearch = $('.dataTables_filter input[type="search"]').val() || '';
        const url = `/admin/posts`;
        let dataParams = {
            form_type: activeTabId,
            fileType: type,
            request_type: 'download',
            status: $(document).find('.status-filter').val() || '',
            search : {
                value : globalSearch.trim() || ''
            },
        };

        if ((window.selectedDateRange && window.selectedDateRange.trim() !== '') 
            || $('#status-filter').val() 
            || globalSearch.trim()
        ) {
            dataParams.dateRange = window.selectedDateRange || '';
            dataParams.status = $(document).find('.status-filter').val() || '';;
        } else {
            dataParams.start = 0;
            dataParams.length = 1000;
        }


        $.ajax({
            url: url,
            type: 'GET',
            data: dataParams,
            dataType: "json",
            success: function(response) {
                $(".page-loader").addClass('d-none');

                const headers = ["Id", "Title", "Status", "CreatedAt", "PostedBy"];
                const flatData = (response.data.length > 0) ? response.data.map(item => ({
                    Id: item.id,
                    Title: item.title,
                    Status: item.status,
                    CreatedAt: item.createdAt,
                    PostedBy: item.createdBy ? `${item.createdBy.firstName} ${item.createdBy.lastName}` : ''
                })) : [];

                if (type === 'excel') {
                    const worksheet = XLSX.utils.json_to_sheet(flatData, { header: headers });

                    if (flatData.length === 0) {
                        XLSX.utils.sheet_add_aoa(worksheet, [[]], { origin: -1 });
                    }

                    const workbook = XLSX.utils.book_new();
                    XLSX.utils.book_append_sheet(workbook, worksheet, "Posts");
                    const filename = `posts-${activeTabId}.xlsx`;
                    XLSX.writeFile(workbook, filename);
                } else if (type === 'csv') {
                    const worksheet = XLSX.utils.json_to_sheet(flatData, { header: headers });

                    if (flatData.length === 0) {
                        XLSX.utils.sheet_add_aoa(worksheet, [[]], { origin: -1 });
                    }

                    const csv = XLSX.utils.sheet_to_csv(worksheet);
                    const filename = `posts-${activeTabId}.csv`;

                    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
                    if (navigator.msSaveBlob) {
                        navigator.msSaveBlob(blob, filename);
                    } else {
                        const link = document.createElement("a");
                        if (link.download !== undefined) {
                            const url = URL.createObjectURL(blob);
                            link.setAttribute("href", url);
                            link.setAttribute("download", filename);
                            link.style.visibility = 'hidden';
                            document.body.appendChild(link);
                            link.click();
                            document.body.removeChild(link);
                        }
                    }
                }
            },
            error: function(xhr, status, error) {
                $(".page-loader").addClass('d-none');
                showNotificationPopup(`<%= t(trans.messages.oops_something_went_wrong, {
                    attribute: trans.cruds.MODULE.POST
                }) %>`, 'error');
            }
        });
    });


});
</script>