{% 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/animate_cdn_css.html" %}
    {% include "cdn_through_html/modal_cdn_css.html" %}
    {% include "cdn_through_html/tabs_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">
                <h3>Manage Principal</h3>
            </div>
            <div class="col text-end">
                <a class="btn btn-success  mb-2 me-4" href="{% url 'module_iam:principal_add' %}">Add Principal</a>
            </div>
        </div>

        <div class="row">
            <div id="tabsSimple" class="col-xl-12 col-12 layout-spacing">
                <div class="statbox widget box box-shadow">
                    <div class="widget-content widget-content-area p-3">
                        <div class="simple-pill">
                            <ul class="nav nav-pills mb-3" id="pills-tab" role="tablist">
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link active" id="pills-tab1-tab" data-bs-toggle="pill" data-bs-target="#pills-tab1" type="button" role="tab" aria-controls="pills-tab1" aria-selected="false">Admin</button>
                                </li>
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link" id="pills-tab2-tab" data-bs-toggle="pill" data-bs-target="#pills-tab2" type="button" role="tab" aria-controls="pills-tab2" aria-selected="true">SubAdmin</button>
                                </li>
                            </ul>
                            <div class="tab-content" id="pills-tabContent">
                                <div class="tab-pane fade active show" id="pills-tab1" role="tabpanel" aria-labelledby="pills-tab1-tab" tabindex="0">
                                    <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 dt-no-sorting" 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;"> # </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;">Record Id </th>
                                                                        <th class="text-center sorting" tabindex="0" aria-controls="style-3" rowspan="1"
                                                                            colspan="1" aria-label="First Name: activate to sort column ascending"
                                                                            style="width: 44.2344px;">Name</th>
                                                                            <th class="text-center sorting" tabindex="0" aria-controls="style-3" rowspan="1"
                                                                            colspan="1" aria-label="Email: activate to sort column ascending"
                                                                            style="width: 44.2344px;">Email</th>
                                                                        <th class="sorting dt-no-sorting" tabindex="0" aria-controls="style-3" rowspan="1" colspan="1"
                                                                            aria-label="Permission: activate to sort column ascending"
                                                                            style="width: 79.7969px;">Permission</th>
                                                                        <th class="sorting dt-no-sorting" tabindex="0" aria-controls="style-3" rowspan="1" colspan="1"
                                                                            aria-label="First Name: activate to sort column ascending"
                                                                            style="width: 79.7969px;">Pricipal_type</th>
                                                                        <th class="sorting" tabindex="0" aria-controls="style-3" rowspan="1" colspan="1"
                                                                            aria-label="First Name: activate to sort column ascending"
                                                                            style="width: 79.7969px;">Active</th>
                                                                        <th class="text-center dt-no-sorting sorting" tabindex="0"
                                                                            aria-controls="style-3" rowspan="1" colspan="1"
                                                                            aria-label="Action: activate to sort column ascending"
                                                                            style="width: 51.625px;">Action</th>
                                                                    </tr>
                                                                </thead>
                                                                <tbody>
                                                                
                                                                </tbody>
                                                            </table>
                                                        </div>
                                                        
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div class="tab-pane fade" id="pills-tab2" role="tabpanel" aria-labelledby="pills-tab2-tab" tabindex="1">
                                    <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="table2_wrapper" class="dataTables_wrapper container-fluid dt-bootstrap4 no-footer">
                                                        
                                                        <div class="table-responsive">
                                                            <table id="table2" 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 dt-no-sorting" 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;"> # </th>
                                                                        <th class="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;"> Record Id </th>
                                                                        <th class="text-center sorting" tabindex="0" aria-controls="style-3" rowspan="1"
                                                                            colspan="1" aria-label="First Name: activate to sort column ascending"
                                                                            style="width: 44.2344px;">Name</th>
                                                                            <th class="text-center sorting" tabindex="0" aria-controls="style-3" rowspan="1"
                                                                            colspan="1" aria-label="Email: activate to sort column ascending"
                                                                            style="width: 44.2344px;">Email</th>
                                                                        <th class="sorting text-center dt-no-sorting" tabindex="0" aria-controls="style-3" rowspan="1" colspan="1"
                                                                            aria-label="Permission: activate to sort column ascending"
                                                                            style="width: 79.7969px;">Permission</th>
                                                                        <th class="sorting dt-no-sorting" tabindex="0" aria-controls="style-3" rowspan="1" colspan="1"
                                                                            aria-label="First Name: activate to sort column ascending"
                                                                            style="width: 79.7969px;">Pricipal_type</th>
                                                                        <th class="sorting" tabindex="0" aria-controls="style-3" rowspan="1" colspan="1"
                                                                            aria-label="First Name: activate to sort column ascending"
                                                                            style="width: 79.7969px;">Active</th>
                                                                        <th class="text-center dt-no-sorting sorting" tabindex="0"
                                                                            aria-controls="style-3" rowspan="1" colspan="1"
                                                                            aria-label="Action: activate to sort column ascending"
                                                                            style="width: 51.625px;">Action</th>
                                                                    </tr>
                                                                </thead>
                                                                <tbody>
                                                                
                                                                </tbody>
                                                            </table>
                                                        </div>
                                                        
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

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



{% endblock content %}

{% block javascript %}

    <!-- include required css 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;


// Entry point
$(document).ready(function() {

    const table1Settings = {
        tableId: '#table',
        MainUrl: "{% url 'module_iam:principal_group_link_list' %}?deleted_flag=False",
        actionUrl: "{% url 'module_iam:principal_group_link_action' %}",
        editUrl: "{% url 'module_iam:principal_edit' pk=0 %}",
        viewArchiveUrl: "{% url 'module_iam:principal_archive' %}"
    };
    
    const table2Settings = {
        tableId: '#table2',
        MainUrl: "{% url 'module_iam:principal_group_link_list_sub' %}?deleted_flag=False",
        actionUrl: "{% url 'module_iam:principal_group_link_action' %}",
        editUrl: "{% url 'module_iam:principal_resource_permission_edit' pk=0 %}",
        viewArchiveUrl: "{% url 'module_iam:principal_archive' %}"
    };

    dataTableInstance = initializeDataTable(table1Settings);
    activeSwitchEventListener(dataTableInstance, table1Settings);

    dataTable2Instance = initialize2DataTable(table2Settings);
    activeSwitchEventListener(dataTable2Instance, table2Settings);
});

// Function to initialize DataTable
function initializeDataTable(tableSettings) {
    return $(tableSettings.tableId).DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: tableSettings.MainUrl,
            type: "GET",
        },
        columns: [
            { data: null, className: "text-center", render: renderCheckbox },
            { data: "id", className: "text-center" },
            { data: "first_name" },
            { data: "email" },
            { 
                data: null, 
                render: function(){
                    return `<ul><span class="badge badge-success">All Access Permission</span></ul>`
                } 
            },
            { data: "principal_type_name", className: "text-center" },
            { data: "is_active", className: "text-center", render: renderSwitch },
            { data: null, className: "text-center",
                render: (data, type, row) => {
                    return renderActions(data, type, row, tableSettings.editUrl);
                } 
            }
        ],
        debug: true,
        columnDefs: [
            {
                targets: [1, 2, 3],
                searchable: true,
                orderable: true
            },
            {
                targets: [0,4,5,-1], // Targeting the last column (action column)
                searchable: false,
                orderable: false
            },
        ],
        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: 'Archive', 
                className: "btn btn-dark buttons-archive", 
                action: function (e, dt, node, config) {
                    archiveAction(e, dt, node, config, tableSettings);
                },
                init: function(api, node, config){
                    $(node).hide();
                } 
            },
            { 
                text: 'View Archive List', 
                className: "btn btn-dark ", 
                action: function () {
                    // Add your action here, e.g., redirect to archive page
                    window.location.href = tableSettings.viewArchiveUrl;
                }
            }
        ],
        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 to initialize DataTable
function initialize2DataTable(tableSettings) {
    return $(tableSettings.tableId).DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: tableSettings.MainUrl,
            type: "GET",
        },
        columns: [
            { data: null, className: "text-center", render: renderCheckbox },
            { data: "id", className: "text-center" },
            { data: "first_name" },
            { data: "email" },
            { 
                data: "permission", 
                render: renderPermission
            },
            { data: "principal_type_name", className: "text-center" },
            { data: "is_active", className: "text-center", render: renderSwitch },
            { data: null, className: "text-center",
                render: (data, type, row) => {
                    return renderActions(data, type, row, tableSettings.editUrl);
                } 
            }
        ],
        debug: true,
        columnDefs: [
            {
                targets: [1, 2, 3],
                searchable: true,
                orderable: true
            },
            {
                targets: [0,4,5,-1], // Targeting the last column (action column)
                searchable: false,
                orderable: false
            },
        ],
        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: 'Archive', 
                className: "btn btn-dark buttons-archive", 
                action: function (e, dt, node, config) {
                    archiveAction(e, dt, node, config, tableSettings);
                },
                init: function(api, node, config){
                    $(node).hide();
                } 
            },
            { 
                text: 'View Archive List', 
                className: "btn btn-dark ", 
                action: function () {
                    // Add your action here, e.g., redirect to archive page
                    window.location.href = tableSettings.viewArchiveUrl;
                }
            }
        ],
        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 renderPermission(data, type, row) {
    if (type === 'display' && row.permission) {
        let html = '<ul><li class="mb-1 d-flex gap-2 p-2">';
        for (const [index, permission] of Object.entries(row.permission)) {
            html += `<span class="badge badge-warning">${permission.name}</span>`;
        }
        html += '</li></ul>';
        return html;
    } else if (type === 'display' && !row.permission) {
        return '<span class="badge badge-danger">No Group assigned</span>';
    } else {
        return '';
    }
}

// Function to reload the DataTable
function reloadDataTable(tableInstance) {
    tableInstance.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 + '" data-id="'+ row.id +'" id="checkbox-' + row.id + '">';
    checkboxHTML += '</div>';
    return checkboxHTML;
}

// Render switch
function renderSwitch(data, type, row) {
    var checkedAttribute = data.toLowerCase() === 'true' ? 'checked' : '';
    var switchHTML = '<div class="switch form-switch-custom switch-inline form-switch-primary">';
    switchHTML += '<input class="switch-input" type="checkbox" role="switch" data-id="'+ row.id +'" id="form-custom-switch-checked' + row.id + '" ' + checkedAttribute + '>';
    switchHTML += '</div>';
    return switchHTML;
}

// Render actions
function renderActions(data, type, row, editUrl) {
    return `
    <ul class="table-controls">
        <li>
            <a href="${ editUrl.replace('0',row.id)}" class="bs-tooltip edit" data-bs-toggle="tooltip" data-bs-placement="top" title="Edit" data-bs-original-title="Edit" aria-label="Edit">
                <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-edit-2 p-1 br-8 mb-1">
                    <path d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"></path>
                </svg>
            </a>
        </li>
    </ul>`;
}

// Callback function for DataTable initialization complete event
function initCompleteCallback(settings) {
    var tableId = '#' + settings.sTableId; // Get the ID of the current table
    var api = this.api();

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

}

// Function to handle archive action
function archiveAction(e, dt, node, config, tableSettings) {
    // Get all the checked checkboxes
    var checkedCheckboxes = dt.$('.archive-checkbox:checked');
    // If no checkboxes are checked, show an error message
    if (checkedCheckboxes.length === 0) {
        Swal.fire({
            title: 'No Record selected',
            text: 'Please select at least one Record 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: tableSettings.actionUrl, // Replace with your archive endpoint
                type: 'POST',
                data: {
                    action: "archive",
                    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(dt);
                },
                error: function(response) {
                    // Show error message
                    Swal.fire({
                        title: 'Error!',
                        text: response.message,
                        icon: 'error',
                        showConfirmButton: true
                    });
                }
            });
        }
    });
}



// Function to add event listener for switch
function activeSwitchEventListener(tableInstance, tableSettings) {
    // Add event listener for switch change event
    tableInstance.on('change', '.switch-input', function() {
        var rowId = $(this).closest('tr').find('.switch-input').data('id');
        var isActive = $(this).prop('checked');
        console.log("calling this data", rowId, isActive)
        // Perform active toggle action for the current user
        $.ajax({
            url: tableSettings.actionUrl, // Replace with your active toggle endpoint
            type: 'POST',
            data: {
                action: "active",
                ids: [rowId],
                active: isActive,
                csrfmiddlewaretoken: '{{csrf_token}}'
             },
            success: function(response) {
                // Show success message
                Swal.fire({
                    title: 'Done!',
                    text: response.msg,
                    icon: 'success',
                    showConfirmButton: true
                });
                // Reload the DataTable after successful toggle
                reloadDataTable();
            },
            error: function(response) {
                // Show error message
                Swal.fire({
                    title: 'Error!',
                    text: response.message,
                    icon: 'error',
                    showConfirmButton: true
                });
            }
        });
    });
}


    </script>
{% endblock %}