{% load static i18n %}
{% load i18n %}
{% load widget_tweaks %} {% load basefilters %} {% load pmsfilters %}
{% comment %} <section class="oh-wrapper oh-main__topbar" x-data="{searchShow: false}"> {% endcomment %}
    <div class="oh-main__titlebar oh-main__titlebar--left">
        <h1 class="oh-main__titlebar-title fw-bold">
            {% trans "Employee Key Results" %}
        </h1>
    </div>
{% comment %} </section> {% endcomment %}
{% comment %} <main :class="sidebarOpen ? 'oh-main__sidebar-visible' : ''">
    <div class="oh-wrapper" style="margin-top: 5px;"> {% endcomment %}
        <div class="oh-card">
            {% for krs_list in krs %}
                <div class="oh-accordion-meta">
                    <div class="oh-accordion-meta__item">
                    <div class="oh-accordion-meta__header">
                        <span class="oh-accordion-meta__title pt-3 pb-3">
                        <div class="oh-tabs__input-badge-container">
                            <span
                            class="oh-badge oh-badge--secondary oh-badge--small oh-badge--round mr-1"
                            >
                            {{krs_list.list.paginator.count}}
                            </span>
                            {{krs_list.grouper}}
                        </div>
                        </span>
                    </div>
                    <div class="oh-accordion-meta__body d-none">
                        <div class="oh-sticky-table oh-sticky-table--no-overflow mb-5">
                            <div class="oh-sticky-table__table">
                                <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"
                                                title='{% trans "Select All" %}'
                                                class="oh-input oh-input__checkbox myTicketsAll"
                                                onchange="$(this).closest('.oh-sticky-table').find('.my-tickets-row').prop('checked',$(this).is(':checked')).change();addingTicketsIds()"
                                                />
                                            </div>
                                        </div>
                                        <div class="oh-sticky-table__th">{% trans "Title" %}</div>
                                        <div class="oh-sticky-table__th">{% trans "Start Value" %}</div>
                                        <div class="oh-sticky-table__th">{% trans "Current Value" %}</div>
                                        <div class="oh-sticky-table__th">{% trans "Target Value" %}</div>
                                        <div class="oh-sticky-table__th">{% trans "Progress Percentage" %}</div>
                                        <div class="oh-sticky-table__th">{% trans "Start Date" %}</div>
                                        <div class="oh-sticky-table__th">{% trans "End Date" %}</div>
                                        <div class="oh-sticky-table__th">{% trans "Status" %}</div>
                                        {% if perms.pms.change_employeeobjective or emp_objective|is_manager:request.user %}
                                            <div class="oh-sticky-table__th oh-sticky-table__right">{% trans "Actions" %}</div>
                                        {% endif %}
                                    </div>
                                </div>
                                <div class="oh-sticky-table__tbody">
                                    {% for kr in krs_list.list %}
                                        <div class="oh-sticky-table__tr" data-kr-id="{{kr.id}}"
                                            {% comment %} onclick="window.location.href = `{% url 'ticket-detail' ticket.id %}`" {% endcomment %}
                                        >
                                            <div class="oh-sticky-table__sd
                                                {% if ticket.priority == 'high' %}row-status--red
                                                {% elif ticket.priority == 'medium' %}row-status--orange
                                                {% elif ticket.priority == 'low' %}row-status--blue{% endif %}"
                                                onclick="event.stopPropagation()"

                                            >
                                                <div class="centered-div">
                                                    <input
                                                    type="checkbox"
                                                    id="{{kr.id}}"
                                                    onchange="highlightRow($(this));
                                                            if (!$(this).is(':checked')) {
                                                                $(this).closest('.oh-sticky-table').find('.myTicketsAll').prop('checked',false)
                                                            };addingTicketsIds()"
                                                    class="oh-input holiday-checkbox oh-input__checkbox my-tickets-row"
                                                    />
                                                </div>
                                            </div>
                                            <div class="oh-sticky-table__td">
                                                <span class='d-flex justify-content-between align-items-center'
                                                >
                                                    {{kr.key_result_id}}
                                                    {% comment %} <span title = 'due  {% if ticket.deadline == today %} today {% else %}in {{ticket.deadline|sub:today}}{% endif %}'> {% endcomment %}
                                                        <ion-icon
                                                            class="text-{% if ticket.deadline < today %}danger {% elif ticket.deadline == today %}warning {% else %}success{% endif %}"
                                                            name="time-sharp"
                                                        >
                                                        </ion-icon>
                                                    {% comment %} </span> {% endcomment %}
                                                </span>
                                            </div>
                                            <div class="oh-sticky-table__td">{{kr.start_value}}</div>
                                            <div class="oh-sticky-table__td">
                                                <input
                                                    id = {{kr.id}}
                                                    type="number" class="oh-input p-1"  min="0"
                                                    max="{{kr.target_value}}"
                                                    value="{{kr.current_value}}"
                                                    {% comment %} hx-post="{%url 'employee-keyresult-update-current_value' kr.id %}"
                                                    hx-trigger="change"
                                                    hx-target="#emp_objective_card"  {% endcomment %}
                                                    name="current_value"
                                                    onchange="progress(this)"
                                                />
                                            </div>
                                            <div class="oh-sticky-table__td " data-value="{{kr.target_value}}" >{{kr.target_value}}</div>
                                            <div class="oh-sticky-table__td p-percentage" >{{kr.progress_percentage}}% </div>
                                            <div class="oh-sticky-table__td">{{kr.start_date}}</div>
                                            <div class="oh-sticky-table__td">{{kr.end_date}}</div>
                                            <div class="oh-sticky-table__td">{{kr.get_status_display}}
                                                {% comment %} <select
                                                    id="keyResultStatus" name="key_result_status"
                                                    hx-post="{% url 'employee-keyresult-update-status'  kr.id %}"
                                                    hx-trigger="change" class="oh-table__editable-input w-100"
                                                    hx-target="#krData{{kr.employee_objective_id.id}}">
                                                        {% for value,label in key_result_status %}
                                                            {% if kr.status != value %}
                                                                <option value="{{value}}">{{label}}</option>
                                                            {% else %}
                                                                <option value="{{value}}" selected>{{label}}</option>
                                                            {% endif%}
                                                        {% endfor %}
                                                </select> {% endcomment %}
                                            </div>
                                            {% if perms.pms.change_employeeobjective or emp_objective|is_manager:request.user %}
                                                <div class="oh-sticky-table__td oh-sticky-table__right" onclick="event.stopPropagation()">
                                                    <div class="oh-btn-group">
                                                        <button
                                                            class="oh-btn oh-btn--light-bkg w-50"
                                                            title="{% trans 'Edit' %}"
                                                            data-toggle="oh-modal-toggle"
                                                            data-target="#objectDetailsModal"
                                                            hx-get='{% url "employee-key-result-update" kr.id %}'
                                                            hx-target="#objectDetailsModalTarget"
                                                        >
                                                            <ion-icon name="create-outline"></ion-icon>
                                                        </button>
                                                        <form
                                                            action='{% url "delete-employee-keyresult" kr.id %}?dashboard=True'
                                                            class="w-50"
                                                            onsubmit="return confirm('{% trans 'Are you sure you want to delete	this Key result?' %}');"
                                                            method='post' onclick="event.stopPropagation()" >
                                                            <input type="hidden" name="dashboard" value="True">
                                                            {% csrf_token %}
                                                            <button
                                                                type="submit"
                                                                class="oh-btn oh-btn--light-bkg w-100"
                                                                title="{% trans 'Delete' %}"
                                                            >
                                                                <ion-icon
                                                                    class="me-1 md hydrated"
                                                                    name="trash-outline"
                                                                    role="img"
                                                                    aria-label="trash outline"
                                                                ></ion-icon>
                                                            </button>
                                                        </form>
                                                    </div>
                                                </div>
                                            {% endif %}
                                        </div>
                                    {% endfor %}
                                </div>
                            </div>
                        </div>
                        {% comment %} <div class="oh-pagination">
                            <span class="oh-pagination__page">
                            {% trans "Page" %} {{ krs_list.list.number }} {% trans "of" %} {{ krs_list.list.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="{{krs_list.dynamic_name}}"
                                class="oh-pagination__input"
                                value="{{krs_list.list.number}}"
                                hx-get="{% url 'attendance-ot-search' %}?{{pd}}"
                                hx-target="#ot-table"
                                min="1"
                            />
                            <span class="oh-pagination__label"
                                >{% trans "of" %} {{krs_list.list.paginator.num_pages}}</span
                            >
                            </div>
                            <ul class="oh-pagination__items">
                            {% if krs_list.list.has_previous %}
                            <li class="oh-pagination__item oh-pagination__item--wide">
                                <a
                                hx-target="#ot-table"
                                hx-get="{% url 'attendance-ot-search' %}?{{pd}}&{{krs_list.dynamic_name}}=1"
                                class="oh-pagination__link"
                                >{% trans "First" %}</a
                                >
                            </li>
                            <li class="oh-pagination__item oh-pagination__item--wide">
                                <a
                                hx-target="#ot-table"
                                hx-get="{% url 'attendance-ot-search' %}?{{pd}}&{{krs_list.dynamic_name}}={{ krs_list.list.previous_page_number }}"
                                class="oh-pagination__link"
                                >{% trans "Previous" %}</a
                                >
                            </li>
                            {% endif %} {% if krs_list.list.has_next %}
                            <li class="oh-pagination__item oh-pagination__item--wide">
                                <a
                                hx-target="#ot-table"
                                hx-get="{% url 'attendance-ot-search' %}?{{pd}}&{{krs_list.dynamic_name}}={{ krs_list.list.next_page_number }}"
                                class="oh-pagination__link"
                                >{% trans "Next" %}</a
                                >
                            </li>
                            <li class="oh-pagination__item oh-pagination__item--wide">
                                <a
                                hx-target="#ot-table"
                                hx-get="{% url 'attendance-ot-search' %}?{{pd}}&{{krs_list.dynamic_name}}={{ krs_list.list.paginator.num_pages }}"
                                class="oh-pagination__link"
                                >{% trans "Last" %}</a
                                >
                            </li>
                            {% endif %}
                            </ul>
                            </nav>
                            </div>
                        </div> {% endcomment %}
                    </div>
                </div>
            {% endfor %}
        </div>
    {% comment %} </div> {% endcomment %}
{% comment %} </main> {% endcomment %}
<script src="{% static 'htmx/htmx.min.js' %}"></script>
<script src="{% static 'build/js/web.frontend.min.js' %}"></script>
<script>
    function progress (element) {
        var currentValue = $(element).val()
        keyResultTable = $(element).closest('.oh-sticky-table__tbody');
        keyResultRow = $(element).closest('.oh-sticky-table__tr');
        empKeyResultId = keyResultRow.attr("data-kr-id")
        var targetValue = keyResultRow.find('[data-value]').attr("data-value")

        // Extract only the numeric part using a regular expression
        var numericValue = parseFloat(targetValue.replace(/[^\d.]/g, ''));
        var prgressPercentage = parseInt( currentValue*100/numericValue )
        // Ensure totalProgress doesn't exceed 100
        if (prgressPercentage > 100) {
            prgressPercentage = 100;
            Swal.fire({
                icon: 'error',
                title: 'Oops...',
                text: 'Current Value cannot exceed target value!',
                timer: 3000, // Display the alert for 3 seconds
                timerProgressBar: true, // Show the progress bar
                showConfirmButton: false // Hide the "OK" button
            });
        }
        else{
            $.ajax({
            type: "post",
            url: "{% url 'key-result-current-value-update' %}",
            data: {
                csrfmiddlewaretoken: getCookie("csrftoken"),
                "current_value":currentValue,
                "emp_key_result_id":empKeyResultId

            },
            success: function (response) {
                if (response.type != 'error'){
                keyResultRow.find('.p-percentage').text(prgressPercentage+'%');

                // Iterate over each span and get its text content
                var total_percentage = 0
                var total_kr = 0
                keyResultTable.find('.p-percentage').each(function() {
                    strPercentage =  $(this).text();
                    numPercentage = parseFloat(strPercentage.replace(/[^\d.]/g, ''));
                    total_percentage += numPercentage
                    total_kr += 1
                });
                totalProgress = parseInt( total_percentage/total_kr)
                // Ensure totalProgress doesn't exceed 100
                if (totalProgress > 100) {
                    totalProgress = 100;
                }
                objectiveProgressContainer = $(element).closest('.oh-accordion-meta__item').find('.progress_bar_objective');
                objectiveProgressContainer.html(
                    '<div class="oh-progress" role="progressbar">'+
                    '<div class="oh-progress__bar oh-progress__bar--secondary" style="width: calc('+ totalProgress + '%)"></div>' +
                    '</div>' +
                    '<div class="oh-progress-container__percentage" style="width:50px" name= "key_result_percentage">'+ totalProgress +' %</div>'

                    )
                }
            }
            });
        }
    }
</script>
