{% load static %}
{% load i18n %}
{% load basefilters %}
{% include 'filter_tags.html' %}
{% if messages %}
    <div class="oh-wrapper">
        {% for message in messages %}
        <div class="oh-alert-container">
            <div class="oh-alert oh-alert--animated {{message.tags}}">
                {{ message }}
            </div>
        </div>
        {% endfor %}
    </div>
{% endif %}
{% if perms.base.view_worktyperequest and rwork_type_assign %}
    {% if perms.base.change_worktyperequest %}
        <span name="" id="archiveRotatingWorkTypeAssignSpan" style="display: none"
            hx-post="{% url 'rotating-shift-work-type-bulk-archive' %}?{{pd}}" hx-target="#view-container" hx-vals="">
        </span>
    {% endif %}
    <div class="oh-checkpoint-badge text-success mb-2" id="selectAllRWorktypes" style="cursor: pointer">
        {% trans "Select All Worktypes" %}
    </div>
    <div class="oh-checkpoint-badge text-secondary mb-2" id="unselectAllRWorktypes" style="cursor: pointer;display: none;">
        {% trans "Unselect All Worktypes" %}
    </div>
    <div class="oh-checkpoint-badge text-info mb-2" id="exportRWorktypes" style="cursor: pointer; display: none">
        {% trans "Export Worktypes" %}
    </div>
    <div class="oh-checkpoint-badge text-danger mb-2" id="selectedShowRWorktypes" style="display: none"></div>
{% endif %}

{% if rwork_type_assign %}
    <div class="oh-table_sticky--wrapper">
        <div class="oh-sticky-dropdown--header">
            <div class="oh-dropdown" x-data="{open: false}">
                <button class="oh-sticky-dropdown_btn " @click="open = !open"><ion-icon name="ellipsis-vertical-sharp"
                        role="img" class="md hydrated" aria-label="ellipsis vertical sharp"></ion-icon></button>
                <div class="oh-dropdown__menu oh-sticky-table_dropdown" x-show="open" @click.outside="open = false">
                    <ul class="oh-dropdown__items" id="roratingWorkTypeCells">
                    </ul>
                </div>
            </div>
        </div>
    </div>
    <div id="rotating-work-type-table" data-table-name="rotating_work_type_tab">
        <!-- start of sticky table -->
        <div class="oh-sticky-table">
            <div class="oh-sticky-table__table oh-table--sortable">
                <div class="oh-sticky-table__thead">
                    <div class="oh-sticky-table__tr">
                        <div class="oh-sticky-table__th" style="width:10px">
                            <div class="centered-div">
                                <input type="checkbox" class="oh-input oh-input__checkbox all-rwork-type"
                                    title='{% trans "Select All" %}' />
                            </div>
                        </div>
                        <div class="oh-sticky-table__th {% if request.sort_option.order == '-employee_id__employee_first_name' %}arrow-up {% elif request.sort_option.order == 'employee_id__employee_first_name' %}arrow-down {% else %} arrow-up-down {% endif %}"
                            hx-target="#view-container"
                            hx-get="{% url 'rotating-work-type-assign-view' %}?{{pd}}&orderby=employee_id__employee_first_name">
                            {% trans "Employee" %}
                        </div>
                        <div data-cell-index="1" data-cell-title='{% trans "Title" %}' class="oh-sticky-table__th">{% trans "Title" %}</div>
                        <div data-cell-index="2" data-cell-title='{% trans "Based On" %}' class="oh-sticky-table__th">{% trans "Based On" %}</div>
                        <div data-cell-index="3" data-cell-title='{% trans "Rotate" %}' class="oh-sticky-table__th">{% trans "Rotate" %}</div>
                        <div data-cell-index="4" data-cell-title='{% trans "Start Date" %}'
                            class="oh-sticky-table__th {% if request.sort_option.order == '-start_date' %}arrow-up {% elif request.sort_option.order == 'start_date' %}arrow-down {% else %} arrow-up-down {% endif %}"
                            hx-target="#view-container"
                            hx-get="{% url 'rotating-work-type-assign-view' %}?{{pd}}&orderby=start_date">
                            {% trans "Start Date" %}
                        </div>
                        <div data-cell-index="5" data-cell-title='{% trans "Current Work Type" %}' class="oh-sticky-table__th">{% trans "Current Work Type" %}</div>
                        <div data-cell-index="6" data-cell-title='{% trans "Next Switch" %}'
                            class="oh-sticky-table__th {% if request.sort_option.order == '-next_change_date' %}arrow-up {% elif request.sort_option.order == 'next_change_date' %}arrow-down {% else %} arrow-up-down {% endif %}"
                            hx-target="#view-container"
                            hx-get="{% url 'rotating-work-type-assign-view' %}?{{pd}}&orderby=next_change_date">{% trans "Next Switch" %}</div>
                        <div data-cell-index="7" data-cell-title='{% trans "Next Work Type" %}' class="oh-sticky-table__th">{% trans "Next Work Type" %}</div>
                        {% if perms.base.change_rotatingworktypeassign or request.user|is_reportingmanager or perms.base.delete_rotatingworktypeassign %}
                            <div class="oh-sticky-table__th  oh-sticky-table__right" style="width:250px">{% trans "Actions" %}</div>
                        {% endif %}
                    </div>
                </div>
                <div class="oh-sticky-table__tbody">
                    {% for rwork_type in rwork_type_assign %}
                    <div class="oh-sticky-table__tr" hx-get="{% url 'rwork-individual-view' rwork_type.id %}?{{pd}}&instances_ids={{assign_ids}}" data-toggle="oh-modal-toggle"
                        data-target="#objectDetailsModal" hx-target="#objectDetailsModalTarget" draggable="true">
                        <div class="oh-sticky-table__sd" onclick="event.stopPropagation();">
                            <div class="centered-div">
                                <input type="checkbox" id="{{rwork_type.id}}" onchange="highlightRow($(this))"
                                    class="oh-input rwork-type-checkbox oh-input__checkbox all-rwork-type-row" />
                            </div>
                        </div>
                        <div class="oh-sticky-table__td">
                            <div class="oh-profile oh-profile--md">
                                <div class="oh-profile__avatar mr-1">
                                    <img src="{{rwork_type.employee_id.get_avatar}}" class="oh-profile__image"
                                        alt="Username" />
                                </div>
                                <span class="oh-profile__name oh-text--dark">{{rwork_type.employee_id}}</span>
                            </div>
                        </div>
                        <div data-cell-index="1" class="oh-sticky-table__td">
                            {{rwork_type.rotating_work_type_id}}
                        </div>
                        <div data-cell-index="2" class="oh-sticky-table__td">{{rwork_type.get_based_on_display}}</div>
                        <div data-cell-index="3" class="oh-sticky-table__td">
                            {% if rwork_type.based_on == 'after' %}
                                {% trans "Rotate after" %} {{rwork_type.rotate_after_day}} {% trans "days" %}
                            {% elif rwork_type.based_on == "weekly" %}
                                {% trans "Weekly every" %} {{rwork_type.rotate_every_weekend}}
                            {% elif rwork_type.based_on == "monthly" %}
                                {% if rwork_type.rotate_every == "1" %}
                                    {% trans "Rotate every" %} {{rwork_type.rotate_every}}{% trans "st day of month" %}
                                {% elif rwork_type.rotate_every == "2" %}
                                    {% trans "Rotate every" %} {{rwork_type.rotate_every}}{% trans "nd day of month" %}
                                {% elif rwork_type.rotate_every == "3" %}
                                    {% trans "Rotate every" %} {{rwork_type.rotate_every}}{% trans "rd day of month" %}
                                {% elif rwork_type.rotate_every == "last" %}
                                    {% trans "Rotate every last day of month" %}
                                {% else %}
                                    {% trans "Rotate every" %} {{rwork_type.rotate_every}}{% trans "th day of month" %}
                                {% endif %}
                            {% endif %}
                        </div>
                        <div data-cell-index="4" class="oh-sticky-table__td dateformat_changer">{{rwork_type.start_date}}
                        </div>
                        <div data-cell-index="5" class="oh-sticky-table__td">{{rwork_type.current_work_type}}</div>
                        <div data-cell-index="6" class="oh-sticky-table__td dateformat_changer">
                            {{rwork_type.next_change_date}}</div>
                        <div data-cell-index="7" class="oh-sticky-table__td">{{rwork_type.next_work_type}}</div>
                        {% if perms.base.change_rotatingworktypeassign or request.user|is_reportingmanager or perms.base.delete_rotatingworktypeassign %}
                            <div class="oh-sticky-table__td  oh-sticky-table__right">
                                <div class="oh-btn-group" onclick="event.stopPropagation()">
                                    {% if perms.base.change_rotatingworktypeassign or request.user|is_reportingmanager %}
                                        <a hx-get="{% url 'rotating-work-type-assign-update' rwork_type.id %}"
                                            hx-target="#objectUpdateModalTarget" data-target="#objectUpdateModal"
                                            data-toggle="oh-modal-toggle" type="button" class="oh-btn oh-btn--light-bkg w-50"
                                            title="{% trans 'Update' %}">
                                            <ion-icon name="create-outline"></ion-icon>
                                        </a>
                                        <a hx-get="{% url 'rotating-work-type-assign-duplicate' rwork_type.id %}"
                                            hx-target="#objectCreateModalTarget" data-target="#objectCreateModal"
                                            data-toggle="oh-modal-toggle" type="button" class="oh-btn oh-btn--light-bkg w-50"
                                            title="{% trans 'Duplicate' %}">
                                            <ion-icon name="copy-outline"></ion-icon>
                                        </a>
                                    {% endif %}
                                    {% if perms.base.change_rotatingworktypeassign or request.user|is_reportingmanager %}
                                        {% if rwork_type.is_active %}
                                            <form hx-confirm="{% trans 'Do you want to archive this rotating work type assign?' %}"
                                                hx-get="{% url 'rotating-work-type-assign-archive' rwork_type.id %}?{{pd}}"
                                                hx-target="#view-container" style="width:100%">
                                                <button class="oh-btn oh-btn--danger-outline oh-btn--light-bkg w-100"
                                                    title="{% trans 'Archive' %}">
                                                    <ion-icon name="archive"></ion-icon>
                                                </button>
                                            </form>
                                        {% else %}
                                            <form hx-confirm="{% trans 'Do you want to un-archive this rotating work type assign?' %}"
                                                hx-get="{% url 'rotating-work-type-assign-archive' rwork_type.id %}?{{pd}}"
                                                hx-target="#view-container" style="width:100%">
                                                <button class="oh-btn oh-btn--danger-outline oh-btn--light-bkg w-100"
                                                    title="{% trans 'Un-Archive' %}">
                                                    <ion-icon name="archive"></ion-icon>
                                                </button>
                                            </form>
                                        {% endif %}
                                    {% endif %}
                                    {% if perms.base.delete_rotatingworktypeassign or request.user|is_reportingmanager %}
                                        <form
                                            hx-confirm="{% trans 'Are you sure you want to delete this rotating work type assign?' %}"
                                            hx-post="{% url 'rotating-work-type-assign-delete' rwork_type.id %}?{{pd}}"
                                            hx-target="#view-container" style="width:100%">
                                            {% csrf_token %}
                                            <button type="submit" class="oh-btn oh-btn--danger-outline oh-btn--light-bkg w-100"
                                                title="{% trans 'Remove' %}">
                                                <ion-icon name="trash-outline"></ion-icon>
                                            </button>
                                        </form>
                                    {% endif %}
                                </div>
                            </div>
                        {% endif %}
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
        <!-- end of sticky table -->

        <!-- start of pagination -->
        <div class="oh-pagination">
            <span class="oh-pagination__page">
                {% trans "Page" %} {{ rwork_type_assign.number }} {% trans "of" %}
                {{rwork_type_assign.paginator.num_pages }}.
            </span>
            <nav class="oh-pagination__nav">
                <div class="oh-pagination__input-container me-3">
                    <span class="oh-pagination__label me-1">{% trans "Page" %}</span>
                    <input type="number" name="page" class="oh-pagination__input" value="{{rwork_type_assign.number}}"
                        hx-get="{% url 'rotating-work-type-assign-view' %}?{{pd}}" hx-target="#view-container" min="1" />
                    <span class="oh-pagination__label">{% trans "of" %} {{rwork_type_assign.paginator.num_pages}}</span>
                </div>
                <ul class="oh-pagination__items">
                    {% if rwork_type_assign.has_previous %}
                    <li class="oh-pagination__item oh-pagination__item--wide">
                        <a hx-target="#view-container" hx-get="{% url 'rotating-work-type-assign-view' %}?{{pd}}&page=1"
                            class="oh-pagination__link">{% trans "First" %}</a>
                    </li>
                    <li class="oh-pagination__item oh-pagination__item--wide">
                        <a hx-target="#view-container"
                            hx-get="{% url 'rotating-work-type-assign-view' %}?{{pd}}&page={{ rwork_type_assign.previous_page_number }}"
                            class="oh-pagination__link">{% trans "Previous" %}</a>
                    </li>
                    {% endif %} {% if rwork_type_assign.has_next %}
                    <li class="oh-pagination__item oh-pagination__item--wide">
                        <a hx-target="#view-container"
                            hx-get="{% url 'rotating-work-type-assign-view' %}?{{pd}}&page={{ rwork_type_assign.next_page_number }}"
                            class="oh-pagination__link">{% trans "Next" %}</a>
                    </li>
                    <li class="oh-pagination__item oh-pagination__item--wide">
                        <a hx-target="#view-container"
                            hx-get="{% url 'rotating-work-type-assign-view' %}?{{pd}}&page={{ rwork_type_assign.paginator.num_pages }}"
                            class="oh-pagination__link">{% trans "Last" %}</a>
                    </li>
                    {% endif %}
                </ul>
            </nav>
        </div>
        <!-- end of pagination -->
    </div>
{% else %}
<!-- start of empty page -->
<div class="oh-404">
    <img style="width: 150px; height: 150px" src="{% static 'images/ui/no-results.png' %}" class="oh-404__image mb-4" />
    <h5 class="oh-404__subtitle">
        {% trans "No search result found!" %}
    </h5>
</div>
<!-- end of empty page -->
{% endif %}


<script src="{% static '/base/actions.js' %}"></script>
<script>
    function addingRWorktypeIds() {
        var ids = JSON.parse($("#selectedRWorktypes").attr("data-ids") || "[]");
        var selectedCount = 0;

        $(".all-rwork-type-row").each(function () {
            if ($(this).is(":checked")) {
                ids.push(this.id);
            } else {
                var index = ids.indexOf(this.id);
                if (index > -1) {
                    ids.splice(index, 1);
                }
            }
        });

        ids = makeRWorktypeListUnique(ids);
        selectedCount = ids.length;

        getCurrentLanguageCode(function (code) {
            languageCode = code;
            var message = rowMessages[languageCode];
            $("#selectedRWorktypes").attr("data-ids", JSON.stringify(ids));
            if (selectedCount === 0) {
                $("#selectedShowRWorktypes").css("display", "none");
                $("#exportRWorktypes").css("display", "none");
                $("#unselectAllRWorktypes").css("display", "none");
            } else {
                $("#exportRWorktypes").css("display", "inline-flex");
                $("#unselectAllRWorktypes").css("display", "inline-flex");
                $("#selectedShowRWorktypes").css("display", "inline-flex");
                $("#selectedShowRWorktypes").text(selectedCount + " - " + message);
            }
        });
    }

    $(document).ready(function () {
        $(".all-rwork-type-row").change(function () {
            var parentTable = $(this).closest(".oh-sticky-table");
            var body = parentTable.find(".oh-sticky-table__tbody");
            var parentCheckbox = parentTable.find(".all-rwork-type");
            parentCheckbox.prop(
                "checked",
                body.find(".all-rwork-type-row:checked").length ===
                body.find(".all-rwork-type-row").length
            );
            addingRWorktypeIds();
        });

        $(".all-rwork-type").change(function () {
            addingRWorktypeIds();
        });

        tickRWorktypeCheckboxes();

        $("#selectAllRWorktypes").click(function () {
            $("#selectedRWorktypes").attr("data-clicked", 1);
            $("#selectedShowRWorktypes").removeAttr("style");
            var savedFilters = JSON.parse(localStorage.getItem("savedFilters"));

            if (savedFilters && savedFilters["filterData"] !== null) {
                var filter = savedFilters["filterData"];
                $.ajax({
                    url: '{% url "r-work-type-select-filter" %}',
                    data: { page: "all", filter: JSON.stringify(filter) },
                    type: "GET",
                    dataType: "json",
                    success: function (response) {
                        var employeeIds = response.employee_ids;
                        var selectedCount = employeeIds.length;
                        for (var i = 0; i < employeeIds.length; i++) {
                            var empId = employeeIds[i];
                            $("#" + empId).prop("checked", true);
                        }
                        $("#selectedRWorktypes").attr(
                            "data-ids",
                            JSON.stringify(employeeIds)
                        );

                        count = makeRWorktypeListUnique(employeeIds);
                        tickRWorktypeCheckboxes(count);
                    },
                    error: function (xhr, status, error) {
                        console.error("Error:", error);
                    },
                });
            } else {
                $.ajax({
                    url: '{% url "r-work-type-select" %}',
                    data: { page: "all" },
                    type: "GET",
                    dataType: "json",
                    success: function (response) {
                        var employeeIds = response.employee_ids;
                        var selectedCount = employeeIds.length;
                        for (var i = 0; i < employeeIds.length; i++) {
                            var empId = employeeIds[i];
                            $("#" + empId).prop("checked", true);
                        }
                        var previousIds = $("#selectedRWorktypes").attr("data-ids");
                        $("#selectedRWorktypes").attr(
                            "data-ids",
                            JSON.stringify(
                                Array.from(
                                    new Set([...employeeIds, ...JSON.parse(previousIds)])
                                )
                            )
                        );
                        count = makeRWorktypeListUnique(employeeIds);
                        tickRWorktypeCheckboxes(count);
                    },
                    error: function (xhr, status, error) {
                        console.error("Error:", error);
                    },
                });
            }
        });

        $("#unselectAllRWorktypes").click(function () {
            $("#selectedRWorktypes").attr("data-clicked", 0);
            $.ajax({
                url: '{% url "r-work-type-select" %}',
                data: { page: "unselect", filter: "{}" },
                type: "GET",
                dataType: "json",
                success: function (response) {
                    var employeeIds = response.employee_ids;
                    for (var i = 0; i < employeeIds.length; i++) {
                        var empId = employeeIds[i];
                        $("#" + empId).prop("checked", false);
                        $(".all-rwork-type").prop("checked", false);
                    }
                    var ids = JSON.parse(
                        $("#selectedRWorktypes").attr("data-ids") || "[]"
                    );
                    var uniqueIds = makeListUnique(ids);
                    toggleHighlight(uniqueIds);
                    $("#selectedRWorktypes").attr("data-ids", JSON.stringify([]));

                    count = [];
                    tickRWorktypeCheckboxes(count);
                },
                error: function (xhr, status, error) {
                    console.error("Error:", error);
                },
            });
        });
    });
    // toggle columns //
    toggleColumns("rotating-work-type-table", "roratingWorkTypeCells");
    localStorageroratingWorkTypeCells = localStorage.getItem(
        "rotating_work_type_tab"
    );
    if (!localStorageroratingWorkTypeCells) {
        $("#roratingWorkTypeCells").find("[type=checkbox]").prop("checked", true);
    }
    $("[type=checkbox]").change();
</script>
