'use strict';

// ======================================================
// GLOBALS
// ======================================================

const attendanceTable =
    document.getElementById('attendanceTable');

const attendanceCards =
    document.getElementById('attendanceCards');

const saveBtn =
    document.getElementById('saveAttendanceBtn');

const loadBtn =
    document.getElementById('loadStudentsBtn');

const attendanceForm =
    document.getElementById('attendanceForm');

// ======================================================
// LOAD STUDENTS
// ======================================================

async function loadStudents() {

    try {

        const classId =
            document.getElementById('class_id').value;

        const attendanceDate =
            document.getElementById(
                'attendance_date'
            ).value;

        if (!classId) {

            alert('Please select class.');

            return;
        }

        if (!attendanceDate) {

            alert('Please select attendance date.');

            return;
        }

        loadBtn.disabled = true;

        loadBtn.innerHTML =
            '<i class="fas fa-spinner fa-spin"></i> Loading...';

        showLoader();

        const response = await fetch(

            `ajax.php?action=load_students&class_id=${encodeURIComponent(classId)}&attendance_date=${encodeURIComponent(attendanceDate)}`

        );

        const data = await response.json();

        hideLoader();

        loadBtn.disabled = false;

        loadBtn.innerHTML =
            '<i class="fas fa-search"></i> Load Students';

        // ==============================================
        // ERROR
        // ==============================================

        if (!data.success) {

            alert(data.message || 'Failed.');

            return;
        }

        // ==============================================
        // HOLIDAY
        // ==============================================

        if (data.is_holiday) {

            attendanceTable.innerHTML = `
                <tr>
                    <td colspan="6" class="text-center p-5">

                        <div class="text-danger mb-2">
                            <i class="fas fa-calendar-times fa-3x"></i>
                        </div>

                        <h5>
                            Holiday
                        </h5>

                        <div>
                            ${escapeHtml(data.holiday_title)}
                        </div>

                    </td>
                </tr>
            `;

            attendanceCards.innerHTML = '';

            saveBtn.style.display = 'none';

            return;
        }

        // ==============================================
        // WEEKLY OFF
        // ==============================================

        if (data.is_weekly_off) {

            attendanceTable.innerHTML = `
                <tr>
                    <td colspan="6" class="text-center p-5">

                        <div class="text-warning mb-2">
                            <i class="fas fa-bed fa-3x"></i>
                        </div>

                        <h5>
                            Weekly Off
                        </h5>

                        <div>
                            ${escapeHtml(data.day_name)}
                        </div>

                    </td>
                </tr>
            `;

            attendanceCards.innerHTML = '';

            saveBtn.style.display = 'none';

            return;
        }

        // ==============================================
        // EMPTY
        // ==============================================

        if (!data.students.length) {

            attendanceTable.innerHTML = `
                <tr>
                    <td colspan="6" class="text-center p-4">
                        No students found.
                    </td>
                </tr>
            `;

            attendanceCards.innerHTML = '';

            saveBtn.style.display = 'none';

            return;
        }

        renderDesktopTable(data);

        renderMobileCards(data);

        saveBtn.style.display = 'inline-block';

    } catch (error) {

        console.error(error);

        alert('Something went wrong.');

        hideLoader();

        loadBtn.disabled = false;

        loadBtn.innerHTML =
            '<i class="fas fa-search"></i> Load Students';
    }
}

// ======================================================
// DESKTOP TABLE
// ======================================================

function renderDesktopTable(data) {

    let html = '';

    data.students.forEach(student => {

        const attendance =
            data.attendance[
                student.student_session_id
            ] || {};

        const status =
            attendance.status || 'Present';

        const remarks =
            attendance.remarks || '';

        html += `
            <tr>

                <td>
                    ${escapeHtml(student.roll_no || '-')}
                </td>

                <td>
                    <strong>
                        ${escapeHtml(student.name)}
                    </strong>
                </td>

                <td>
                    ${escapeHtml(student.section || '-')}
                </td>

                <td>

                    ${renderStatusSelect(
                        student.student_session_id,
                        status
                    )}

                </td>

                <td>

                    <input
                        type="text"
                        class="form-control form-control-sm"

                        name="attendance[${student.student_session_id}][remarks]"

                        value="${escapeHtml(remarks)}"

                        maxlength="255"

                        placeholder="Remarks"
                    >

                </td>

            </tr>
        `;
    });

    attendanceTable.innerHTML = html;
}

// ======================================================
// MOBILE CARDS
// ======================================================

function renderMobileCards(data) {

    let html = '';

    data.students.forEach(student => {

        const attendance =
            data.attendance[
                student.student_session_id
            ] || {};

        const status =
            attendance.status || 'Present';

        const remarks =
            attendance.remarks || '';

        html += `
            <div class="card shadow-sm mb-3 border-0">

                <div class="card-body">

                    <div class="d-flex justify-content-between">

                        <div>

                            <h6 class="font-weight-bold mb-1">

                                ${escapeHtml(student.name)}

                            </h6>

                            <small class="text-muted">

                                Roll :
                                ${escapeHtml(student.roll_no || '-')}

                            </small>

                        </div>

                        <span class="badge badge-info">

                            ${escapeHtml(student.section || '-')}

                        </span>

                    </div>

                    <hr>

                    <div class="mb-3">

                        ${renderStatusSelect(
                            student.student_session_id,
                            status
                        )}

                    </div>

                    <input
                        type="text"

                        class="form-control"

                        name="attendance[${student.student_session_id}][remarks]"

                        value="${escapeHtml(remarks)}"

                        maxlength="255"

                        placeholder="Remarks"
                    >

                </div>

            </div>
        `;
    });

    attendanceCards.innerHTML = html;
}

// ======================================================
// STATUS SELECT
// ======================================================

function renderStatusSelect(id, selected) {

    const statuses = [

        'Present',
        'Late',
        'Leave',
        'Absent'

    ];

    let html = `
        <select
            class="form-control"

            name="attendance[${id}][status]"
        >
    `;

    statuses.forEach(status => {

        html += `
            <option
                value="${status}"

                ${selected === status ? 'selected' : ''}
            >

                ${status}

            </option>
        `;
    });

    html += '</select>';

    return html;
}

// ======================================================
// MARK ALL
// ======================================================

function markAll(status) {

    const selects =
        document.querySelectorAll(
            'select[name*="[status]"]'
        );

    selects.forEach(select => {

        select.value = status;
    });
}

// ======================================================
// SAVE ATTENDANCE
// ======================================================

attendanceForm.addEventListener(

    'submit',

    async function(event) {

        event.preventDefault();

        try {

            saveBtn.disabled = true;

            saveBtn.innerHTML =
                '<i class="fas fa-spinner fa-spin"></i> Saving...';

            const formData =
                new FormData(attendanceForm);

            const response = await fetch(

                'process.php',

                {
                    method : 'POST',
                    body   : formData
                }

            );

            const data = await response.json();

            if (!data.success) {

                alert(data.message || 'Failed.');

                return;
            }

            alert(data.message);

        } catch (error) {

            console.error(error);

            alert('Failed to save attendance.');

        } finally {

            saveBtn.disabled = false;

            saveBtn.innerHTML =
                '<i class="fas fa-save"></i> Save Attendance';
        }
    }
);

// ======================================================
// LOADER
// ======================================================

function showLoader() {

    attendanceTable.innerHTML = `
        <tr>
            <td colspan="6" class="text-center p-5">

                <i class="fas fa-spinner fa-spin fa-2x"></i>

            </td>
        </tr>
    `;

    attendanceCards.innerHTML = `
        <div class="text-center p-5">

            <i class="fas fa-spinner fa-spin fa-2x"></i>

        </div>
    `;
}

function hideLoader() {

    // handled by render
}

// ======================================================
// ESCAPE HTML
// ======================================================

function escapeHtml(text) {

    if (text === null || text === undefined) {

        return '';
    }

    return String(text)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}