{% extends 'base_structure/layout/base_template.html' %}
{% load static %}
{% block stylesheet %}
<!-- include required css cdn link through html here -->
{% include "cdn_through_html/datatable_cdn_css.html" %}
{% include "cdn_through_html/switches_cdn_css.html" %}
{% include "cdn_through_html/sweetalert2_cdn_css.html" %}

{% endblock %}

{% block content %}


<div class="row layout-top-spacing">
    <div class="col-lg-12">
        <div class="row mb-2">
            <div class="col">
                <a href="{% url 'module_iam:principal_group'%}" style="height: fit-content;width: fit-content;display: inline-block;">
                <h3 class="card-title m-2 d-flex align-items-center gap-2" style="width: fit-content;"><span class="fw-bold material-symbols-outlined">
                    arrow_back
                    </span><span>Principal Group Archive List</span></h3>
                </a>
            </div>
        </div>

        <div class="row layout-spacing">
            <div class="col-lg-12">
                <div class="statbox widget box box-shadow">
                    <div class="widget-content widget-content-area">
                        <div id="table_wrapper" class="dataTables_wrapper container-fluid dt-bootstrap4 no-footer">

                            <div class="table-responsive">
                                <table id="table" class="table style-3 dt-table-hover dataTable" role="grid"
                                    aria-describedby="style-3_info">

                                    <thead>
                                        <tr role="row">
                                            <th class="checkbox-column text-center sorting_asc" tabindex="0"
                                                aria-controls="style-3" rowspan="1" colspan="1" aria-sort="ascending"
                                                aria-label=" Record Id : activate to sort column descending"
                                                style="width: 69.2656px;"> Id </th>
                                            <th class="checkbox-column text-center sorting_asc" tabindex="0"
                                                aria-controls="style-3" rowspan="1" colspan="1" aria-sort="ascending"
                                                aria-label=" Record Id : activate to sort column descending"
                                                style="width: 69.2656px;"> Id </th>
                                            <th class="text-center sorting" tabindex="0" aria-controls="style-3" rowspan="1"
                                                colspan="1" aria-label="Image: activate to sort column ascending"
                                                style="width: 44.2344px;">Group Name</th>
                                            <th class="text-center sorting" tabindex="0" aria-controls="style-3" rowspan="1"
                                                colspan="1" aria-label="Image: activate to sort column ascending"
                                                style="width: 44.2344px;">Role</th>
                                        </tr>
                                    </thead>
                                        <tbody>

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

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


{% endblock content %}

{% block javascript %}
<!-- include required js cdn link through html here -->
{% include "cdn_through_html/datatable_cdn_js.html" %}
{% include "cdn_through_html/datatable_button_cdn_js.html" %}
{% include "cdn_through_html/sweetalert2_cdn_js.html" %}

<script>

// Define DataTable instance
var dataTableInstance;
var mainUrl = "{% url 'module_iam:principal_group_list' %}?deleted_flag=True"
var actionUrl = "{% url 'module_iam:principal_group_action' %}"

// Entry point
$(document).ready(function() {
    
    tableName = $('#table');
    dataTableInstance = initializeDataTable(tableName, mainUrl);
    viewClickEvent(dataTableInstance, viewUrl);
    editClickEvent();
    activeSwitchEventListener()
});

// Function to initialize DataTable
function initializeDataTable(tableName, mainUrl) {
    return tableName.DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: mainUrl,
            type: "GET",
        },
        columns: [
            { data: null, className: "text-center", render: renderCheckbox },
            { data: "id", className: "text-center" },
            { data: "name" },
            { data: "roles", render: renderRole},
        ],
        debug: true,
        columnDefs: [
            { targets: [1, 2], searchable: true, orderable: true },
        ],
        dom: "<'dt--top-section'<'row'<'col-12 col-sm-6 d-flex justify-content-sm-start justify-content-center'l><'col-12 col-sm-6 d-flex justify-content-sm-end justify-content-center mt-sm-0 mt-3'Bf>>>" +
            "<'table-responsive'tr>" +
            "<'dt--bottom-section d-sm-flex justify-content-sm-between text-center'<'dt--pages-count  mb-sm-0 mb-3'i><'dt--pagination'p>>",
            buttons: [
            { 
                text: 'UnArchive', 
                className: "btn btn-dark buttons-unarchive", 
                action: unArchiveAction, 
                init: function(api, node, config){
                    $(node).hide();
                } 
            }
        ],
        oLanguage: {
            oPaginate: { "sPrevious": '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-left"><line x1="19" y1="12" x2="5" y2="12"></line><polyline points="12 19 5 12 12 5"></polyline></svg>', "sNext": '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-arrow-right"><line x1="5" y1="12" x2="19" y2="12"></line><polyline points="12 5 19 12 12 19"></polyline></svg>' },
            sInfo: "Showing page _PAGE_ of _PAGES_",
            sSearch: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-search"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>',
            sSearchPlaceholder: "Search...",
            sLengthMenu: " _MENU_",
        },
        stripeClasses: [],
        lengthMenu: [5, 10, 20, 50],
        pageLength: 10,
        initComplete: initCompleteCallback
    });
}

function renderRole(data, type, row) {
    if (type === 'display' && row.roles) {
        let html = '<ul>';
        for (const [index, role] of Object.entries(row.roles)) {
            html += `<li class="mb-1"><span class="badge badge-primary">${role.name}</span></li>`;
        }
        html += '</ul>';
        return html;
    } else if (type === 'display' && !row.roles) {
        return '<span class="badge badge-danger">No Permission assigned</span>';
    } else {
        return '';
    }
}

// Function to reload the DataTable
function reloadDataTable() {
    dataTableInstance.ajax.reload();
}

// Render checkbox
function renderCheckbox(data, type, row) {
    var checkboxHTML = '<div class="form-check form-check-danger">';
    checkboxHTML += '<input class="form-check-input archive-checkbox" type="checkbox" value="' + row.id + '" id="checkbox-' + row.id + '">';
    checkboxHTML += '</div>';
    return checkboxHTML;
}


// Callback function for DataTable initialization complete event
function initCompleteCallback() {
    var api = this.api();

    // Add event listener for checkbox change
    $('body').on('change', 'input[type="checkbox"]', function () {
        var checkedCount = $('tbody input.archive-checkbox:checked').length;
        var archiveButton = $('.buttons-unarchive');
        archiveButton.toggle(checkedCount > 0);
    });

}


// Function to handle archive action
function unArchiveAction() {
    // Get all the checked checkboxes
    var checkedCheckboxes = $('.archive-checkbox:checked');
    // If no checkboxes are checked, show an error message
    if (checkedCheckboxes.length === 0) {
        Swal.fire({
            title: 'No users selected',
            text: 'Please select at least one user to archive.',
            icon: 'error',
            showConfirmButton: true
        });
        return;
    }
    // Get the IDs of the checked checkboxes
    var ids = checkedCheckboxes.map(function() {
        return $(this).val();
    }).get();
    // Perform archive action with the collected user IDs
    Swal.fire({
        title: 'Are you sure?',
        text: 'Once archived, you will recover it from archive list!',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Yes, archive it!'
    }).then((result) => {
        if (result.isConfirmed) {
            // Perform archive action
            $.ajax({
                url: actionUrl, // Replace with your archive endpoint
                type: 'POST',
                data: {
                    action: "unarchive",
                    ids: ids,
                    csrfmiddlewaretoken: '{{csrf_token}}'
                 },
                success: function(response) {
                    // Show success message
                    Swal.fire({
                        title: 'Done!',
                        text: response.msg,
                        icon: 'success',
                        showConfirmButton: true
                    });
                    // Optionally, you can reload the DataTable after successful archive
                    reloadDataTable();
                },
                error: function(response) {
                    // Show error message
                    Swal.fire({
                        title: 'Error!',
                        text: response.message,
                        icon: 'error',
                        showConfirmButton: true
                    });
                }
            });
        }
    });
}


</script>
{% endblock %}