{% extends 'base.html' %}
{% load static %}
{% block content %}
{% include 'profile/header.html' %}
{% include 'profile/drawer.html' %}

<br />
<br />

<br />
<br />

<div id="printableArea">

<div class="container mt-4">
    <h1 class="text-center">کارنامه: {{ reportcard.title }}</h1>
    {% include 'profile/message.html' %}

   

    <div class="card mb-2 shadow-sm p-3 mb-5 bg-white rounded animate__animated animate__delay-0.1s animate__fadeIn">
        <div class="card-body">
            <div >
                {% if reportcard.person.person_private_info.pic %}
                <img src="{{reportcard.person.person_private_info.pic.url}}" alt="تصویر" class="d-flex float-right rounded-circle" width="80px" height="80px">
                {% else %}
                <img src="{% static 'media\users\default_profile.png' %}" alt="تصویر پیش‌فرض" width="80" height="80" class="d-flex float-right rounded-circle" />
                 {% endif %} 
            </div> 
            <h4><strong>نام:</strong> {{ reportcard.person }}</h4>
            <p><strong>حلقه:</strong> {{ reportcard.ring }}</p>
            <p><strong>سرگروه حلقه:</strong> {{ reportcard.ring.major }}</p>
            <p><strong>بازه زمانی:</strong> {{ reportcard.date }}</p>
        </div>
    </div>

    <div class="text-center mt-3">
        <button id="edit-button" class="btn btn-primary no-print">ویرایش نمرات</button>
        <button id="save-button" class="btn btn-success d-none">ذخیره</button>
    </div>

    <h2>جزئیات:</h2>

    <div class="table-responsive animate__animated animate__delay-0.1s animate__fadeIn">
        <table class="table table-bordered bg-light text-center">
            <thead class="bg-light-dark text-dark">
                <tr>
                    <th>ردیف</th>
                    <th>عنوان شاخصه</th>
                    <th>ضریب</th>
                    <th>نمره</th>
                </tr>
            </thead>
            <tbody>
                {% for item in index_details %}
                <tr data-id="{{ item.details.id|default:'' }}" data-index-id="{{ item.index.id }}">
                    <td>{{ forloop.counter }}</td>
                    <td>{{ item.index.title }}</td>
                    <td>{{ item.index.coefficient }}</td>
                    <td>
                        {% if item.details %}
                            <span class="score-text">{{ item.details.score }}</span>
                            <input type="number" class="form-control score-input d-none" value="{{ item.details.score }}">
                        {% else %}
                            <span class="score-text">-</span>
                            <input type="number" class="form-control score-input d-none" value="0">
                        {% endif %}
                    </td>
                </tr>
                {% empty %}
                <tr>
                    <td colspan="5" class="text-center">شاخصه‌ای یافت نشد.</td>
                </tr>
                {% endfor %}
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="3" class="text-right"><strong>معدل کل:</strong></td>
                    <td id="total-average" class="text-center">0.00</td> <!-- اینجا معدل کل نمایش داده می‌شود -->
                </tr>
            </tfoot>
        </table>
    </div>
</div>
</div>
<div class="text-center mt-4">
    <button class="btn btn-primary btn-lg" onclick="printReport()">پرینت کارنامه</button>
</div>
<script>
    function printReport() {
        var printContents = document.getElementById("printableArea").innerHTML;
        var originalContents = document.body.innerHTML;
        document.body.innerHTML = printContents;
        window.print();
        document.body.innerHTML = originalContents;
        location.reload();
    }

    const editButton = document.getElementById("edit-button");
    const saveButton = document.getElementById("save-button");
    const scoreTexts = document.querySelectorAll(".score-text");
    const scoreInputs = document.querySelectorAll(".score-input");

    editButton.addEventListener("click", () => {
        scoreTexts.forEach(scoreText => scoreText.classList.add("d-none"));
        scoreInputs.forEach(scoreInput => scoreInput.classList.remove("d-none"));
        editButton.classList.add("d-none");
        saveButton.classList.remove("d-none");
    });

    saveButton.addEventListener("click", () => {
        const updatedScores = [];

        scoreInputs.forEach((scoreInput) => {
            const scoreValue = scoreInput.value;
            const detailId = scoreInput.closest("tr").dataset.id || null;
            const indexId = scoreInput.closest("tr").dataset.indexId;
            updatedScores.push({
                detailId: detailId,  
                indexId: indexId,
                reportcardId: "{{ reportcard.id }}", 
                score: scoreValue
            });
        });

        fetch("/update-detail-scores/", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "X-CSRFToken": "{{ csrf_token }}"
            },
            body: JSON.stringify({ scores: updatedScores })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                location.reload();
            } else {
                alert("خطا در ذخیره‌سازی نمرات.");
            }
        });
    });

    // محاسبه معدل به طور دائم
    document.addEventListener('DOMContentLoaded', () => {
        const scoreInputs = document.querySelectorAll(".score-input");

        // محاسبه معدل کل به طور دائم
        function calculateAverage() {
            let totalScore = 0;
            let totalCoefficient = 0;

            const rows = document.querySelectorAll("tbody tr");
            rows.forEach((row) => {
                const scoreInput = row.querySelector(".score-input");
                const coefficientCell = row.querySelector("td:nth-child(3)"); // ضریب در ستون سوم

                if (scoreInput && coefficientCell) {
                    const scoreValue = parseFloat(scoreInput.value) || 0;
                    const coefficient = parseFloat(coefficientCell.textContent) || 1;

                    // محاسبه مجموع نمرات و ضریب‌ها
                    totalScore += scoreValue * coefficient;
                    totalCoefficient += coefficient;
                }
            });

            // نمایش معدل کل
            let totalAverage = 0;
            if (totalCoefficient > 0) {
                totalAverage = totalScore / totalCoefficient;
            }

            const totalAverageCell = document.getElementById("total-average");
            totalAverageCell.textContent = totalAverage.toFixed(2); // نمایش معدل کل با 2 رقم اعشاری
        }

        // برای هر بار تغییر نمره‌ها، محاسبه معدل
        scoreInputs.forEach((scoreInput) => {
            scoreInput.addEventListener('input', calculateAverage);
        });

        // محاسبه معدل اولیه بعد از بارگذاری صفحه
        calculateAverage();
    });
</script>

{% endblock %}
